我开始研究Asynctask Demo。我想要的是,“当我按下Android设备中的后退按钮时,我想停止在应用程序中运行的任务”
我在onBackPressed()方法上设置了这个东西但是之后在Logcat任务中没有停止。
我在哪里弄错了,帮我解决这个问题?
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");
}
}
}
答案 0 :(得分:7)
问题出在这一行
new CountDownTask().cancel(true);
您正在创建一个新的CountDownTask并取消它。取消现有的Asynctask实例。
例如
private CountDownTask cT; // declare as member
从
开始ct = new CountDownTask();
ct.execute();
并取消
ct.cancel(true);
答案 1 :(得分: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);
}