1. 修改AndroidManifest.xml
添加:
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
2. res目录下增加xml目录,xml目录下增加file_paths.xml
内容:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="." />
<files-path name="files-path" path="." />
<cache-path name="cache-path" path="." />
<external-files-path name="external_file_path" path="." />
<external-cache-path name="external_cache_path" path="." />
<root-path name="root-path" path="" />
</paths>
3. 使用代码
void test(Activity activity) {
String filePath = Environment.getExternalStorageDirectory().getPath() + "/Download/test.apk";
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri;
File file = new File(filePath);
if (Build.VERSION.SDK_INT >= 24) {//android 7.0以上
//第二个参数:"app的包名.fileProvider"
uri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID.concat(".FileProvider"), file);
} else {
uri = Uri.fromFile(file);
}
String type = "application/vnd.android.package-archive";
intent.setDataAndType(uri, type);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= 24) {
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
int flag = Intent.FLAG_GRANT_READ_URI_PERMISSION;
activity.grantUriPermission("com.android.packageinstaller", uri, flag);
}
activity.startActivity(intent);
}
网友评论