美文网首页
Android 7.0后下载后自动打开安装包报错问题

Android 7.0后下载后自动打开安装包报错问题

作者: 重庆李老栓 | 来源:发表于2017-03-03 11:33 被阅读0次

由于Android 7.0后修改了文件访问机制,导致下载apk后直接打开安装会导致程序崩溃。

解决方案如下:

AndroidManifest.xml里面增加

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

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

android:exported="false"

android:grantUriPermissions="true">

android:name="android.support.FILE_PROVIDER_PATHS"

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

</provider>

在资源文件xml文件夹下增加provider_paths文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>

<paths xmlns:android="http://schemas.android.com/apk/res/android">

< external-path name="external_files" 

path="."/>

</paths>

然后打开下载apk的代码如下:

public static voidinstallApk(Context context,File apk) {

Intent install =null;

if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) {

Uri uri = FileProvider.getUriForFile(context,BuildConfig.APPLICATION_ID+

".provider",apk);

install =newIntent(Intent.ACTION_INSTALL_PACKAGE);

install.setData(uri);

install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

}else{

Intent intent =newIntent(Intent.ACTION_VIEW);

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

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

}

context.startActivity(install);

}

重要的是这句install.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);,如果不加,任然无法打开。

相关文章

网友评论

      本文标题:Android 7.0后下载后自动打开安装包报错问题

      本文链接:https://www.haomeiwen.com/subject/ltmvvttx.html