在后退按钮上按下取消asynctask下载

时间:2012-12-01 16:07:52

标签: android android-asynctask override back-button

这是我的下载类,其中我使用了Asynctask.Everything工作正常,当文件完全下载时,它显示'文件下载'并且'确定'按下回到之前的活动。现在我想取消asynctask (请不要在取消asynctask'而不仅仅是'loading'对话框)按下后退按钮并返回上一个活动。如何做到这一点?有人请帮忙。谢谢提前

public class Download extends Activity {

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;

private ProgressDialog mProgressDialog;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.down);

    startDownload();


}

private void startDownload() {
    String url = data.proj;


    new DownloadFileAsync().execute(url);
}
private void showMsg() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Document is downloaded")
           .setCancelable(false)
           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
               @Override
            public void onClick(DialogInterface dialog, int id) {
                    //do things
                   Download.this.finish();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();
}
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Downloading file..");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);

        mProgressDialog.show();


        return mProgressDialog;
    default:
        return null;
    }
}

    class DownloadFileAsync extends AsyncTask<String, String, String> {

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

}

@Override
protected String doInBackground(String... aurl) {
    int count;

try {

URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();

int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

String fname;
 fname = data.proj.substring( data.proj.lastIndexOf('/')+1, data.proj.length() );

InputStream input = new BufferedInputStream(url.openStream());
String path=Environment.getExternalStorageDirectory()
        .toString() + File.separator;
OutputStream output = new FileOutputStream(path+fname);


byte data[] = new byte[1024];

long total = 0;

    while ((count = input.read(data)) != -1) {
        total += count;
        publishProgress(""+(int)((total*100)/lenghtOfFile));
        output.write(data, 0, count);
    }

    output.flush();
    output.close();
    input.close();
} catch (Exception e) {}

return null;

}
@Override
protected void onProgressUpdate(String... progress) {
     Log.d("ANDRO_ASYNC",progress[0]);
     mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
    dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
    showMsg();
}
}}

2 个答案:

答案 0 :(得分:3)

真的很老问题,但似乎很多人在取消AsyncTasks方面仍面临问题。所以,这里......

您需要在AsyncTask类(DownloadFileAsync)中使用一个字段来存储用于取消任务的View(此处为ProgressDialog)。

对于ProgressDialog,在创建对话框时,将true传递给setCancelable()

mProgressDialog.setCancelable(true);

要传递视图,请按以下步骤更改对任务的调用:

new DownloadFileAsync(mProgressDialog).execute(url);

在我们的AsyncTask类中,创建一个构造函数,将该值保存到字段并注册OnCancelListener以调用AsyncTask的cancel方法:

ProgressDialog mProgressDialog;

DownloadFileAsync(ProgressDialog progressDialog) {
    mProgressDialog = progressDialog;
    mprogressDialog.setOnCancelListener(new OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            cancel(true);
        }
    });
}

doInBackground的while循环中,在循环中添加以下代码

if (isCancelled()) {
    outputStream.flush();
    outputStream.close();
    inputStream.close();
    return null;
}

这样我们每隔一段时间检查一次任务是否被取消,如果是,我们关闭开放流并停止运行返回任务(返回将是为Task的结果给出的类型)。接下来,在onCancelled

@Override
protected void onCancelled (Integer fileSize) {
    super.onCancelled(fileSize);
    Log.d("TASK TAG", "Cancelled.");
    //anything else you want to do after the task was cancelled, maybe delete the incomplete download.
}

答案 1 :(得分:0)

这就是我做的事情

public class downloadAllFeeds extends AsyncTask<Void, Void, Void> 
implements OnCancelListener{


    protected void onPreExecute() {
    pDialog2.setCancelable(true);
    pDialog2.setOnCancelListener(this);
    }

    @Override
    public void onCancel(DialogInterface dialog) {
    // TODO Auto-generated method stub
    downloadAllFeeds.this.cancel(true);
    Log.d("on click cancel true","true");
    }

    @Override
    protected Void doInBackground(Void... params) {
    if(isCancelled()==true){
    //cancel true stop async
    Log.d("cancel true","true");

    }else{
      //perform your task
     }
}

这对我有用,我知道这是一个非常古老的问题,但它没有答案,所以我认为我应该分享我现在可以实现的内容:)