記錄Android7.0下載APK自動安裝出錯的問題
Android系統(tǒng)自從6.0部分權限需要去動態(tài)申請之后,Android在7.0在訪問私有錄被限制。
如果一項包含文件file:// URI類型 的 Intent 離開你的應用,則會報出異常。這項權限的變更將意味著你無法通過File API訪問手機存儲上的數(shù)據(jù)了,基于File API的一些文件瀏覽器等也將受到很大的影響.

即類似于這樣的獲取file的uri的Api在7.0版本之前都是可以正常使用的,但是在7.0之后的版本就不能在這樣去實現(xiàn)了,只能通過FileProvider類去實現(xiàn)。
在Android8.0Oreo中,Google移除掉了容易被濫用的“允許位置來源”應用的開關,在安裝第三方來源的應用的時候需要手動的去打開允許安裝未知來源的開關。
適配代碼:
這個是安裝APK的代碼:
Intent intent = new Intent(Intent.ACTION_VIEW);File file = new File(filePath);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", file);????intent.setDataAndType(contentUri, "application/vnd.android.package-archive");} else {????intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);????intent.setDataAndType(Uri.fromFile(file),????????????"application/vnd.android.package-archive");}context.startActivity(intent);
這個是8.0判斷時候有安裝第三方來源的代碼判斷:
boolean flag = ?context.getPackageManager().canRequestPackageInstalls();
如果flag = true的話即允許安裝第三方來源的,否則則不允許。
另外FileProvider還要在AndroidManifest.xml添加:
<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>
這個file_paths文件要在res目錄新建一個xml的文件夾

內(nèi)容如下:
<?xml version="1.0" encoding="utf-8"?><paths xmlns:android="http://schemas.android.com/apk/res/android">????<external-path????????name="office"????????path="." /></paths>
一切就都大功告成了。嘿嘿!!!
(友情提示一下:上面的BuildConfig是你自己項目下的BuildConfig,不要導錯包哦,嘿嘿?。。。?/p>