Search code examples
javaandroidmultithreadingconcurrencyjava.util.concurrent

How to pause execution until listener finished?


How to implement pause() and resume() in a way that pause() stops code execution (prevents proceedFurther() from execution) until resume() is called by clicking the button?

button.setOnClickListener(new View.OnClickListener() {
    @Override
     public void onClick(View v) {
         resume();
     }
});
pause();
proceedFurther();

As I understand OnClickListener creates a separeate thread and main thread must be stopped somehow with concurrency-stuff I'm not aware of.


Solution

  • Your assumption is wrong - the code inside the on click listener is executed in the UI thread.

    So, to define the task better - you wan't to make sure that proceedFurther() is called only after resume() has been executed.

    They are two ways to achieve this:

    • If you don't need background processing - resume doesn't touch the database or the network, or other potentially memory - heavy and time consuming stuff, you can just have sequential method calls in the callback:

      public void onClick(View v) {
          resume();
          proceedFurther();
      }
      
    • If you do need to execute resume() in a background thread, you can indeed use the AsyncTask. You just need to call resume() in doInBackground() and proceedFurther() in onPostExecute().