您的位置:首页 > 其它

安卓安装apk时出现“解析程序包时出现错误” 的解决方法

2018-01-11 11:00 591 查看
测试升级的时候发现安卓7.0以上的版本出现升不了级的情况    百度找到答案  

第一步:根据安卓版本适配不同的apk打开方式

File file = new File(apkPath);

//更新包文件Intent
intent = new Intent();

intent.setAction(Intent.ACTION_VIEW);

if (Build.VERSION.SDK_INT
>= 24)

{ // Android7.0及以上版本
Log.d("-->最新apk下载完毕","Android
N及以上版本");

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

Uri contentUri = FileProvider.getUriForFile(context,
"应用包名"
+ ".fileProvider",
file);

//参数二:应用包名+".fileProvider"(和步骤二中的Manifest文件中的provider节点下的authorities对应)

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

} else {

// Android7.0以下版本
Log.d("-->最新apk下载完毕","Android
N以下版本");

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

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);}

context.startActivity(intent);

第二步:在manifest中加入

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

android:authorities="应用包名.fileProvider"
android:exported="false"

android:grantUriPermissions="true">

<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"

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

</provider>

注意:authorities:app的包名.fileProvidergrantUriPermissions:必须是true,

表示授予
URI
临时访问权限exported:必须是falseresource:

中的@xml/file_paths是我们接下来要添加的文件

第三步:添加file_paths文件

<paths>
<files-path
path="Android/data/应用包名/"
name="files_root" />

<files-path
path="."
name="files_path" />

<root-path
path="."
name="root"/>

<external-path
path="."
name="files"/></paths>

说明:path:需要临时授权访问的路径(.代表所有路径)

name:就是你给这个访问路径起个名字

<root-path>这个是偶然间看到一篇文章里写的,忘了收藏了,再找就找不到了。。用途是可以访问存储卡里的数据

<files-path/>代表的根目录:
Context.getFilesDir()

<external-path/>代表的根目录:
Environment.getExternalStorageDirectory()

<cache-path/>代表的根目录:
getCacheDir()

但是这样改了之后又出现了7.0以下升不了级的问题(我用的是机顶盒,提示程序包解析错误,模拟器上可以升级),对比后发现问题

7.0以下的版本改为

try {
Runtime.getRuntime().exec("chmod 777 " + apkfile.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

添加获取权限代码即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