1. 程式人生 > >Android8.0 安裝apk

Android8.0 安裝apk

/**
 * 判斷是否是8.0,8.0需要處理未知應用來源許可權問題,否則直接安裝
 */
private void checkIsAndroidO() {
    LogUtil.d("getPackageManager:"+filePath);
    if (Build.VERSION.SDK_INT >= 26) {
        boolean b = getPackageManager().canRequestPackageInstalls();
        LogUtil.d("getPackageManager:"+b);
        if (b) {
            installApk(DialogActivity.this,filePath);//安裝應用
        } else {
            //請求安裝未知應用來源的許可權
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.REQUEST_INSTALL_PACKAGES}, 10010);
        }
    } else {
        installApk(DialogActivity.this,filePath);//安裝應用
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    LogUtil.d("requestCode"+requestCode);
    switch (requestCode) {
        case 10010:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                installApk(DialogActivity.this,filePath);//安裝應用
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                startActivityForResult(intent, 10012);
            }
            break;
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 10012:
            checkIsAndroidO();
            break;

        default:
            break;
    }
}
/**
 * 安裝APK
 *
 * @param context
 * @param apkPath
 */
public static void installApk(Context context, String apkPath) {
    if (context == null || TextUtils.isEmpty(apkPath)) {
        return;
    }

    LogUtil.d("apkPath:"+apkPath);
    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, BuildConfig.APPLICATION_ID+".provider", file);
        //Granting Temporary Permissions to a URI
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
    } else {
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    }

    context.startActivity(intent);
}