Android,杀死/删除Asynctask在它的onPostExecute()

时间:2015-02-18 14:33:41

标签: android android-asynctask

我正在开发一款应用,当用户点击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);
    }

}

1 个答案:

答案 0 :(得分:1)

在按钮onClick上调用AsyncTask方法之前,使用AsyncTask.Status检查AsyncTask.execute()的状态:

    @Override
    public void onClick(View arg0) {
      if(a ==null){
        a = new A();
        a.execute();
      }
    }

onPostExecute Bnull中,a分配给@Override protected void onPostExecute(Void result) { super.onPostExecute(result); //doing st b.cancel(true); a=null; }

{{1}}