AsyncTask在调用new myTask.cancel()方法后仍然运行。当我按下后退按钮,或者当我用微调器更改片段时,我调用该方法。我记录了增量的进度,即使在调用myTask.cancel之后,增量仍然会增加。
我的AsyncTask类
public class myTask extends AsyncTask<Void, Integer, String> {
private static final String TAG = "myTask";
private ProgressBar budgetProgressBar=null;
private TextView textView1;
double b_val,e_val;
int position;
private Context mContext;
public myTask(){
}
public myTask(double b_val ,double e_val,ProgressBar budgetProgressBar, TextView textView1) {
this.b_val = b_val;
this.textView1=textView1;
this.e_val = e_val;
pStatus = (int) e_val;
this.budgetProgressBar= budgetProgressBar;
position = (int) budgetProgressBar.getTag();
maxBudget = (int) this.b_val;
}
int pStatus;
int maxBudget;
@Override
protected void onPreExecute() {
budgetProgressBar.setMax(maxBudget);
budgetProgressBar.setVisibility(View.VISIBLE);
budgetProgressBar.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
// }
}
@Override
protected String doInBackground(Void... params) {
int incrementor =10;
for (int i = incrementor; i<=pStatus && !isCancelled(); i+=incrementor){
if (isCancelled()){
Log.d(TAG, "doInBackground: CANCELLED");
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
return "Complete";
}
@Override
protected void onProgressUpdate(Integer... p) {
super.onProgressUpdate(p);
Log.d(TAG, "onProgressUpdate: ");
if ((int) budgetProgressBar.getTag() == position){
budgetProgressBar.incrementProgressBy(p[0]);
budgetProgressBar.setProgress(p[0]);
textView1.setText(p[0]+"/"+maxBudget);
// Log.d(TAG, "Setting progress to " + p[0]);
double calc =(e_val/b_val)*100;
if (calc>100){
calc-=100;
textView1.setText("-"+ ((int) calc)+"%");
}else{
textView1.setText(((int) calc)+"%");
}
}
}
}
取消AsyncTask
new myTask().cancel(true);
答案 0 :(得分:4)
即使方法名称暗示AsyncTask#cancel
,doInBackground
也不会停止doInBackground
任务。会发生什么情况onCancel
将一直运行到最后,最后会调用onPostExecute
而不是AsyncTask
。
因此,您可能希望向AsyncTask
private volatile boolean isRunning = true;
public void cancelTask() // sets isRunning to false
添加易失性字段标记,并将其设置为已取消,例如
isRunning
您要检查isCancelled()
而不是{{1}}。
答案 1 :(得分:1)
请阅读本文档以更好地了解Android中的AsyncTask https://developer.android.com/reference/android/os/AsyncTask.html