how to force the AsyncTask to wait

不问归期 提交于 2020-01-06 20:08:30

问题


i want the AsyncTask to wait till it finishes. so i wrote the below code and i used .get() method as follows and as shown below in the code

    mATDisableBT = new ATDisableBT();

but at run time the .get() doesnt force ATDisableBT to wait, becuase in the logcat i receive mixed order of messages issued from ATDisableBT and ATEnableBT which means .get() on ATDisableBT did not force it to wait

how to force the AsyncTask to wait

code:

//preparatory step 1
    if (this.mBTAdapter.isEnabled()) {
        mATDisableBT = new ATDisableBT();
        try {
            mATDisableBT.execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    //enable BT.
    this.mATEnableBT = new ATEnableBT();
    this.mATEnableBT.execute();

回答1:


You should execute AsyncTask on UI thread, so using get() - which will block it makes no sense - it might get you ANR error.

If you are on HONEYCOMB and up, then AsyncTasks are executed on single executor thread, serially - so your mATEnableBT should get executed after mATDisableBT. For more see here:

http://developer.android.com/reference/android/os/AsyncTask.html#execute(Params...)

You might also switch from AsyncTask to Executors. AsyncTask is implemented using executors. By creating single threaded executor you make sure tasks will get executed serially:

ExecutorService executor = Executors.newSingleThreadExecutor();
//...

  executor.submit(new Runnable() {
    @Override
    public void run() {
      // your mATDisableBT code
    }
  });
  executor.submit(new Runnable() {
    @Override
    public void run() {
      // your mATEnableBT code
    }
  }); 



回答2:


You can do this way:

doInBackground of AsyncTask

@Override
protected Void doInBackground(String... params) {
   Log.i("doInBackground", "1");

    synchronized (this) {
    try {
          mAsyncTask.wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
   Log.i("doInBackground", "2");

 return null;
}

Outside this function from where you have to nstrong textotify AsyncTask to release from wait state:

new CountDownTimer(2000, 2000) {
 @Override
 public void onTick(long l) {

   }

  @Override
  public void onFinish() {
      synchronized (mAsyncTask) {
       mAsyncTask.notify();
     }
   }
}.start();

Here I have notified AsyncTask by CountDownTimer after 2 seconds.

Hope this will help you.



来源:https://stackoverflow.com/questions/34351918/how-to-force-the-asynctask-to-wait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!