Nếu bạn targetSdkVersion
là bằng hoặc cao hơn 24, thì bạn cần phải sử dụng FileProvider
thực hiện dành cho Android N và mới hơn Phiên bản Android.
Dưới đây là toàn bộ thực hiện:
// utility method
private void openAppInstaller(Context context, File toInstall) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", toInstall);
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(apkUri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent)
} else {
Uri apkUri = Uri.fromFile(toInstall);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
Thêm nhà cung cấp FileProvider
để AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<application
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
</manifest>
Và tạo provider_paths.xml
dưới nguồn xml.
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
Thông tin thêm về cấu hình FileProvider bạn có thể đọc here và here.
Tất cả tín dụng đi đến @just_user vì câu trả lời của tôi dựa trên his reply.
Như tôi đã đề cập trong câu trả lời của mình, hãy sử dụng "gói lưu trữ" chứ không phải "package_archive". Hy vọng điều này giải quyết được ActivityNotFoundException. – Karthik