0

my data is load from the internet, so I use the AsynTask(). execute() method to open a progressDialog first, then load the data in the background. it works, however, sometimes it takes too long to load the data so I want to cancel loading, and here is the problem: when I click back button the dialog dismiss but after it finish loading at the background, it start to do whatever it supposed to do after loading, e.g. start a new intent. is there any way I can cancel the loading properly???

new GridViewAsyncTask().execute();
public class GridViewAsyncTask extends AsyncTask<Void, Void, Void> {
    private ProgressDialog myDialog;

    @Override
    protected void onPreExecute() {
        // show your dialog here
        myDialog = ProgressDialog.show(ScrollingTab.this, "Checking data",
                "Please wait...", true, true);

    }

    @Override
    protected Void doInBackground(Void... params) {
        // update your DB - it will run in a different thread
        loadingData();

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // hide your dialog here
        myDialog.dismiss();
}
4

2 回答 2

2

mAsycntask.cancel();当您想停止任务时调用。

然后

@Override
protected Void doInBackground(Void... params) {
    // update your DB - it will run in a different thread

    /* load data  */
    ....
    if (isCancelled()) 
       return;
    /* continue loading data. */

    return null;
}

文档: http: //developer.android.com/reference/android/os/AsyncTask.html#isCancelled ()

于 2012-07-22T11:36:09.390 回答
1

像这样声明你的 AsyncTaskasyncTask = new GridViewAsyncTask();

然后像以前一样执行它 (asyncTask.execute();) 并取消它:

asyncTask.cancel();

将该方法添加onCanceled到您的 AsyncTask 类并覆盖它。也许显示一个日志或其他东西!

@Override
protected Void onCancelled () {
    // Your Log here. Will be triggered when you hit cancell.
}
于 2012-07-22T11:51:50.767 回答