Search code examples
androidandroid-download-manager

How can I wait until DownloadManager is complete?


This is the code I'm currently using

                String iosjiUrl = "http://modapps.com/NotoCoji.ttf";
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(iosjiUrl));
                request.setDescription("Sscrition");
                request.setTitle("Somle");
// in order for this if to run, you must use the android 3.2 to compile your app
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                }
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "NotoColorji.ttf");

// get download service and enqueue file
                DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);

                manager.enqueue(request);

I'm not able to find a way for me to wait until the file is downloaded.

I also tried figuring out how to go about doing ASync but couldn't figure that out either =/

Thanks again!


Solution

  • Use a BroadcastReceiver to detect when the download finishes:

    public class DownloadBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
    
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                //Show a notification
            }
        }
    }
    

    and register it in your manifest:

    <receiver android:name=".DownloadBroadcastReceiver">
        <intent-filter>
            <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
        </intent-filter>
    </receiver>