1. 程式人生 > >android 7.0安裝apk失敗

android 7.0安裝apk失敗

7.0中通過FileProvider 來對Content URI讀取授權處理 可參考谷歌官網對FileProvider的說明點選開啟連結

1.在AndroidManifest.xml中定義FileProvider:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
 <application>
  <provider
    android:name="android.support.v4.content.FileProvider"
    android
:authorities="包名.fileProvider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS"
        <!--定義自己的儲存路徑檔案-->
        android:resource="@xml/file_paths" />
  </provider>

</application>
</manifest>
2.在res報下建立xml包並在xml包下建立file_paths.xml檔案:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path path="Android/data/包名/" name="files_root" />
    <external-path path="." name="external_storage_root" />
</paths>

3.在安裝apk的時候檢測並呼叫:


 
//mSavePath :apk的下載到本地的儲存路徑
//fileName:apk的名字
File file = new File(mSavePath, fileName);
Uri downloadFileUri = Uri.fromFile(file);
Intent install = new Intent(Intent.ACTION_VIEW);
if (downloadFileUri != null) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri contentUri = FileProvider.getUriForFile(context, "包名.fileProvider", file);
        install.setDataAndType(contentUri, "application/vnd.android.package-archive");
    } else {
        install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    
    context.getApplicationContext().startActivity(install);

}

 over ! ! !