应用间共享文件 FileProvider

应用间共享文件 FileProvider

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

使用案例

  • 在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);
              }
          }
相关文章
相关标签/搜索