Question

My app has 5 big text files on them, each one about 40kb. Those files are updated weekly on a website. I managed to set downloadManager to download the 5 files from the site. The problem is that I don't want the user to be able to use the app while the files are downloading because that will cause problems. I want that when the user clicks the "Update" button it will show up a loading box. Then when the files finish downloading the box will disappear and a toast will say "Updated." This is the method I've set up:

@SuppressLint("NewApi")
public void DownloadTxtFile(String url, String fileName) {
    if (!new File(Environment.getExternalStorageDirectory()
            + "/folder").exists()) {
        new File(Environment.getExternalStorageDirectory()
                + "/Dovahzul_Dictionary").mkdirs();
    }
    File file = new File(extStore.getAbsolutePath()
            + "/folder/" + fileName);
    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse(url));
    request.setDescription("Downloading Text Files...");
    request.setTitle("Updating")

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalPublicDir("/Dovahzul_Dictionary",
            fileName);
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    if (file.exists()) {
        file.delete();
    } else {
    }
    manager.enqueue(request);
}

By the way, if you find any problem with the method, plase inform me as well. Thanks in advance.

Was it helpful?

Solution

I know this is old, but to anyone that has the same problem: What you need to do, is start the download in a different thread.

As android is not thread prof, you need to use AsyncTask instead. An AsyncTask is very similar to a thread. By starting and using one, you can do some quite long operations without freezing the ui. (Note that AsyncTasks are recomended for operations that take seconds, not minutes. In that case, you need to find something else)

You start an AsyncTask, and make it download the file. The problem is that AsyncTasks can't access ui methods, so they can't change threads. You can, luckly, override a method they have to update the ui, and call it directly from it's onExecute.

Many tutorials on this can be found in the web.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top