我使用DownloadManager获取下载状态,但它仍然不起作用,它从不跳转到条件if(c.moveToFirst())
,我不知道为什么。请问有人帮帮我吗?
private final BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(Intent.ACTION_SCREEN_OFF.equals(action)) {
DownloadManager downloadMgr = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterByStatus(DownloadManager.STATUS_FAILED|DownloadManager.STATUS_PENDING|DownloadManager.STATUS_RUNNING|DownloadManager.STATUS_SUCCESSFUL);
Cursor c = downloadMgr.query(query);
if(c==null) {
//
}
else {
if(c.moveToFirst()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = c.getInt(columnIndex);
if(status == DownloadManager.STATUS_RUNNING){
//do something
}
}
}
}
}
};
答案 0 :(得分:7)
这里有几个链接参考。
示例代码位于::
之下DownloadManager.Query query = null;
Cursor c = null;
DownloadManager downloadManager = null;
downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
query = new DownloadManager.Query();
if(query!=null) {
query.setFilterByStatus(DownloadManager.STATUS_FAILED|DownloadManager.STATUS_PAUSED|DownloadManager.STATUS_SUCCESSFUL|
DownloadManager.STATUS_RUNNING|DownloadManager.STATUS_PENDING);
} else {
return;
}
c = downloadManager.query(query);
if(c.moveToFirst()) {
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch(status) {
case DownloadManager.STATUS_PAUSED:
break;
case DownloadManager.STATUS_PENDING:
break;
case DownloadManager.STATUS_RUNNING:
break;
case DownloadManager.STATUS_SUCCESSFUL:
break;
case DownloadManager.STATUS_FAILED:
break;
}
}
答案 1 :(得分:0)
我就是这样做的
//broadcastReceiver
private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
//call notify off NotificationManager passing in the id & notification
notificationManager.apply {
notify(NOTIFICATION_ID, createNotification())
}
//DownloadManager.Query() is used to filter DownloadManager queries
val query = DownloadManager.Query()
query.setFilterById(id)
val cursor = downloadManager.query(query)
if (cursor.moveToFirst()){
val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
when (status) {
DownloadManager.STATUS_SUCCESSFUL ->{
}
DownloadManager.STATUS_FAILED -> {
}
}
}
}
}