一、在7.0系統上,版本更新後安裝APP時,出現android.os.FileUriExposedException: 異常
解決方案:
1、在在AndroidManifest.xml中的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_provider" />
</provider>
這裏:
grantUriPermissions:必須是true,表示授予 URI 臨時訪問權限
exported:必須是false
resource:中的@xml/file_paths是我們接下來要添加的文件
authorities:你的包名 + “.fileProvider”
2、在res目錄下新建一個xml文件夾,並且新建一個file_provider的xml文件
<?xml version="1.0" encoding="utf-8"?>
<paths >
<!--1、對應內部內存卡根目錄:Context.getFileDir()-->
<!--<files-path-->
<!--name="int_root"-->
<!--path="/" />-->
<!--2、對應應用默認緩存根目錄:Context.getCacheDir()-->
<!--<cache-path-->
<!--name="app_cache"-->
<!--path="/" />-->
<!--3、對應外部內存卡根目錄:Environment.getExternalStorageDirectory()-->
<!--<external-path-->
<!--name="ext_root"-->
<!--path="pictures/" />-->
<!--4、對應外部內存卡根目錄下的APP公共目錄:Context.getExternalFileDir(String)-->
<!--<external-files-path-->
<!--name="ext_pub"-->
<!--path="/" />-->
<!--5、對應外部內存卡根目錄下的APP緩存目錄:Context.getExternalCacheDir()-->
<!--<external-cache-path-->
<!--name="ext_cache"-->
<!--path="/" />-->
<external-path path="Android/data/com.lckj.eight/" name="files_root" />
<external-path path="." name="external_storage_root" />
</paths>
path:需要臨時授權訪問的路徑(.代表所有路徑)
name:就是你給這個訪問路徑起個名字,沒啥鳥用,用來隱藏真實文件目錄
3、以前,Uri的獲取方式是以file://xxx的樣式來,那麼我們也就是通過Uri.fromFile()來獲取。在7.0系統上需要發送一項content://URI,並授予 URI 臨時訪問權限。進行此授權的最簡單方式是使用FileProvider類。
//判斷是否是AndroidN以及更高的版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, MyApplication.getContext().getPackageName() + ".fileProvider", filePath));
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(filePath, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
startActivity(intent);
這裏需要注意的是:
AndroidManifest.xml處的android:authorities跟mActivity.getPackageName() + “.fileProvider”不一樣會報:
Attempt to invoke virtual method ‘android.content.res.XmlResourceParser android.content.pm.
PackageItemInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)’ on a null object reference異常
二、在7.0系統上獲取getDeviceId()時需要先獲取Manifest.permission.READ_PHONE_STATE)權限,不然也會拋出異常