我的应用程序中有一个功能,允许用户下载新版本。
但是我的问题是,当我启动应该启动安装过程的意图时,会显示一条消息:
解析错误。解析包时出现问题
这是我的代码
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文件工作正常。日志猫上既没有错误。删除也不起作用,但这不是我的主要问题。
提前致谢: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");
我之前遇到过同样的问题。
请检查新应用程序版本的最小 API 级别以及所用设备的 API 级别。