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

测试升级的时候发现安卓7.0以上的版本出现升不了级的状况    百度找到答案  android

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

File file = new File(apkPath);ide

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

intent.setAction(Intent.ACTION_VIEW);ui

if (Build.VERSION.SDK_INT >= 24) spa

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

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

intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); string

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

//参数二:应用包名+".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);

添加获取权限代码便可