美文网首页
记一次Android 11上的FileProvider使用

记一次Android 11上的FileProvider使用

作者: 天天小志 | 来源:发表于2022-01-07 18:53 被阅读0次
  1. Android 10开始引入了分区存储的概念,Android 11开始强制执行,也就是以前的时候我们可以任意的访问SD卡下任意目录,Android 11上则不能随意访问,除了/sdcard/Android/data/应用包名目录下的内容外,其它目录都已禁止访问,音乐、视频、下载目录下的文件需要向用户申请权限,允许后才可访问,关于分区存储,不在此文章中赘述,请转至官网:点击跳转,此文章主要介绍使用FileProvider的步骤和示例。
  2. 本文中示例为两个应用,testa负责共享/sdcard/Android/data/com.ttxz.testa/files/config/lala/test.properties文件,testb负责读取此文件,并向此文件中追加写入内容。

1. testa应用设置共享

  • 首页在上目录下创建出相应的文件,并写入部分数据;
File path = getExternalFilesDir("config");
File dirFile = new File(path, "lala");
if (!dirFile.exists()) {
    boolean mkdirs = dirFile.mkdirs();
    Log.e(TAG, "文件目录创建结果:" + mkdirs);
}
File file = new File(dirFile, "test.properties");

if (!file.exists()) {
    boolean fileCreate = false;
    try {
        fileCreate = file.createNewFile();
        Log.e(TAG, "文件创建结果:" + fileCreate);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
ATFProperties atfProperties = new ATFProperties();
try {
    atfProperties.loadPropertiesFromSDCard(file.getAbsolutePath());
    atfProperties.putValue("key1", "value1");
    atfProperties.putValue("key2", "value2");
    atfProperties.putValue("key3", "value3");
    boolean store = atfProperties.store();
    Log.e(TAG, "写入文件内容:" + store);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
  • res目录下创建xml目录,xml目录下创建file_paths.xml
    创建xml
  • file_paths.xml说明
<?xml version="1.0" encoding="utf-8"?>
<paths>
<!--可以配置成根目录整个都可以访问-->
<!--    <external-files-path-->
<!--        name="data_config"-->
<!--        path="/" />-->
<!--或是指定要访问的目录-->
    <external-files-path
        name="data_config"
        path="config/" />
</paths>

paths下标签和路径介绍:

序号 标签名 对应API 对应路径 备注
1 files-path Context.getFilesDir() /data/user/0/com.ttxz.testa/files
2 cache-path Context.getCacheDir() /data/user/0/com.ttxz.testa/cache
3 external-path Environment.getExternalStorageDirectory() /storage/emulated/0
4 external-files-path Context.getExternalFilesDir(String type) /storage/emulated/0/Android/data/com.ttxz.testa/files
5 external-cache-path Context.getExternalCacheDir() /storage/emulated/0/Android/data/com.ttxz.testa/cache
6 external-media-path Context.getExternalMediaDirs() [/storage/emulated/0/Android/media/com.ttxz.testa]

注:上述详细信息参考:官网链接:FileProvider

  • 清单文件provider标签设置
<provider
    android:name="androidx.core.content.FileProvider"<!--可以使用官方提供的,也可以自定义-->
    android:authorities="com.ttxz.testa.fileprovider"<!--一般使用{$包名}.自定义字段-->
    android:exported="false"<!--必须为false,否则报错-->
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"<!--固定值-->
        android:resource="@xml/file_paths"/><!--关联上一步声明的path资源文件-->
</provider>
  • 设置接收testb应用中的Activity请求Uri时的Activity
public class FileProvider extends Activity {
    private static final String TAG = "FileProvider";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        Log.e(TAG, "action:" + intent.getAction());
        //过滤action
        if ("com.ttxz.testa.provider.data".equals(intent.getAction())) {
            //创建要共享的文件
            File imagePath = getExternalFilesDir("config");
            File newFile = new File(imagePath, "lala/test.properties");
            //获取Uri根据要共享的文件,并传入清单文件中定义的authority
            Uri contentUri = androidx.core.content.FileProvider
                    .getUriForFile(this, "com.ttxz.testa.fileprovider", newFile);
            //创建返回Intent对象
            Intent resultIntent = new Intent(Intent.ACTION_SENDTO);
            resultIntent.setData(contentUri);
            //        requestIntent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
            //设置读写权限
            resultIntent.addFlags(
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            setResult(RESULT_OK, resultIntent);
            finish();
        }
    }
}

-清单文件中设置FileProvider外部可访问和action

<activity android:name=".provider.FileProvider" android:exported="true">
    <intent-filter>
        <action android:name="com.ttxz.testa.provider.data" />
    </intent-filter>
</activity>

2. testb应用操作testa应用中的文件

  • 注册registerForActivityResult开启Activity的返回监听
//注意:此方法需要提前调用,和launch方法同时调用时可能会提示未注册该监听
ActivityResultLauncher<Intent> rw = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result){
                      ...
                    }
                });
  • 开启testa应用中的FileProvider,获取要访问的Uri
Intent intent = new Intent("com.ttxz.testa.provider.data");
intent.setClassName("com.ttxz.testa", "com.ttxz.testa.provider.FileProvider");
rw.launch(intent);
  • 收到testa通过setResult方法返回的Uri后,读取文件内容
Intent resultData = result.getData();
Uri uri = resultData.getData();
Log.e(TAG, "uri===" + uri);
BufferedReader br = null;
BufferedWriter bw = null;
try {
    ParcelFileDescriptor fileDescriptor = getContentResolver()
            .openFileDescriptor(uri, "rw");
    FileInputStream fileInputStream = new FileInputStream(
            fileDescriptor.getFileDescriptor());
    br = new BufferedReader(
            new InputStreamReader(fileInputStream));
    String lineData;
    while ((lineData = br.readLine()) != null) {
        Log.e(TAG, "数据:" + lineData);
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}finally {
    try {
        if (br != null) {
            br.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 写入时增加以下即可:
FileOutputStream fos = new FileOutputStream(fileDescriptor.getFileDescriptor());
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.newLine();
bw.write("---------TestB应用写入TestA应用data数据成功----------");
bw.newLine();
bw.write("应用名称=TestB");
bw.flush();

相关文章

网友评论

      本文标题:记一次Android 11上的FileProvider使用

      本文链接:https://www.haomeiwen.com/subject/fdijcrtx.html