Search code examples
javaandroidmultithreadingandroid-serviceworker-thread

Synchronously executing long running methods in a Service


I have an android service that has a set of operations :

MyService.java

public class MyService extends Service {

    public int login() {
      //Invokes yet another logic to initiate login and waits for result 
      //synchronously and returns status code based on result of operation
    }

    public int logout() {
      //Invokes yet another logic to initiate logout and waits for result 
      //synchronously and returns the status code
    }
}

I am invoking the methods from a client activity say, MyClientActivity.java residing in the same process.

For each operations the service invokes some logic and waits for the result in a synchronous manner. When the service is executing all of this logic I do not want the user to perform anything else and just show a loading screen. So basically, after I have initiated an operation I want MyClientActivity to wait for the status code synchronously. Now I know that I cannot block the UI thread to avoid ANR.
How can I make this operation execute on a separate thread and then get the result back so that I can appropriately propagate the result back to the user by changing the UI based on this result.

I am pretty new to this and can't really grasp the concepts. If someone can explain along with an example that would be helpful.


Solution

  • I accomplished this by using a HandlerThread to create a Handler to which I am posting Runnables to do the background tasks.
    To do that main thread tasks (UI tasks) I am using mainLooper to create another Handler to which I posts Runnables to do operations on views.
    A rough representation of the code :

    mBackgroundHandler.post(new Runnable() {
    
        @Override
        public void run() {
            //Do background operation in synchronous manner as usual.
    
        mMainHandler.post(new Runnable() {
            @Override
            public void run() {
                //Remove loader, update UI
            }
        });
      }
    });