我正在开发一款应用,当用户点击Button
时,它会执行Asynctask
该类调用方法onPostExecute
方法调用另一个Asynctask
!它可以在用户点击一次时发挥作用,但在第二次崩溃时会显示Cannot execute task: the task has already been executed (a task can be executed only once)
。
public class Test extends Activity {
A a;
B b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
a = new A();
a.execute();
}
});
}
class A extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
// doing st
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
runB();
a.cancel(true);
}
}
public void runB() {
b = new B();
b.execute();
}
class B extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
// doing st
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//doing st
b.cancel(true);
}
}
答案 0 :(得分:1)
在按钮onClick上调用AsyncTask
方法之前,使用AsyncTask.Status检查AsyncTask.execute()
的状态:
@Override
public void onClick(View arg0) {
if(a ==null){
a = new A();
a.execute();
}
}
在onPostExecute
B
个null
中,a
分配给@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//doing st
b.cancel(true);
a=null;
}
:
{{1}}