應用間共享文件 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);
              }
          }
相關文章
相關標籤/搜索