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

İan*_*son 7 android auto-update apk

我正在尝试通过从应用程序内下载和安装更高版本的 APK 来创建应用程序自我更新的机制。

我有一个位于服务器上的 APK,如果我只是导航到 URI 然后打开 .apk 文件,它安装得很好。当我尝试以编程方式安装它时,问题就出现了。我收到“解析错误 - 解析包时出现问题”

目标手机允许从未知来源安装,并在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"/>
Run Code Online (Sandbox Code Playgroud)

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

该应用程序是为 API 23 构建的,尽管它在完成后需要与 API 24 一起使用。

use*_*816 6

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

is.close();

outputFile.setReadable(true, false);