我可以使用DownloadManager
下载apk以更新我的应用。
public int onStartCommand(Intent intent, int flags, int startId) {
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
downloadSuccess();
stopSelf();
}
};
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(receiver, filter);
Bundle bundle = intent.getExtras();
builder = bundle.getParcelable("updateBuilder");
downloadConfig = bundle.getParcelable("downloadConfig");
startDownload();
return Service.START_NOT_STICKY;
}
BroadcastReceiver
来收听"ACTION_DOWNLOAD_COMPLETE"
; 在方法startDownload()
中,我将检查该方法是否正在下载它:
private void startDownload() {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
if (isDowning(downloadConfig.getDownloadUrl())) {
//tips
} else {
//do downloading
}
}
private boolean isDowning(String uri) {
boolean flag = false;
try {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_RUNNING);
if (dm == null) {
dm = ((DownloadManager) this.getSystemService(Activity.DOWNLOAD_SERVICE));
}
Cursor c = dm.query(query);
String downingURI;
while (c.moveToNext()) {
downingURI = c.getString(c.getColumnIndex(DownloadManager.COLUMN_URI));
if (downingURI.equalsIgnoreCase(uri)) {
flag = true;
break;
}
}
c.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return flag;
}
当我重新启动应用程序并再次检查更新时(在完成最后一个下载任务之前),它可以纠正判断。但是,下载后,尽管通知显示下载任务已完成,但文件不存在。
如果不执行任何操作,如重新启动...或在下载完成后重新启动,则该服务将正常运行。
所以我想知道方法isDowning()
是否影响正在执行的任务?