应用间共享文件 FileProvider

应用间共享文件 FileProvider

7.0及以上版本,分析文件给其他进程访问的时候,需要使用FileProvider,否则会出现崩溃;
例如:用系统下载器下载apk,然后通过Intent安装。
官网

使用案例

  • 在AndroidManifest创建Provider
      <provider
           android:name="android.support.v4.content.FileProvider"
           android:authorities="com.fanle.fanle.fileprovider"
           android:grantUriPermissions="true"
           android:exported="false">
           <meta-data
               android:name="android.support.FILE_PROVIDER_PATHS"
               android:resource="@xml/file_path" />
       </provider>
  • 创建res/xml/file_path 文件
      <?xml version="1.0" encoding="utf-8"?>
      <paths >
          <external-cache-path name="apk" path="update/"/>
      </paths>
  • 修改安装代码
      public static void installApkExtendApp(Context context, File file){
              if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                  Uri fileURI = FileProvider.getUriForFile(context, "com.fanle.fanle.fileprovider", file);
                  Intent intent = new Intent();
                  intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                  intent.setAction(Intent.ACTION_VIEW);
                  intent.setDataAndType(fileURI, "application/vnd.android.package-archive");
                  context.startActivity(intent);
                  ToastUtils.showShort(context, fileURI.toString());
              }else{
                  installApk(context, file);
              }
          }
原文地址:https://www.cnblogs.com/lipeil/p/6709640.html