按下后退按钮时,Async Task事件中的下载不会停止

时间:2012-11-09 06:53:41

标签: android android-asynctask android-alertdialog

我在AsynchTask中下载pdf文件,因此在下载文件时,我的进度对话框正在更新。但问题是,如果我按下后退按钮,弹出警报框,下载在后台停止。我想它应该在警报对话框被调用后继续下载,或者一旦警报弹出就暂停下载,如果我点击警告对话框的取消按钮则继续下载一次。

这是一个片段,

@Override
protected Dialog onCreateDialog(int id)
{
 switch (id)
 {
  case progress_bar_type:
  pDialog = new ProgressDialog(this);
  pDialog.setMessage("Downloading file. Please wait...");
  pDialog.setIndeterminate(false);
  pDialog.setMax(100);
  pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  pDialog.setCancelable(true);
  pDialog.show();
  pDialog.setOnKeyListener(new DialogInterface.OnKeyListener() 
  {
   @Override
   public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) 
   {
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
     running = false;

        AlertDialog.Builder  alertDialog = new AlertDialog.Builder(context);
        AlertDialog.setIcon(R.drawable.ic_launcher);
        alertDialog.setTitle("Ariisto");
        alertDialog.setMessage("Do you Want to Cancel the Download ?");
    alertDialog.setCancelable(true);
    alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() 
        {
        @Override
public void onClick(DialogInterface dialog, int which) 
{
                                // TODO Auto-generated method stub

                                File externalFile = new File(Environment.getExternalStorageDirectory(),"downloadedfile.pdf");
                                externalFile.delete();
                                pDialog.dismiss();
                                running = false;
                                Log.d("External File", "DELETED");
                                pDialog.setProgress(0);
                                count = 2;


                            }
                        });
                        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                new DownloadFileFromURL().execute(file_url);
                                running = true;
                                count = 0;
                            }
                        });

                        AlertDialog alert = alertDialog.create();

                            alert.show();

                    }

                    return false;

                }
            });


            return pDialog;
        default:
            return null;
        }
    }
    class DownloadFileFromURL extends AsyncTask<String, String, String> 
    {

        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         * */




        @SuppressWarnings("deprecation")
        protected void onPreExecute()
        {
            super.onPreExecute();
            showDialog(progress_bar_type);
            publishProgress(""+(int)(0));
            running = true;
        }

        @Override
        protected void onCancelled() {
            // TODO Auto-generated method stub

            Log.d("------------","iNSIDE ON CANCELLED METHOD");

            super.onCancelled();
        }



        @Override
        protected String doInBackground(String... file_url) 
        {
            // TODO Auto-generated method stub
            int count;
            try
            {
                URL url = new URL(file_url[0]);
                URLConnection connection = url.openConnection();
                connection.connect();
                // getting file length
                int lenghtOfFile = connection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file
                FileOutputStream output = new FileOutputStream("/sdcard/downloadedfile.pdf");


                byte data[] = new byte[1024];

                long total = 0;

                while (   ((count = input.read(data)) != -1) && (running == true)  ) 
                {




                    total += count;

                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress(""+(int)((total*100)/lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                output.flush();

                // closing streams
                output.close();
                input.close();
            }
            catch (Exception e)
            {
                Log.e("Error: ", " "+e.getMessage());
            }
            return null;
        }

        protected void onProgressUpdate(String... progress) 
        {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }
        @SuppressWarnings("deprecation")
        protected void onPostExecute(String file_url) 
        {
            // dismiss the dialog after the file was downloaded
            if(running == true){
                dismissDialog(progress_bar_type);
                // Displaying downloaded image into image view
                // Reading image path from sdcard
                String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf";
                // setting downloaded into image view
                Log.d(imagePath, "show file");
                File file = new File(Environment.getExternalStorageDirectory(),"downloadedfile.pdf");
                Uri external = Uri.fromFile(file);

                viewPdf(external);
            }
        }

    }

1 个答案:

答案 0 :(得分:0)

我的要求与此非常相似。用户将单击listItem,AsyncTask将开始下载它,然后在完成后显示它。如果用户在下载完成之前点击后退按钮,则会显示一个警告对话框,询问是否中止下载。如果下载完成,则显示该对话框,它只是取消对话框并完成该活动。我没有时间来清理和清理代码,但模式如下:

该活动有两个私人字段:

private DownloadTask downloader = null;
private AlertDialog dlgCancel = null;
onBackPressed中的

if( downloader != null ) {
    dlgCancel =....
    dlgCancel.show();
} else
    finish();
在DownloadTask的onPostExecute中

if( isCancelled() ) {
    ... dismiss the download
} else { 
    if( dlgCancel == null ) {
        ... handle the download here ...
    } else {
        dlgCancel.dismiss();
        dlgCancel = null;
        Activity.finish();
    }
}

最后,在onClick for Abort-Download按钮中:

downloader.cancel( true );
Activity.finish();

请注意,您需要在AsyncTask的doInBackground()中查看isCancelled(),以便您能够尽快做出反应。有些操作不会立即返回。