从Android下载管理器完成所有下载后如何通知

时间:2017-04-20 08:47:44

标签: android android-download-manager

我正在使用Android下载管理器课程。所有下载完成后,我需要编写“下载完成”。我尝试了一些东西,它正在发挥作用。但是在这里它是在逐个文件完成之后写的。我只需要写一次(毕竟完成)。我也试过没有光标。但我没能实现。

public class DownloadReceiver extends BroadcastReceiver {


Context context;
@Override
public void onReceive(Context context, Intent intent) {
    long receivedID = intent.getLongExtra(
             DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
             DownloadManager mgr = (DownloadManager)
            context.getSystemService(Context.DOWNLOAD_SERVICE);

    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(receivedID);
    Cursor cur = mgr.query(query);
    int index = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
    if(cur.) {
        String  filePath = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_TITLE));
        if(cur.getInt(index) == DownloadManager.STATUS_SUCCESSFUL){
            DatabaseHandler dh = new DatabaseHandler(context);
            dh.addDownloadComplete(new DownloadComplete("Download Complete"));
        }
    }
    cur.close();
}}

2 个答案:

答案 0 :(得分:1)

在通知所有下载完成之前添加一项检查。喜欢

query.setFilterByStatus(DownloadManager.STATUS_PAUSED |
      DownloadManager.STATUS_PENDING |
      DownloadManager.STATUS_RUNNING);
    Cursor cursor = downloadManager.query(query);
    if (cursor != null && cursor.getCount() > 0) {
      return;
    }else {
      query.setFilterById(receivedID);
      //proceed your...
    }

答案 1 :(得分:0)

这是我认为可行的。定义一个函数如下:

public boolean areAllDownloadsComplete(int[] downloadIds) {

    DownloadManager mgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

    DownloadManager.Query query = new DownloadManager.Query();

    for(int i = 0; i < downloadIds.length; i++) {

        query.setFilterById(downloadIds[i]);

        Cursor cur = mgr.query(query);

        if(cur.moveToNext()) {

            if(cur.getInt(cur.getColumnIndex(DownloadManager.COLUMN_STATUS)) != DownloadManager.STATUS_SUCCESSFUL) {

                return false;
            }
        }
    }

    return true;
}

在广播中调用此函数(在每次下载完成通知时),如下所示:

if(areAllDownloadsComplete(THE_DOWNLOAD_IDS)) {
    DatabaseHandler dh = new DatabaseHandler(context);
    dh.addDownloadComplete(new DownloadComplete("Download Complete"));
}

您可以将下载ID传递给广播接收器意图

Bundle bundle = new Bundle();
bundle.putIntArray("download_ids", THE_DOWNLOAD_IDS);
intent.putExtra(bundle);