Ramin Roshan Ramin Roshan - 3 months ago 21
Android Question

Find out File be download in android

I download file by this code:

manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); String url = json_string_4_all[0];
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
id = manager.enqueue(request);
request.setDescription("درصد دانلود ");
request.setTitle("دانلود کتاب " + json_string_1_all[0]);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}

request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, json_string_1_all[0] + ".pdf");manager.enqueue(request);


Now i want do something after it downloaded (finished).

How can i do that?

Answer

You could create a receiver for the ACTION_DOWNLOAD_COMPLETE broadcast:

private final BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // download complete, do whatever you would like here

        // optionally, check the ID of the completed download
        long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        if(id == yourId) {
            // do your stuff
        }
    }
};

And register it:

registerReceiver(downloadReceiver,
    new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

Don't forget to unregister when appropriate (in onPause() for example):

unregisterReceiver(downloadReceiver);