简体   繁体   中英

simultaneous download of files - best way to handle it

I am writing an application targeting API level 9 or higher. So, i have decided to go with DownloadManager Class that SDK offers. My question is 2 part - 1. When i am downloading a single file, how do i display the progress of the download. I see i can get COLUMN_TOTAL_SIZE_BYTES and COLUMN_BYTES_DOWNLOADED_SO_FAR from the querying the download manager instance. But i am not sure if i have to put the query in a thread and implement a loop so that i can poll regularly to update the progress bar. I guess, i am not sure, how to query regularly - will it go in the main thread or be implemented as a runnable - the mechanism i am not clear. 2. If i have to support multiple file downloads, then do i have to launch each one of them in it's own thread? Thanks.

If you are building on 2.3 and above you don't need to, it automatically displays it in the status bar. Do it like this, Code from commonsware,

    private static final int DOWNLOAD_SUCCESSFUL = 100;
private static final int DOWNLOAD_FAILED = 99;
    private DownloadManager mgr=null;

on create do this,

`mgr = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);    

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

`

Then on the click event of the file download,

lastDownload = mgr.enqueue(new DownloadManager.Request(uri) .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE) .setAllowedOverRoaming(false) .setTitle("Test File") .setDescription("Download zipped file.") .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, file_name));

And then a broadcast receiver for when your donwnload compeletes,

BroadcastReceiver onComplete=new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {

            findViewById(R.id.start).setEnabled(true);  

            File unzipFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),file_name);            

            //check for new file download
            //extract if it's a new download

            if (unzipFile.exists()) {
                new UnzipFile().execute();              
            } else {
                Toast.makeText(Main.this, "Download not found!", Toast.LENGTH_LONG).show();
            }           
        }
    };`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM