0

Let's say I have a an Android started service that does some tasks as this example:

-Service starts

-Does task A, does task B, then downloads file 1, downloads file 2, and Finally does task C.

-Service stops

Let's say while the service is doing task B, an activity binds to it. What is the correct way to check what task is the service currently doing to update the activity UI?

The way I'm doing now is by creating a Boolean flag for each task while in process and then when the activity binds to the service it checks which flag is true to send the right callback to the activity. It works, but with more tasks, it gets more complicated and even harder when errors occur.

private boolean doingTaskA = false;
private boolean doingTaskB = false;
.
.

public void doTaskA() {
   // Task started, set the flag to true.
   doingTaskA = true;
   // send callback to update activity UI.
   callback.onDoingTaskA();
   // doing some API calls that takes some time to retrieve information
   ...
   // Task finished, set to false.
   doingTaskA = false;
}
public void doTaskB() {
   // Task started, set the flag to true.
   doingTaskB = true;
   // send callback to update activity UI.
   callback.onDoingTaskB();
   // doing some API calls that takes some time to retrieve information
   // while doing in background, an activity binds to this service (assuming 
   // not already bound).
   ...
   // Task finished, set to false.
   doingTaskB = false;
}

public IBinder onBind(Intent intent) {
  // when binding check to see what the service is doing.
  if(doingTaskA){
    // send callback to update activity UI.
    callback.onDoingTaskA();
  }
  if(doingTaskB){
    // send callback to update activity UI.
    callback.onDoingTaskB();
  }
  ...
}

Please help me with efficient and reliable way of doing that.

Thanks!

Sam Matt
  • 123
  • 2
  • 8
  • 1
    For that you can make use of event bus and just fire events when particular task is executed inside your service – Mr. Patel Oct 11 '19 at 03:28
  • Thanks for your suggestion, but my question is not about how to communicate with activity. I'm using Binder with callbacks. Here, I'm assuming the activity is in background, and then it binds to the service at some point. How will the activity receive the event bus when it's in background or destroyed? My situation here is when the activity binds while service already in middle of executing the task. Can you please explain more in details? – Sam Matt Oct 11 '19 at 03:33
  • Mr. Patel, actually you are correct. Using sticky EvenBus events did the trick. Thanks so much for the hint! – Sam Matt Oct 21 '19 at 01:34
  • Glad it helped ;) – Mr. Patel Oct 21 '19 at 08:32

0 Answers0