解決 Android N 上 報錯:android.os.FileUriExposedException

解決 Android N 上 安裝Apk時報錯:android.os.FileUriExposedException: file:///storage/emulated/0/Download/appName-2.3.0.apk exposed beyond app through Intent.getData()

解決方法

1、在AndroidManifest.xml中添加如下代碼
<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="app的包名.fileProvider"
    android:grantUriPermissions="true"
    android:exported="false">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

注意: 
authorities:app的包名.fileProvider 
grantUriPermissions:必須是true,表示授予 URI 臨時訪問權限 
exported:必須是false 
resource:中的@xml/file_paths是我們接下來要添加的文件

2、在res目錄下新建一個xml文件夾,並且新建一個file_paths的xml文件(如下圖)

這裏寫圖片描述

3、打開file_paths.xml文件添加如下內容
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path path="Android/data/app的包名/" name="files_root" />
    <external-path path="." name="external_storage_root" />
</paths>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

path:需要臨時授權訪問的路徑(.代表所有路徑) 
name:就是你給這個訪問路徑起個名字

4、修改代碼適配Android N
Intent intent = new Intent(Intent.ACTION_VIEW);
//判斷是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile);
    intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
startActivity(intent);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

1、首先我們對Android N及以上做判斷; 
2、然後添加flags,表明我們要被授予什麼樣的臨時權限 
3、以前我們直接 Uri.fromFile(apkFile)構建出一個Uri,現在我們使用FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", apkFile); 
4、BuildConfig.APPLICATION_ID直接是應用的包名

參考地址



轉自:http://blog.csdn.net/yy1300326388/article/details/52787853

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章