安卓7.0 安装应用与截图设置FileProvider冲突

来源:互联网 发布:淘宝买东西怎么分期 编辑:程序博客网 时间:2024/06/06 04:29

在安卓7.0中不能和之前一样下载安装了
7.0之前:
File apkFile = new File(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
context.startActivity(intent);

7.0:

//第二个参数要和清单文件中的authorities相对应Uri apkUri =FileProvider.getUriForFile(context, "(这里是自定义的,一般来说写包名).DownloadProvider", new File(file));Intent intent = new Intent(Intent.ACTION_VIEW);// 由于没有在Activity环境下启动Activity,设置下面的标签intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//添加这一句表示对目标应用临时授权该Uri所代表的文件intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);intent.setDataAndType(apkUri, "application/vnd.android.package-archive");context.startActivity(intent);

好了,重点来了,这里的DownloadProvider是个什么东西,很简单就是因为其中导了第三方的截图,已经存在了FileProvider,自己再写的时候就报错了,所以就自己写一个DownloadProvider类继承FileProvicer

public class DownloadProvider extends FileProvider {//里面什么也不用写}

在清单文件中添加

 <provider            android:name=".Controller.Sys.Provider.DownloadProvider"            android:authorities="(这里是自定义的,一般来说写包名).DownloadProvider"            android:exported="false"            android:grantUriPermissions="true">            <meta-data                android:name="android.support.FILE_PROVIDER_PATHS"                android:resource="@xml/file_path"/>        </provider>

file_path:这里要注意一下对应,就是下载的地址

<?xml version="1.0" encoding="utf-8"?><resources xmlns:android="http://schemas.android.com/apk/res/android">    <paths>        <!--对应getExternalCacheDir()-->        <external-cache-path            name="download"            path=""/>    </paths></resources>

这样下载的就可以使用了,而不会报错。
同理可得有了下载,在使用截图同样写一个CropProvider继承FileProvider就可以了,
需要使用多个FileProvider就写多少个继承FileProvider。