Android 7.0,8.0上安装Apk

在网上查找到资料,这里做个总结。

原因:日愈严重的病毒,7.0对安全做了优化。具体原因网上有很多资料,就不说了。

正题:

class方法:

public static boolean installAPK(Context context, File apkFile) {
    if (apkFile.exists()) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, context.getApplicationInfo().processName+".install.fileProvider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        if (context.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
            context.startActivity(intent);
        }
        return true;
    } else {
        return false;
    }
}

其中install.fileProvider为mainfests自定义的FileProvider的名称。

配置mainfests

<provider
    android:name=".provider.InstallFileProvider"
    android:authorities="${applicationId}.install.fileProvider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

name:这此是因为有多个provider,所以自定义的provider用于区分。如果你只有一个provider,可以这样写:android.support.v4.content.FileProvider

file_paths.xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="files_root"
        path="Android/data/org.chris.quick/" />
    <external-path
        name="external_storage_root"
        path="." />

</paths>
温馨提示:此种写法可以放在library中,8.0会自动弹出授权界面。

猜你喜欢

转载自blog.csdn.net/Fy993912_chris/article/details/80235394