Android FileProvider应用之间共享数据

Android FileProvider应用之间共享数据

大鱼 12,920 2019-01-08

随着Android版本越来越高,Android官方对用户数据保护力度也越来越大。Android提供FileProvider类来供应用之间共享数据。

像我们的应用安装更新,利用相机拍照然后进行图片处理,或者把文件分享给其他应用,可能都会用到这些知识点

类似于这样

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_storage_root" path="."/>
    <files-path path="." name="files" />
    <cache-path path="." name="cache"  />
</paths>

FileProvider所支持的几种path类型

从Android官方文档上可以看出FileProvider提供以下几种path类型:

 <files-path path="." name="camera_photos" />

该方式提供在应用的内部存储区的文件/子目录的文件。它对应Context.getFilesDir返回的路径:eg:”/data/data/com.richard.simple/files”。

<cache-path name="name" path="path" />

该方式提供在应用的内部存储区的缓存子目录的文件。它对应getCacheDir返回的路径:eg:“/data/data/com.richard.simple/cache”;

 <external-path name="name" path="path" />

该方式提供在外部存储区域根目录下的文件。它对应Environment.getExternalStorageDirectory返回的路径:eg:”/storage/emulated/0”;

 <external-files-path name="name" path="path" />

该方式提供在应用的外部存储区根目录的下的文件。它对应Context.getExternalFilesDir(String) 返回的路径。eg:”/storage/emulated/0/Android/data/com.jph.simple/files”。

 <external-cache-path name="name" path="path" />

该方式提供在应用的外部缓存区根目录的文件。它对应Context.getExternalCacheDir()返回的路径。eg:”/storage/emulated/0/Android/data/com.richard.simple/cache”。

使用方式就是这样

  1. 在AndroidManifest的application下面注册
  <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="me.richard.note.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
  </provider>
  1. 编写path文件
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_storage_root" path="."/>
    <files-path path="." name="files" />
    <cache-path path="." name="cache"  />
</paths>
  1. 调用方式(此处以安装更新为例)
private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", new File(savePath));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            PalmApp.getContext().startActivity(intent);
        }else {
            intent.setDataAndType(Uri.fromFile(new File(savePath)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
    }

savaPath为apk存放的路径,此处放到了应用下files文件夹,也就是

savaPath = getContext().getFilesDir().getAbsolutePath() +"/update.apk"

注意

  1. android:authorities的配置一定要和FileProvider.getUriForFile()方法的第二个参数一致
  2. BuildConfig.APPLICATION_ID不要导错了包,用当前应用下面的BuildConfig