解決用Android N編譯版本引起的android.os.FileUriExposedException
阿新 • • 發佈:2018-11-17
app一般都有檢測新版本自動升級的功能, 一但使用Android NSDK版本來編譯, app啟動安裝新apk的時候會出來FileUriExposedException, 我們需要做的是:
1/修改AndroidManifest.xml, 在application段加入provider內容:
<application android:name=".model.MyApplication" android:allowBackup="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:roundIcon="@mipmap/icon_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.yourcompany.yourapp.fileProvider" android:grantUriPermissions="true" android:exported="false"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
2/在res下建立xml資料夾,並新建file_paths.xml
xml的內容:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path path="Android/data/com.yourcompany.yourapp/" name="files_root" />
<external-path path="." name="external_storage_root" />
</paths>
3/修改你安裝apk的程式碼:
/*Intent i = new Intent(Intent.ACTION_INSTALL_PACKAGE); i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); i.putExtra("EXTRA_RETURN_RESULT", true); ((Activity)context).startActivityForResult(i, REQUEST_CODE);*/ 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); } ((Activity)context).startActivity(intent);