Android 6.x 及以下
Android 6.x 及以下使用Uri.fromFile()
获取文件的Uri
,只需要配置上Action
、DataAndType
即可隐式启动系统安装器。
/**
* Android 6.x 及以下安装 APK
*
* @param context 上下文
* @param file 要安装的APK文件对象
*/
public void installApk6x(Context context, File file) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");// APK的MimeType
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 在新栈中启动
context.startActivity(intent);
}
Android 7.x
Android 7.0 起,引入了 FileProvider,APP需要手动配置对外暴露的目录并通过FileProvider.getUriForFile()
获取文件的Uri
。
/**
* Android 7.x 安装APK,需要配置FileProvider
*
* @param context 上下文
* @param file 要安装的APK文件
* @param authority FileProvider配置的authority
*/
public void installApk7x(Context context, File file, String authority) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
Uri uri = FileProvider.getUriForFile(context, authority, file); // 通过FileProvider获取Uri
intent.setDataAndType(uri, "application/vnd.android.package-archive");// APK的MimeType
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 在新栈中启动
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 授权读取URI权限
context.startActivity(intent);
}
Android 8.x 及以上
Developer changes
To take advantage of this new behavior, developers of apps that require the ability to download and install other apps via the Package Installer may need to make some changes.
If an app uses a targetSdkLevel
of 26
or above and prompts the user to install other apps, the manifest file needs to include the REQUEST_INSTALL_PACKAGES
permission:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
Apps that haven't declared this permission cannot install other apps, a handy security protection for apps that have no intention of doing so.
You can choose to pre-emptively direct your users to the Install unknown apps permission screen using the ACTION_MANAGE_UNKNOWN_APP_SOURCES
Intent action.
You can also query the state of this permission using the PackageManager canRequestPackageInstalls()
API.
官方文档:Making it safer to get apps on Android O
/**
* Android 8.x 及以上安装APK,除配置FileProvider外,
* 还需要在清单文件中添加REQUEST_INSTALL_PACKAGES权限。
*
* @param context 上下文
* @param file 要安装的APK文件
* @param authority FileProvider配置的authority
*/
public void installApk7x(Context context, File file, String authority) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
Uri uri = FileProvider.getUriForFile(context, authority, file); // 通过FileProvider获取Uri
intent.setDataAndType(uri, "application/vnd.android.package-archive");// APK的MimeType
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 在新栈中启动
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 授权读取URI权限
context.startActivity(intent);
}
网友评论