Android 6.x 及以下
Android 6.x 及以下使用Uri.fromFile()获取文件的Uri,只需要配置上Action、DataAndType即可隐式启动系统安装器。
/**
Android 6.x 及以下安装 APK
Build.VERSION.SDK_INT>=Build.VERSION_CODES.N
@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
Build.VERSION.SDK_INT>=Build.VERSION_COD