我已经创建了一个android应用程序,如果有任何新版本发布,它会从服务器上通过使用内置的“下载管理器”自动开始下载.为了完成下载后的自动安装,我创建了一个广播接收器,通知下载已完成并完成,然后我开始安装它.在我停留在应用程序中并且不关闭它时,它工作正常.但是我的问题是我关闭应用程序时.因此,完成下载后,我想自动安装它.但我不会发生.我应该为这个问题做什么?
private void download(String link) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(link));
request.setDescription("new version");
request.setTitle("app name");
request.setMimeType("application/vnd.android.package-archive");
request.setDestinationInExternalFilesDir(getApplicationContext(), Environment.DIRECTORY_DOWNLOADS, "myapk.apk");
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
downloadID = dm.enqueue(request);
br = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
String action = i.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadID);
Cursor downloadResult = dm.query(query);
if (downloadResult.moveToFirst()) {
int statusColumnIndex = downloadResult.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = downloadResult.getInt(statusColumnIndex);
if (status == DownloadManager.STATUS_SUCCESSFUL) {
//download completed successfully
int localFileNameId = downloadResult.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
String downloadPathFile = downloadResult.getString(localFileNameId);
String downloadPathDir = downloadPathFile.substring(0, downloadPathFile.lastIndexOf("/") + 1);
String downloadName = downloadPathFile.substring(downloadPathFile.lastIndexOf("/") + 1);
Log.i("name =", downloadName);
File file = new File(downloadPathDir);
File[] files = file.listFiles();
for (File f : files) {
if (f.isFile() && f.exists() && !f.getName().equals(downloadName)) {
f.delete();
}
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(downloadPathFile)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
unregisterReceiver(br);
}
}
}
}
};
registerReceiver(br, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}