In my Android app there is a Service performing long-running task (e.g. playing music) which can be in one of two states: running or paused. There is a single 'pause/resume' image button to pause/resume the task. And also the task can be paused due to other reasons (not from UI). The button should look differently depending on the current state of the task (running or paused). So I need to sync the button image with the actual state of the task.
Now I've come up with the following solution:
My Service has static pause
and resume
methods which send intents to itself like this:
public static void pause(Context context) {
Intent intent = new Intent(context, MyService.class);
intent.putExtra("PAUSE", true);
context.startService(intent);
}
public static void resume(Context context) {
Intent intent = new Intent(context, MyService.class);
intent.putExtra("RESUME", true);
context.startService(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getBooleanExtra("PAUSE", false)) {
doPause();
} else if (intent.getBooleanExtra("RESUME", false)) {
doResume();
}
return START_STICKY;
}
Since doPause()
and doResume()
can also be called from other places, I can't just set image to the ImageButton when calling MyService.pause()
/ MyService.resume()
: the button image and the actual state of the task may become out of sync. Instead I use LocalBroadcastManager to notify activity when the button should be updated:
public void doPause() {
paused = true;
... // Do some stuff to pause the service
// Notify about state change
Intent intent = new Intent("SERIVCE_STATE_CHANGED");
intent.putExtra("PAUSED", true);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
Code for doResume()
is analogous.
So, my activity registers the receiver and sets the image in onReceive()
.
The solution seems to work. But my question is whether there is a better/simpler way to achieve the same goal? Any best practices?