代码之家  ›  专栏  ›  技术社区  ›  IdkHowToCodeAtAll

我如何才能等到DownloadManager完成?

  •  2
  • IdkHowToCodeAtAll  · 技术社区  · 9 年前

    这是我当前使用的代码

                    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);
    

    我找不到一种方法来等待文件下载。

    我还试着弄清楚如何进行ASync,但也弄不清楚=/

    再次感谢!

    2 回复  |  直到 9 年前
        1
  •  4
  •   camelCaseCoder    9 年前

    使用 BroadcastReceiver 检测下载何时完成:

    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
            }
        }
    }
    

    并在您的舱单中注册:

    <receiver android:name=".DownloadBroadcastReceiver">
        <intent-filter>
            <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
        </intent-filter>
    </receiver>
    
        2
  •  1
  •   geniushkg    9 年前

    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