/**
* 判断是否是8.0,8.0需要处理未知应用来源权限问题,否则直接安装
*/
private void checkIsAndroidO() {
if (Build.VERSION.SDK_INT >= 26) {
boolean b = getPackageManager().canRequestPackageInstalls();
if (b) {
ToolsUtil.installApk(WelcomeActivity.this, ToolsUtil.getApkDir() + ToolsUtil.getApplicationName() + ".apk");
//安装应用的逻辑(写自己的就可以)
} else {
//设置安装未知应用来源的权限
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
startActivityForResult(intent, 10012);
}
} else {
ToolsUtil.installApk(WelcomeActivity.this, ToolsUtil.getApkDir() + ToolsUtil.getApplicationName() + ".apk");
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10012) {
checkIsAndroidO();
}
}
ToolsUtil
private static boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
private static String getAppDir() {
if (hasSDCard) { // SD卡根目录的hello.text
return Environment.getExternalStorageDirectory() + "/CarSystem";
} else { // 系统下载缓存根目录的hello.text
return Environment.getDownloadCacheDirectory() + "/CarSystem";
}
}
private static String mkdirs(String dir) {
File file = new File(dir);
if (!file.exists()) {
file.mkdirs();
}
return dir;
}
public static String getApkDir() {
String dir = getAppDir() + "/apk/";
return mkdirs(dir);
}
/**
* 安装APK
*
* @param context
* @param apkPath
*/
public static void installApk(Context context, String apkPath) {
if (context == null || TextUtils.isEmpty(apkPath)) {
return;
}
File file = new File(apkPath);
Intent intent = new Intent(Intent.ACTION_VIEW);
//判读版本是否在7.0以上
if (Build.VERSION.SDK_INT >= 24) {
//provider authorities
Uri apkUri = FileProvider.getUriForFile(context, "你的包名", file);
//Granting Temporary Permissions to a URI
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
context.startActivity(intent);
}
7.0以上需要用数据共享AndroidMainifest 配置如下:
<!--数据共享-->
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="你的包名"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_path" />
</provider>
在res文件夹下新建xml文件夹,并建立xml子文件file_path
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="CacheCarSystem" path="CarSystem"/>
</paths>
<files-path/>代表的根目录: Context.getFilesDir()
<external-path/>代表的根目录: Environment.getExternalStorageDirectory()
<cache-path/>代表的根目录: getCacheDir()
path="CarSystem"表示你要共享的文件夹
可参考:http://www.czhzero.com/2016/12/21/how-to-install-apk-on-Android7-0/