private void checkInstall() {
boolean haveInstallPermission;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//先获取是否有安装未知来源应用的权限
haveInstallPermission = getPackageManager().canRequestPackageInstalls();
if (!haveInstallPermission) {//没有权限
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("请开启未知来源权限")
.setMessage("应用需要打开安装未知来源应用权限,请去设置中开启权限")
.setCancelable(false)
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
ToastUtil.showToast(MainActivity.this,"您拒绝了权限,应用无法正常使用!");
finish();
}
})
.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
toInStallPermissionSettingActivity();
}
}).create();
alertDialog.show();
return;
}
}
//有权限,进行安装操作
installAPK();
}
protected static final int REQUEST_CODE_INSTALL_PERMISSION = 2;
private void toInStallPermissionSettingActivity() {
Uri packageURI = Uri.parse("package:" + getPackageName());
//注意这个是8.0新API
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
startActivityForResult(intent, REQUEST_CODE_INSTALL_PERMISSION);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK && requestCode == REQUEST_CODE_INSTALL_PERMISSION){
checkInstall();//以防万一,再次检查权限
}
}
private void installAPK() {
String fileName = MyResource.DOWNLOAD_PATH
+ "/app-release.apk";
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//7.0 Android N
//com.xxx.xxx.fileprovider为上述manifest中provider所配置相同
MyLog.i("tag","大于7.0");
uri = FileProvider.getUriForFile(mContext, "zz.bole.songjisn.fileprovider", new File(fileName));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//7.0以后,系统要求授予临时uri读取权限,安装完毕以后,系统会自动收回权限,该过程没有用户交互
} else {//7.0以下
MyLog.i("7.0以下","7.0以下");
uri = Uri.fromFile(new File(fileName));
}
intent.setDataAndType(uri, "application/vnd.android.package-archive");
// 查询所有符合 intent 跳转目标应用类型的应用,注意此方法必须放置在 setDataAndType 方法之后
List
// 然后全部授权
for (ResolveInfo resolveInfo : resolveLists){
String packageName = resolveInfo.activityInfo.packageName;
mContext.grantUriPermission(packageName, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
startActivity(intent);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}catch (ActivityNotFoundException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
android:authorities="你的包名.fileprovider" android:name="android.support.v4.content.FileProvider" android:grantUriPermissions="true" android:exported="false"> android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/filepaths"/>