安装APK时出现解析错误

5

我在/sdcard/Download创建了一个app-debug.apk文件。

我有以下代码:

@Override
public void onClick(View v){
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/sdcard/Download/" + "app-debug.apk")),
    "application/vnd.android.package-archive");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

我遇到了这个错误:

解析错误

包解析时出现了问题。

我该如何在程序中修改它而不会引发此错误?

2
这条消息意味着 APK 文件已损坏。除非是你自己的文件,否则你无法做太多事情来解决它,如果是你自己的文件,请确保它没有损坏! - Kosh
@k0sh apk文件损坏了吗?但我的apk文件很简单,只显示更新文本。 - 조현욱
也许没有构建成功?为什么不尝试重新构建呢? - Kosh
你是否声明了写入SD卡的清单权限。<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> - Lips_coder
我建议通过 new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) 访问下载文件夹,而不是使用硬编码的位置,因为它在每个设备上的位置都不同。解析错误可能是应用程序找不到apk的结果。因此,apk的名称和位置必须正确。 - Yonjuni
显示剩余4条评论
1个回答

1

对于Android N及以上版本,您应该像这样使用FileProvider

        Uri apkUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        intent.setData(apkUri);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);

在你的 AndroidManifest.xml 文件中:
    <application ...>
    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>
    </application>

然后在res/xml下创建名为provider_paths.xml的文件:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />
</paths>

不要忘记在清单文件中添加权限:

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

使用setFlag()会导致安全异常,而使用addFlag()对我来说是有效的。 - Mrinmoy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接