java - 下载和运行 .apk 文件时出现解析错误

标签 java android android-intent android-download-manager download-manager

我的应用程序中有一项功能允许用户下载新版本。
但我的问题是当我开始应该开始安装过程的 Intent 时有一条消息:

Parse error. There was a problem parsing the package

这是我的代码

Button button;
String urlApp = "example.com/app.apk"
String fileName = "app.apk";
DownloadManager downloadManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            File file = new File(Environment.DIRECTORY_DOWNLOADS, fileName);
            if (file.exists()){
                boolean deleted = file.delete();
                Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
            }

            downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlApp));
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setTitle("Click to update");
            downloadManager.enqueue(request);
            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        }
    });

}

private void openFile() {
    Intent install = new Intent(Intent.ACTION_VIEW);
    install.setDataAndType(Uri.fromFile(new File(Environment.DIRECTORY_DOWNLOADS+"/"+fileName)),
            "application/vnd.android.package-archive");
    startActivity(install);
}

BroadcastReceiver onComplete = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        openFile();
    }
};

}

它只适用于 .apk 文件,.txt 文件可以正常工作。 logcat 上也没有错误。 删除也不起作用,但这不是我的主要问题。

提前致谢:D

对不起,如果这是一个愚蠢的问题,但这是我第一次使用下载管理器

最佳答案

好吧,我终于解决了

代替:

install.setDataAndType(Uri.fromFile(new File(Environment.DIRECTORY_DOWNLOADS+"/"+fileName)),
        "application/vnd.android.package-archive");

我用过

    install.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/"+fileName)),
            "application/vnd.android.package-archive");

关于java - 下载和运行 .apk 文件时出现解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35397956/

相关文章:

java - 从 web 服务重定向到 jsp 页面

Java - 使用 javax.mail 库更改电子邮件附件的名称

android - 如何在地理 URI Intent 启动的 map 中显示标记?

android - Linux驱动和安卓驱动有什么区别

Android 服务 Activity Intent

java - Android动态TabView使用JSON配置文件

Java Spring Boot 配置和组件

java - 类路径和资源问题

android - 错误 :Failed to find target with hash string 'android-24' in:

android - 为移动响应站点对齐 DIV 中的 2 个按钮