1

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.

aikrikunov95
  • 307
  • 4
  • 13
  • See http://stackoverflow.com/questions/20900885/what-is-the-best-way-to-stop-execution-for-few-seconds-in-java and http://stackoverflow.com/questions/2622804/how-to-indefinitely-pause-a-thread-in-java-and-later-resume-it – Jibran Khan Jul 23 '15 at 10:14

2 Answers2

1

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().

Danail Alexiev
  • 7,624
  • 3
  • 20
  • 28
  • I just need to proceed after the button is clicked. May be using OnClickListener is a wrong choice and there's a method like `waitForAction()` which stops code execution and waits for click? – aikrikunov95 Jul 23 '15 at 11:18
  • Unfortunately, you can't stop the code execution and wait for a click. This means you will block the main thread, effectively rendering your app unresponsive. This won't be tolerated by the OS. Why don't you just call the proceed method from inside the onClick()? – Danail Alexiev Jul 23 '15 at 11:25
  • because `ProceedFurther()` goes after switch and only last case needs waiting for a click, while all previous don't, so putting `ProceedFurther()` in `Listener`'s `onClick()` will create code duplicating, which is a bad design. – aikrikunov95 Jul 24 '15 at 18:21
0

Is the resulting onClick() function invoked on the main UI thread.

If you want do to some stuff in background use AnsycTask.

eddykordo
  • 607
  • 5
  • 14