2

I am start working on the Asynctask Demo. What I want is , "When I press the back button in the android device I want to stop the task which is running in the app "

I set up this thing on the onBackPressed() method but after this in the Logcat Task doesn't stop .

Where am I make the mistake , help me out of this ?

public class Activity1 extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new CountDownTask().execute();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
@Override
public void onBackPressed() {
    super.onBackPressed();
    new CountDownTask().cancel(true);
}

private class CountDownTask extends AsyncTask<Void, Integer, Void>{
    @Override
    protected void onPreExecute() {
        TextView tvCounter = (TextView) findViewById(R.id.tv_counter);
        tvCounter.setText("START");
    }

    @Override
    protected Void doInBackground(Void... params) {
        for(int i=15;i>=0;i--){
            try {
                Thread.sleep(1000);
                publishProgress(i);
                Log.e("Aka", String.valueOf(i));
                if(isCancelled()){
                    break;
                }
            } catch (InterruptedException e) {
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        TextView tvCounter = (TextView) findViewById(R.id.tv_counter);

        tvCounter.setText( Integer.toString(values[0].intValue()));         
    }

    @Override
    protected void onPostExecute(Void result) {
        TextView tvCounter = (TextView) findViewById(R.id.tv_counter);
        tvCounter.setText("DONE");          
    }       
}

}

4

2 回答 2

7

问题出在这一行

new CountDownTask().cancel(true);

您正在创建一个新的 CountDownTask 并取消它。取消现有的 Asynctask 实例。

例如

private CountDownTask cT;  // declare as member

开始喜欢

ct = new CountDownTask();
ct.execute();

并取消喜欢

ct.cancel(true);
于 2013-05-29T07:19:29.183 回答
1

您正在重新初始化任务,而是参考该任务并停止该任务,如下所示:

            public class Activity1 extends Activity {

              CountDownTask countDownTask = new CountDownTask();

         @Override
         public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

countDownTask.execute();
             }

        @Override
          public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
         return true;
            } 
          @Override
         public void onBackPressed() {
            super.onBackPressed();
         countDownTask.cancel(true);
           }
于 2013-05-29T09:19:01.047 回答