Android 7.0之后下载安装apk注意事项

在android 7.0之前版本更新其实相当简单,只需要使用系统下载器就能够完成下载之后安装,但是在7.0之后android升级安全机制,下载安装受到一些限制,以至于安装无反应或无法正常安装。

1、清单文件AndroidManifest.xml application中添加

    android:name="android.support.v4.content.FileProvider"

    android:authorities="${applicationId}.fileprovider"

    android:exported="false"

    android:grantUriPermissions="true">

        android:name="android.support.FILE_PROVIDER_PATHS"

        android:resource="@xml/provider_paths" />

2、资源目录res新建xml文件夹,新建provider_paths.xml

文件内容如下:

        name="external"

        path="." />

3、安装方法如下:

private void installApk() {

File apkfile =new File(saveFileName);

    if (!apkfile.exists()) {

return;

    }

//Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);

    Intent intent =new Intent(Intent.ACTION_VIEW);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        //intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");

        intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");

    }else {

// 声明需要的临时的权限

        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // 第二个参数,即第一步中配置的authorities

// 注意这里, 因为这里容易导错包,如果你是多module开发,一定要使用主Module(即:app)的那个BuildConfig

// 这里说明一下,我上面的清单文件是主Module的,所以这里也要导包导入主module的,我觉得写到被依赖module也是可以的,但要保持一致,这个我没试过)

        Uri contentUri = FileProvider.getUriForFile(context, xx.xxx.BuildConfig.APPLICATION_ID +".fileprovider", apkfile);

        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

    }

startActivity(intent);

}

注:Android8.0、9.0添加请求未知来源应用安装权限

你可能感兴趣的:(Android 7.0之后下载安装apk注意事项)