在安卓7.0之前Uri的創建只需要通過
Uri uri = Uri.fromFile(url);
創建即可。但是在安卓7.0之後做了更改,通過內容提供者包裝uri,具體步驟:1,在AndroidManifest.xml中加入:
<provider
android:authorities="com.android.demo"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
2,xml文件夾中創建file_paths
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="my_images"
path="" />
3,
Uri imageUri = Build.VERSION.SDK_INT >= 24 ? FileProvider.getUriForFile(mContext, "com.android.demo", apkfile) : Uri.fromFile(apkfile);
安卓apk:
File currentFile = new File(filePath);
if (!currentFile.exists()){
return;
}
Uri uri = Build.VERSION.SDK_INT >= 24 ? FileProvider.getUriForFile(ManageCanlendarActivity.this, "com.android.demo", currentFile) : Uri.fromFile(currentFile);
// 核心是下面幾句代碼
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= 24) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
intent.setDataAndType(uri,
"application/vnd.android.package-archive");
startActivity(intent);
注意一定要加上判斷 加上intent.addFlags();要不然會解析包失敗