0

我的应用程序上有 5 个大文本文件,每个文件大约 40kb。这些文件每周在网站上更新。我设法将 downloadManager 设置为从站点下载 5 个文件。问题是我不希望用户在下载文件时能够使用该应用程序,因为这会导致问题。我希望当用户单击“更新”按钮时,它会显示一个加载框。然后,当文件下载完成时,该框将消失,吐司会说“已更新”。这是我设置的方法:

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

顺便说一句,如果您发现该方法有任何问题,也请告诉我。提前致谢。

4

1 回答 1

0

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.

于 2014-06-24T12:59:29.130 回答