Search code examples
androidandroid-download-manager

Finding download complete from downloadManager in android


I am downloading a file to the device external storage from my android app from a web server using DownloadManager. I need to initiate another function on completion of this download. my file download code goes like this:

String url = "http://192.168.1.105/download/file.ext";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "files.ext");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);

please suggest how to get something like onDownloadComplete.....


Solution

  • I found my answer at : DownloadManager.ACTION_DOWNLOAD_COMPLETE broadcast receiver receiving same download id more than once with different download statuses in Android
    and the code for me goes like this:

    private boolean downloadComplete(long downloadId){
            DownloadManager dMgr = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            Cursor c= dMgr.query(new DownloadManager.Query().setFilterById(downloadId));
    
            if(c.moveToFirst()){
                int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
    
                if(status == DownloadManager.STATUS_SUCCESSFUL){
                    return true; //Download completed, celebrate
                }else{
                    int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
                    Log.d(TAG, "Download not correct, status [" + status + "] reason [" + reason + "]");
                    return false;
                }
            }
            return false;
        }