0

我使用带有进度对话框的 AsyncTask 从服务器下载数据库。我想为用户提供取消下载任务的选项。

我的目的是在用户单击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);
        }
    }
}   
4

3 回答 3

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 return (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 函数应该结束。

于 2012-11-25T10:01:52.853 回答
0

你可以这样做,

 progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
      public void onCancel(DialogInterface dialog) {
          yourAysncTask.cancel(true);
      }
});
于 2012-11-24T17:09:06.230 回答
0

你应该

yourAsyncTask.cancel(true);

并且,在您的类 DownloadFile 中,您应该检查isCanceled()并在 true 时返回。

于 2012-11-24T17:12:59.807 回答