在android中跳转安装apk
需要先添加权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
在跳转的过程中分为三种情况
- android版本低于等于6.0
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri,"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, requestcode);
- 版本大于等于7.0
Android7.0后添加一个权限机制,androidN对访问文件权限收回,需要使用FileProvider来授权
1.在manifest中添加provider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="独一无二的名字.fileProvider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
2.添加xml指定路径
在manifest中有用resource指引到一个xml目录下的file_paths文件
<paths>
<external-path path="." name="external_storage_root" />
</paths>
这里直接指向根目录,这里顺便贴一下所有路径相关的标签。
(1)files-path:
对应物理路径:getFilesDir()
对应具体路径:/data/user/0/包名/files
(2)cache-path:
对应物理路径:getCacheDir()
对应具体路径:/data/user/0/包名/cache
(3)external-path:
对应物理路径:Environment.getExternalStorageDirectory()
对应具体路径:/storage/emulated/0
(4)external-files-path:
对应物理路径:getExternalFilesDir("名字")
对应具体路径:/storage/emulated/0/Android/data/包名/files/名字
(5)external-cache-path:
对应物理路径:getExternalCacheDir()
对应具体路径:/storage/emulated/0/Android/data/包名/cache
- 版本大于8.0
Android 8.0强化了权限管理,新增了一个未知来源管理列表页面。简单来说就是说你如果要在这个应用里面去安装另一个应用。要去这个未知来源管理列表页面去设置成允许
Android8.0申请权限
if (VERSION.SDK_INT >= 26) {
boolean hasInstallPermission = isHasInstallPermissionWithO(activity);
if (!hasInstallPermission) {
startInstallPermissionSettingActivity(activity, req);
return;
}
}
整体代码:
private void install(Context context, String path, int req) {
File file = new File(path);
if (file == null && !file.exists()) {
return;
}
Uri uri;
if (Build.VERSION.SDK_INT >= 24) {
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".AppFileProvider", file);
} else {
uri = Uri.fromFile(file);
}
if (Build.VERSION.SDK_INT >= 26) {
boolean hasInstallPermission = isHasInstallPermissionWithO(context);
if (!hasInstallPermission) {
startInstallPermissionSettingActivity(context, req);
return;
}
}
Intent intent = new Intent("android.intent.action.VIEW");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (Build.VERSION.SDK_INT >= 24) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
intent.setDataAndType(uri, "application/vnd.android.package-archive");
context.startActivity(intent);
}
@RequiresApi(api = Build.VERSION_CODES.O)
private static boolean isHasInstallPermissionWithO(Context context) {
return context == null ? false : context.getPackageManager().canRequestPackageInstalls();
}
private static void startInstallPermissionSettingActivity(Context context, int req) {
if (context != null) {
Uri uri = Uri.parse("package:" + context.getPackageName());
Intent intent = new Intent("android.settings.MANAGE_UNKNOWN_APP_SOURCES", uri);
((Activity) context).startActivityForResult(intent, req);
}
}