如何在执行后取消AsyncTask?

时间:2012-11-24 17:04:35

标签: java android android-asynctask

我使用AsyncTask with Progress Dialog从服务器下载数据库。我想为用户提供取消下载任务的选项。

我的目的是在用户点击进度对话框上的Cancel button时解除进度对话框并取消AsyncTask。

我已应用了大量代码示例,但它们仅帮助解除进度对话框,无法停止或取消下载任务。

关于我在下面的代码行, ,您能给一点帮助吗?非常感谢。

已编辑版本

public class Download_gram extends Activity {

// File url to download
private static String url = "https://dl.dropbox.com/u/15034088/Anhroid_Dict/grammar.nvk.zip";
private static DownloadFile newTask; 

// Progress Dialog
private ProgressDialog progressDialog;
// Progress dialog type (0 - for Horizontal progress bar) 
public static final int progress_bar = 0; 

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.download_gram);
    newTask = new DownloadFile();

    startDownload_gram = (Button) findViewById(R.id.btnProgressBar_gram);

    //start download event and show progress bar
    startDownload_gram.setOnClickListener(new View.OnClickListener() {  
        @Override
        public void onClick(View v) {
        //Checi if file exists 
             File fgram = new File(Environment.getExternalStorageDirectory()+"/my_Folder/db/my_file/my_file.nvk");
             if(fgram.exists())
             { 
                 Toast.makeText(getApplicationContext(), "File installed.", Toast.LENGTH_LONG).show();
             }
             else
             {

                //checking if the user has an internet connection
                ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = cm.getActiveNetworkInfo();
                if (info != null) {
                    if (!info.isConnected()) {
                        Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_SHORT).show();
                    }
                // execute async task
                    else 
                        //new DownloadFile().execute(url);                          
                    newTask.execute(url);
                }
                else {
                    Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_SHORT).show();
                }                   
             }           

        }});        
    }   

//show progress dialog
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar:
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Downloading… Please wait.");
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dismissDialog(progress_bar);
                newTask.cancel(true);
            }
        });
        progressDialog.show();
        return progressDialog;
    default:
        return null;
    }
}

