即使按下后退按钮,也不会停止在AsynchTask上

问题描述:

我正在下载AsynchTask中的pdf文件,因此它下载文件时,我的进度对话框正在更新。然而,问题是,如果我按下后退按钮比我的警报箱弹出,下载停止在后台。我希望即使在调用警报对话框后它仍应继续下载,或者一旦警报弹出后暂停下载,并在单击警报对话框的取消按钮时继续下载一次。即使按下后退按钮,也不会停止在AsynchTask上

这里是一个片段,

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

    } 
+0

按下活动不应该停止AsyncTask,除非您取消它。尽管如此,你可能更适合使用服务。 – 323go

+0

它不停止下载我的意思是AsynchTask仍在执行其操作。我需要它应该暂停过程当用户按下后退按钮,并恢复其操作,一旦用户点击提醒框的取消按钮。 –

+1

下载操作从后台线程开始,一旦操作在doInBackground()中开始,您不能“暂停”它。点击按钮后,您将不得不取消该任务并重新启动该任务。 – GamDroid

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

的活动有两个私有字段:

private DownloadTask downloader = null; 
private AlertDialog dlgCancel = null; 
在onBackPressed

if(downloader != null) { 
    dlgCancel =.... 
    dlgCancel.show(); 
} else 
    finish(); 

下载任务的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 bu tton:

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

请注意,你需要留意isCancelled()在你的AsyncTask的doInBackground(),这样就可以尽可能快地作出反应。有些操作不会立即返回。