How can I wait until DownloadManager is complete?

丶灬走出姿态 提交于 2019-12-19 10:22:59

问题


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!


回答1:


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>



回答2:


A Broadcast intent action sent by the download manager when a download completes so you need to register a receiver for when the download is complete:

To register receiver

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

and a BroadcastReciever handler

BroadcastReceiver onComplete=new BroadcastReceiver() {
    public void onReceive(Context ctxt, Intent intent) {
        // your code
    }
};

You can also create AsyncTask to handle the downloading of big files

Create a download dialog of some sort to display downloading in notification area and than handle the opening of the file:

protected void openFile(String fileName) {
    Intent install = new Intent(Intent.ACTION_VIEW);
    install.setDataAndType(Uri.fromFile(new File(fileName)),"MIME-TYPE");
    startActivity(install);
}

you can also check the sample link
sample

来源:https://stackoverflow.com/questions/35285914/how-can-i-wait-until-downloadmanager-is-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!