Android download queue using DownloadManger

前端 未结 2 1951
Happy的楠姐
Happy的楠姐 2021-01-06 12:36

I\'m using DownloadManager to download my files in android and its great since it handles everything (connectivity lost, retry, etc.) The problem is I want my file to be dow

2条回答
  •  礼貌的吻别
    2021-01-06 13:18

    I found the answer! The problem with IntentService is it execute DownloadManager.engueue() so fast and as a result all download get downloaded together. So i made sure requests are not finished running until download is finished simply by calling wait() on background thread. and calling notify() when Broadcast onReceive is called and my download is finished!

    I run this after downloding the file

        currentDownloadId = downloadManager.enqueue(downloadRequest);
        backgroundThread = Thread.currentThread();
        synchronized (Thread.currentThread()) {
            try {
                Thread.currentThread().wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    

    and when download is finished i run this

    @Override
    public void onReceive(Context context, Intent intent) {
        long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,0);
        if (downloadId == currentDownloadId) {
            synchronized (backgroundThread) {
                backgroundThread.notify();
            }
        }
    }
    

    now execution of current download gets finished and next one begans automatically!

提交回复
热议问题