Android11如何使用文件选择器?
创始人
2024-08-20 11:00:41
0

在Android 11中,FileProvider已经被替代为了DocumentProvider。因此,我们需要用SAF(Storage Access Framework)来实现新的文件选择器。SAF允许用户授权访问外部存储设备中的文件和目录,使得开发人员可以在应用程序中访问这些文件和目录。

以下是使用SAF实现文件选择器的示例代码:

1.添加依赖项:

dependencies {
    implementation 'com.android.support:appcompat-v7:30.0.0'
    implementation 'com.android.support:design:30.0.0'
}

2.在AndroidManifest.xml文件中添加以下内容:


3.在Activity中创建变量和常量:

private static final int READ_REQUEST_CODE = 42;
private static final String MIME_TYPE_IMAGE = "image/*";

4.创建打开文件选择器对话框的方法:

public void openFileSelector() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.setType(MIME_TYPE_IMAGE);
    startActivityForResult(intent, READ_REQUEST_CODE);
}

5.在onActivityResult中处理返回的数据:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        Uri uri = null;
        if (resultData != null) {
            uri = resultData.getData();
            Log.i(TAG, "Uri: " + uri.toString());
            // Do something with the file here
        }
    }
}

6.现在,当用户点击打开文件选择器按钮时,会打开文件选择器对话框。在选择文件后,onActivityResult方法将自动调用,并返回用户选择的文件的URI。您可以使用这个URI来读取或处理选择的文件。

注意事项: 1.在使用SAF时,您的应用程序需要获取外部存储权限。 2.如果您想让用户选择文件和目录,可以使用

相关内容

热门资讯

透视揭露!wepoker养号规... 透视揭露!wepoker养号规律(透视)竞技联盟透视插件,教程指引(讲解有挂)-哔哩哔哩1、进入到竞...
wepoker软件靠谱么!竞技... wepoker软件靠谱么!竞技联盟透视(透视)方法-真是曝光是有挂1、不需要AI权限,帮助你快速的进...
透视揭幕!hhpoker有没有... 透视揭幕!hhpoker有没有透视挂(透视)wepoker到底有没有透视,教程秘籍(有挂透视)-哔哩...
hhpoker德州透视!wep... hhpoker德州透视!wepoker俱乐部辅助(透视)插件-一直详情存在有挂1、在wepoker俱...
透视关于!we-poker有人... 透视关于!we-poker有人玩吗(透视)wepoker怎么破解游戏,教程方案(果真有挂)-哔哩哔哩...
悦扑克脚本!wepoker怎么... 悦扑克脚本!wepoker怎么买辅助(透视)工具-果然曝光真的是有挂1、起透看视 wepoker怎么...
透视详细!wepoker买脚本... 透视详细!wepoker买脚本靠谱吗(透视)wpk透视辅助下载,教程手册(有挂解密)-哔哩哔哩1、让...
wepoker怎么设置透视!w... wepoker怎么设置透视!wepoker手机版辅助(透视)技巧-本来开挂真的有挂1、wepoker...
透视开挂!wepoker辅助器... 透视开挂!wepoker辅助器官方(透视)哈糖大菠萝挂法,教程技法(有挂方法)-哔哩哔哩亲,关键说明...
wpk俱乐部是真的吗!aapo... wpk俱乐部是真的吗!aapoker怎么设置抽水(透视)攻略-果然关于是有挂一、aapoker怎么设...