package com.example.asynctask;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
ProgressBar progressbar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressbar = (ProgressBar) findViewById(R.id.progressBar);
}
class ProgressTask extends AsyncTask<Integer, Integer, Void> {
private boolean flag = true;
@Override
protected void onPreExecute() {
progressbar.setMax(100);
}
@Override
protected void onCancelled() {
//progressbar.setMax(0);
flag = false;
Log.v("onCancelled:flag", String.valueOf(flag));
}
@Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
int start = params[0];
for (int i = start; i <= 100; i=i+10) {
if (!flag) {
break;
} else {
publishProgress(i);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.e("ThreadError", e.toString());
}
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
progressbar.setProgress(values[0]);
}
@Override
protected void onPostExecute(Void result) {
Log.v("Progress", "Finish");
}
}
public void onClick(View v) {
ProgressTask task = new ProgressTask();
switch (v.getId()) {
case R.id.start:
task.execute(10);
break;
case R.id.stop:
task.cancel(true);
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
这是一个简单的 AsyncTask 应用程序,当您点击开始时,它会开始更新进度条。但是当你停止时,它不会停止。事情是当你调用task.cancel(true)时, onCancelled ()方法会被调用并将 flag 的值更改为false,但在onCancelled()中 flag 的值仍然为 true。我也尝试过isCancelled()代替标志变量,但没有成功。有一刻我的问题类似于Ollie C,但在我的情况下没有抛出异常。