//backgroound downloading
    class DownloadFile extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar);
        }

        @Override
        protected String doInBackground(String... args) {
            while (url != null) {
            int count;              
            try {
                URL url = new URL(args[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int fileLength = conection.getContentLength();
                InputStream is = new BufferedInputStream(url.openStream(), 8192);
                OutputStream os = new FileOutputStream(Environment.getExternalStorageDirectory().getPath() + "/_nvk_gram.zip");

                byte data[] = new byte[1024];
                long total = 0;
                while ((count = is.read(data)) != -1) {
                    total += count;
                    publishProgress(""+(int)((total*100)/fileLength));
                    // writing data to file
                    os.write(data, 0, count);
                }
                // flush output
                os.flush();             

                os.close();
                is.close();
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            //Unzip the downloaded zip file 
            {
                String destinationDirectory = Environment.getExternalStorageDirectory().getPath() + "/my_Folder/db/my_file/";
                int BUFFER = 2048;
                List<String> zipFiles = new ArrayList<String>();
                File sourceZipFile = new File(Environment.getExternalStorageDirectory().getPath() + "/_nvk_gram.zip");
                File unzipDestinationDirectory = new File(destinationDirectory);
                unzipDestinationDirectory.mkdir();

                ZipFile zipFile = null;
                // Open Zip file for reading
                try {
                    zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                // Create an enumeration of the entries in the zip file
                Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries();

                // Process each entry
                while (zipFileEntries.hasMoreElements()) {
                    // grab a zip file entry
                    ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

                    String currentEntry = entry.getName();

                    File destFile = new File(unzipDestinationDirectory, currentEntry);
                          //destFile = new File(unzipDestinationDirectory, destFile.getName());

                    if (currentEntry.endsWith(".zip")) {
                        zipFiles.add(destFile.getAbsolutePath());
                    }

                    // grab file's parent directory structure
                    File destinationParent = destFile.getParentFile();

                    // create the parent directory structure if needed
                    destinationParent.mkdirs();

                    try {
                        // extract file if not a directory
                        if (!entry.isDirectory()) {
                            BufferedInputStream is =
                                    new BufferedInputStream(zipFile.getInputStream(entry));
                            int currentByte;
                            // establish buffer for writing file
                            byte data[] = new byte[BUFFER];

                            // write the current file to disk
                            FileOutputStream fos = new FileOutputStream(destFile);
                            BufferedOutputStream dest =
                                    new BufferedOutputStream(fos, BUFFER);

                            // read and write until last byte is encountered
                            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                                dest.write(data, 0, currentByte);
                            }
                            dest.flush();
                            dest.close();
                            is.close();
                        }
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                }
                try {
                    zipFile.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                for (Iterator<String> iter = zipFiles.iterator(); iter.hasNext();) {
                    String zipName = (String)iter.next();
                    doUnzip(
                        zipName,
                        destinationDirectory +
                            File.separatorChar +
                            zipName.substring(0,zipName.lastIndexOf(".zip"))
                    );
                    if(isCancelled())return (null);
                }
            }
            }

            File fav_ifo = new File(Environment.getExternalStorageDirectory()+"/my_Folder/db/my_file/my_file.nvk");
            if(fav_ifo.exists())
            { 
                try {
                    AssetManager am = getAssets();
                    String fileName = "my_file.ifo";
                    File destinationFile = new File(Environment.getExternalStorageDirectory()+"/my_Folder/db/my_file/" + fileName);    
                    InputStream in = am.open("my_file.ifo");
                    FileOutputStream f = new FileOutputStream(destinationFile);  
                    byte[] buffer = new byte[1024];
                    int len1 = 0;
                    while ((len1 = in.read(buffer)) > 0) { 
                        f.write(buffer, 0, len1);
                    }
                    f.close();
                } catch (Exception e) {
                    Log.d("CopyFileFromAssetsToSD", e.getMessage());    
                }   
            }
            else
            {

            }
           //Delete the downloaded zip
            File folder = Environment.getExternalStorageDirectory();
            String fileName = folder.getPath() + "/_nvk_gram.zip";

            File myFile = new File(fileName);
            if(myFile.exists())
                myFile.delete();
                return null; 

                 }          

        private void doUnzip(String zipName, String string) {
            // TODO Auto-generated method stub

        }

        //updating progress bar
        protected void onProgressUpdate(String... progress) {
            //progress percentage
            progressDialog.setProgress(Integer.parseInt(progress[0]));   
       }

        @Override
        protected void onPostExecute(String file_url) { 
            dismissDialog(progress_bar);
            //toast to notify user of download completion
            Toast.makeText(getApplicationContext(), "Database successfully downloaded.", Toast.LENGTH_LONG).show();
             Intent mainIntent = new Intent(Download_gram.this, my_Main_class.class);
                Download_gram.this.startActivity(mainIntent);
        }
    }
}   

3 个答案:

答案 0 :(得分:1)

看你应该跟踪你的DownloadFile(aSyncTask)类对象。

中创建一个新变量
public class Download_gram extends Activity {
    // File url to download
    private static String url = "http://www.abc.123.zip";
    private static DownloadFile newTask; // ADDED BY ME
// ... ...

调用

时应保存对象引用
new DownloadFile().execute("Url String"); //you must be doing this

//instead you should do

newTask = new DownloadFile();
newTask.execute("Url String");  // YOUR OBJECT IS IN newTask
...

// keep track of this newTask variable

// when ever you want to cancel just call
newTask.cancel(true); // ADDED BY ME
dialog.dismiss();//In fact, I want to apply the code to stop both Progress Dialog and AsynTask here.

设置newTask取消后,你应该在doInBackground中及时检查你的任务被取消了吗?如果是,则退出doInBackground

// YOU CAN USE THIS IN WHILE LOOP OF doInBakcground
if(isCancelled())return (null);
//This will exit doInBackground function and hence cancel task.
// you can perform other operations too in this "if" statement as per your need.

供参考这些功能

http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean

##################### 新版本 ################。

您尚未检查任务是否已取消。如果iscancelled为true,则必须检查asynctask中发生的下载正在进行中返回(null);停止asynctask并停止下载。 你应该替换以下代码:

    while ((count = is.read(data)) != -1) { // inside doInBackground
                total += count;
                publishProgress(""+(int)((total*100)/fileLength));
                // writing data to file
                os.write(data, 0, count);
                if(isCancelled())return (null); // ADDED BY ME
            }

上面添加的行必须检查任务是否被取消,这个doInBackground函数应该结束。

答案 1 :(得分:0)

你可以这样做,

 progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
      public void onCancel(DialogInterface dialog) {
          yourAysncTask.cancel(true);
      }
});

答案 2 :(得分:0)

你应该

yourAsyncTask.cancel(true);

并且,在你的类DownloadFile中,你应该检查 isCanceled()并在if为真时返回。