Android:下载线程卡住了应用程序

时间:2013-05-14 18:33:34

标签: android downloading

我的Android应用程序在下载文件时总是卡住,直到下载完成。但是,下载线程继承自AyncTask并且它在后台。任何人都可以看看有什么问题,我怎样才能修改代码才能使它工作?

    private class DownloadFileTask extends AsyncTask<String, Integer, String> {

    File destFile;

    private boolean openAfterDownload;
    private Exception failure;

    public DownloadFileTask(boolean openAfterDownload) {
        this.openAfterDownload = openAfterDownload;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();           
        downloadDialog.setMessage(getString(R.string.downloading));
        downloadDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        try {

            String url = params[0];
            LOG.debug("Downloading: " + url);

            String fileName = url.substring(url.lastIndexOf('/') + 1);

            HttpParams httpParams = new BasicHttpParams();
            DefaultHttpClient client = new DefaultHttpClient(httpParams);
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(null, -1),
                    new UsernamePasswordCredentials(user, password));
            HttpGet get = new HttpGet(url);

            HttpResponse response = client.execute(get);

            if (response.getStatusLine().getStatusCode() == 200) {

                File destFolder = new File(config.getDownloadsFolder());
                if (!destFolder.exists()) {
                    destFolder.mkdirs();
                }

                /**
                 * Make sure we always store downloaded files as .epub, 
                 * so they show up in scans later on.
                 */
                if ( ! fileName.endsWith(".epub") ) {
                    fileName = fileName + ".epub";
                }

                destFile = new File(destFolder, URLDecoder.decode(fileName));

                if (destFile.exists()) {
                    destFile.delete();
                }

                // lenghtOfFile is used for calculating download progress
                long lenghtOfFile = response.getEntity().getContentLength();
                if(lenghtOfFile>=config.getAvailableSpace())
                {
                    this.failure = new Exception("not enough space");
                    return null;
                }
                // this is where the file will be seen after the download
                FileOutputStream f = new FileOutputStream(destFile);

                try {
                    // file input is from the url
                    InputStream in = response.getEntity().getContent();

                    // here's the download code
                    byte[] buffer = new byte[1024];
                    int len1 = 0;
                    long total = 0;

                    while ((len1 = in.read(buffer)) > 0) {

                        // Make sure the user can cancel the download.
                        if (isCancelled()) {
                            return null;
                        }

                        total += len1;
                        publishProgress((int) ((total * 100) / lenghtOfFile));
                        f.write(buffer, 0, len1);
                    }
                } finally {
                    f.close();
                }

            } else {
                this.failure = new RuntimeException(response
                        .getStatusLine().getReasonPhrase());
                LOG.error("Download failed: "
                        + response.getStatusLine().getReasonPhrase());
            }

        } catch (Exception e) {
            Toast.makeText(getActivity(), e.getMessage() + "1",
                    Toast.LENGTH_LONG).show();
            LOG.error("Download failed.", e);
            this.failure = e;
        }

        return null;
    }

1 个答案:

答案 0 :(得分:0)

虽然您在AsyncTask中运行任务,但您拥有以下代码行:

    downloadDialog.setMessage(getString(R.string.downloading));
    downloadDialog.show();

在你的onPreExecute()方法中,它基本上会在自己开始的任务之前启动一个DialogBox。

我还没有在您的实现中看到onPostExecute()方法。所以你永远不会.dismiss()对话。但即使你这样做,你仍然会在下载完成后使用此对话框进行“堆叠”(正常行为)。