Android7.0系统安装APk,并且出现安装运行时报错的问题解决思路

来源:互联网 发布:yosemite mac 编辑:程序博客网 时间:2024/06/11 22:33

Android 7.0发布,除了带来很多福利,体验增加,也增加了更多的隐私权限,7.0之前的系统安装Apk相当的方便只需要通过Intent即可,例如:


 Intent i = new Intent(Intent.ACTION_VIEW);     i.setDataAndType(Uri.fromFile(apkfile),                    "application/vnd.android.package-archive");            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);startActivity(i);

但是7.0以上的系统,调用这些代码就会报错,因为权限不够,这时候就需要通过ContentProvider来得到权限从而成功安装apk:

1.在AndroidManifest.xml中添加<provider>标签

 <provider            tools:replace="android:authorities"//(很重要不加运行时会报错)            android:name="android.support.v4.content.FileProvider"            android:authorities="包名.fileProvider"            android:grantUriPermissions="true"            android:exported="false"            >            <meta-data                android:name="android.support.FILE_PROVIDER_PATHS"                android:resource="@xml/provider_paths" />        </provider>

2.在res目录下创建 xml文件夹,里面创建xml文件,名字就和前面标签里的一样:

provider_paths.xml文件:

<?xml version="1.0" encoding="utf-8"?><paths xmlns:android="http://schemas.android.com/apk/res/android">    <external-path path="Android/data/com.papa.auction/" name="files_root"/>    <external-path path="." name="external_storage_root" /></paths>

3.在需要安装apk的代码中添加

 Intent i = new Intent(Intent.ACTION_VIEW); // 由于没有在Activity环境下启动Activity,设置下面的标签            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件            Uri apkUri = FileProvider.getUriForFile(mContext, "包名.fileProvider", apkfile);        //添加这一句表示对目标应用临时授权该Uri所代表的文件            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);            i.setDataAndType(apkUri, "application/vnd.android.package-archive");startActivity(i);


有些要注意的地方:

1.AndroidManifest.xml中

  android:authorities="包名.fileProvider"

和代码中

 Uri apkUri = FileProvider.getUriForFile(mContext, "包名.fileProvider", apkfile);
"包名.fileProvider" 这个地方需要一致


2.报错

Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : Attribute provider#android.support.v4.content.FileProvider@authorities value=(包名.fileProvider) from AndroidManifest.xml:150:13-64
is also present at [com.yuyh.imgsel:library:2.0.2] AndroidManifest.xml:28:13-60 value=(包名.provider).
Suggestion: add 'tools:replace="android:authorities"' to <provider> element at AndroidManifest.xml:147:9-157:20 to override.


 在<provider>标签中添加  tools:replace="android:authorities"语句







 
阅读全文
0 0