3

I am learning how to cancel asyncTask so there is no uses on the code below.

I tried to called the asyncTask and execute it then cancel it and execute it.

        MyAsyncTask asyncTask = new MyAsyncTask();
        Log.i("cancel","cancel 1");     
        asyncTask.execute();
        Log.i("cancel","cancel 2");
        asyncTask.onCancelled();
        Log.i("cancel","cancel 3");
        asyncTask.execute();
        Log.i("cancel","cancel done");

"cancel 1" and "cancel 2" is executed finely as it shown on logcat but ActivityThread.performLaunchActivity error is thrown when "cancel 3" is trying to execute. (cancel 3 is not showing on logcat) Anything wrong with my asyncTask code?

private class MyAsyncTask extends AsyncTask<String,Integer,Void>{

    private ArrayList<Map<String, String>> list;
    private ProgressBar progressBar;
    @Override
    protected Void doInBackground(String... arg0) {

        progressBar = (ProgressBar)findViewById(R.id.year_expense_progressbar);
        progressBar.setVisibility(View.VISIBLE);
        getListView().setVisibility(View.GONE);
        textView.setVisibility(View.GONE);

        list = new ArrayList<Map<String, String>>();

        String time = "";
        String category = "";
        String expense = "";
        String day = "";
        String month = "";


        totalExpense = 0;       


        Cursor c = SQLLiteAdapter.fetchAllItems();

        while(c.moveToNext() != false){

            if(isCancelled()){
                Log.e("cancel","cancel inside background");
                break;
            }


            // if there is nothing is input, don't execute verifyLevel
            if(tokenizedResult.isEmpty()) break;


            category = c.getString(c.getColumnIndex(SQLLiteAdapter.col_category));
            expense = c.getString(c.getColumnIndex(SQLLiteAdapter.col_price));
            time = c.getString(c.getColumnIndex(SQLLiteAdapter.col_time));
            day = c.getString(c.getColumnIndex(SQLLiteAdapter.col_day));
            month = c.getString(c.getColumnIndex(SQLLiteAdapter.col_month));


            VerifyLevel a = new VerifyLevel(tokenizedResult,category,expense,time,day,month); 
            if(!a.isEmpty()){
                list.add(a.addToList());
            }           

            totalExpense += a.totalExpense;          
        }



        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {
        progressBar.setVisibility(View.GONE);
        getListView().setVisibility(View.VISIBLE);
        textView.setVisibility(View.VISIBLE);
        fillData(list);
        textView.setText("Total Expense is "+convertNumeric(totalExpense));         
        Log.i("yearExpense","buildList is finished");

    }

    @Override
    protected void onCancelled(){
        super.onCancelled();
        list.clear();
        progressBar.setVisibility(View.GONE);
        totalExpense = 0;
        Log.i("yearEx","Cancel asyncTask");
        Toast.makeText(getApplicationContext(), "cancelled", Toast.LENGTH_SHORT).show();

    }       
}
4

4 回答 4

13

我的方法略有不同,也许有点冗长。但它一直有效,没有任何问题。

这段代码在doInBackground(). 如果你有 afor... loop在它,然后使用break;语句。如果您不使用 a for.... loop,请将其删除。

// CHECK IF THE USER HAS CANCELLED THE TASK
if (isCancelled())  {
    cancelTask = true; // (OPTIONAL) THIS IS AN ADDITIONAL CHECK I HAVE USED. THINK OF IT AS A FAIL SAFE.
    break; // REMOVE IF NOT USED IN A FOR LOOP
}

你已经有一个Asynctask声明的:MyAsyncTask asyncTask = new MyAsyncTask();。除此之外,还要创建两个boolean. 打电话给他们,例如:

boolean blMyAsyncTask;
boolean cancelTask;

现在,在 中onPreExecute(),切换 blMyAsyncTask 实例的状态:

blMyAsyncTask = true;

并且在onPostExecute()

blMyAsyncTask = false;

而且,在同样的情况下onPostExecute(),我也在检查cancelTask boolean. 例如:

if (cancelTask == false)    {
    // THE NORMAL CODE YOU HAVE IN YOUR onPostExecute()
}

最后,在onDestroy()(我使用这个,但我怀疑它onPause()也可以工作。老实说从来没有做过onPause()),检查状态boolean blMyAsyncTask

if (blMyAsyncTask== true)   {
    asyncTask.cancel(true);
}

正如我在开始时所说,它很长,甚至可能很复杂,但它从未失败过。如果你愿意的话,我也认为这有点模块化。如果我有更多Asycntasks添加到 中Activity,我可以在 中添加另一个检查onDestroy()

于 2013-04-11T11:36:23.637 回答
3

你不应该asyncTask.onCancelled();直接打电话。您可以致电cancel(true)并在您的内部doInBackground()检查isCancelled()

于 2013-04-11T11:13:54.407 回答
0

要取消 AsyncTask,请调用以下行。

asyncTask.cancel();

onCancelled() 是一个在调用取消时执行的覆盖方法。

于 2013-04-11T11:13:08.247 回答
0

你可以使用

asynctask.cancel(true);

或者

asyncTask.wait();

"true" 如果执行此任务的线程应该被中断;否则,允许完成正在进行的任务

于 2013-04-11T11:18:41.610 回答