今天和小夥伴聊到關於8.0版本應用更新權限的問題,8.0沒有得到未知應用的安裝權限是不能安裝的,但是,我在oppo8.0上測試的結果卻表明,沒有設置此權限,依然能安裝上,但是中間會增加個關於對未知應用安裝的提示,所以這部分確實不是所有機型都是一樣的,對於8.0的安裝,代碼給各位大佬們附上。
/**
* 下載完成後自動跳到安裝界面
* download_path 爲默認安裝路徑
* @param context
*/
public static void installApk(String versionName, Context context) {
if (TextUtils.isEmpty(versionName)) {
return;
}
File file = new File(Environment.getExternalStorageDirectory(), DOWNLOAD_PATH + "/" + versionName);
///medcare-doctor.apk
Intent mintent = new Intent();
mintent.setAction(Intent.ACTION_VIEW);
mintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String type = getMIMEType(file, context);
//判斷版本是否在7.0以上
if (Build.VERSION.SDK_INT >= 24) {
//provider authorities
//Granting Temporary Permissions to a URI
Uri data = FileProvider.getUriForFile(context, "你的應用包名.fileProvider", file);
mintent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mintent.setDataAndType(data, type);
}else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
boolean hasInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
if (!hasInstallPermission) {
ToastUtil.makeText(MyApplication.getContext(), MyApplication.getContext().getString(R.string.string_install_unknow_apk_note), false);
startInstallPermissionSettingActivity();
return;
}
Uri data = FileProvider.getUriForFile(context, "你的應用包名.fileProvider", file);
mintent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mintent.setDataAndType(data, type);
}else {
mintent.setDataAndType(Uri.fromFile(file), type);
}
context.startActivity(mintent);
}
/**
* 解析apk安裝包,如若不能解析,用戶則手動選擇安裝包
*
* @param f
* @param context
* @return
*/
private static String getMIMEType(File f, Context context) {
String type = "";
String filename = f.getName();
String endname = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
if (endname.equals("apk")) {
type = "application/vnd.android.package-archive";
} else {
type = "*/*";
Toast.makeText(context, "解析包錯誤,請手動選擇安裝包進行安裝...", Toast.LENGTH_SHORT).show();
}
return type;
}
/**
* 跳轉到設置-允許安裝未知來源-頁面
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private void startInstallPermissionSettingActivity() {
//注意這個是8.0新API
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
除此之外,你還需要配置7.0以上就需要配置的fileProvider,這個可以參考其他資料。
感謝一隻懂音樂的碼蟲的博客,附上鍊接:
https://blog.csdn.net/zj_blog/article/details/79897241?tdsourcetag=s_pctim_aiomsg