以编程方式安装 APK 时出现解析错误

Parse error when programmatically installing an APK

我正在尝试创建一种机制,让应用通过从应用内下载和安装更新的 APK 来自我更新。

我有一个位于服务器上的 APK,如果我只需导航到 URI 然后打开 .apk 文件,它就可以正常安装。当我尝试以编程方式安装它时,问题就来了。我得到 "Parse Error - There was a problem while parsing the package"

目标 phone 允许从未知来源安装并且在 AndroidManifest.xml 我请求这些权限:

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

执行更新的代码取自 Whosebug 上的另一个线程,并略有更改以适应我的特殊情况。

public class UpdateApp extends AsyncTask<String,Void,Void> {
    private Context context;
    public void setContext(Context contextf){
        context = contextf;
    }

    @Override
    protected Void doInBackground(String... arg0) {
        try {
            URL url = new URL(arg0[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            conn.connect();

            File file = context.getCacheDir();
            file.mkdirs();
            File outputFile = new File(file, "update.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = conn.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

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


        } catch (Throwable ex) {
            Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
        }
        return null;
    }
}

我可以尝试什么来理解为什么从代码中安装 APK 时生成错误,但从服务器下载时安装没有问题?

该应用程序正在为 API 23 构建,但完成后需要与 API 24 一起使用。

您必须使您的缓存 apk 文件世界可读。

is.close();

之后

outputFile.setReadable(true, false);

这对我有用 Android 8

startActivity(Intent(Intent.ACTION_VIEW).apply {
    type = "application/vnd.android.package-archive"
    data = FileProvider.getUriForFile(applicationContext, "$packageName.fileprovider", file)
    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
})