Android – Keep updating Android UI from service, when activity is closed / restarted

androidhandlerserviceuser interface

Trying to figure this out for a while. I have got an app that runs a countdown in a separate service which calls startsForeground, displaying a notification. I start the countdown service from a button:

            Intent i = new Intent(getApplicationContext(),  PomoService.class);
            i.putExtra("EXTRA_MESSENGER", new Messenger(handler));
            startService(i);

and I update the UI with an handler, which received the bundle data telling how many milliseconds are left in the countdown, sent via message in the onTick() method:

Messenger messenger = (Messenger)extras.get("EXTRA_MESSENGER");
        Message msg = new Message();
        Bundle b = new Bundle();
        b.putLong("remainingTime", millisUntilFinished);
        msg.setData(b);
        try {
            messenger.send(msg);
        } catch (RemoteException e) {
            Log.i("error", "error");
        }

And in the activity:

    private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        long sentTime = msg.getData().getLong("remainingTime");
        textCountdownMin.setText(String.format("%02d", (sentTime/1000)/60));
        textCountdownSec.setText(":" + String.format("%02d", (sentTime/1000)%60));
    }
};

The whole setup works fine, the only problem is that if the user hits the back button or swipes away the app from the recent app list and then reopens it either from the drawer or the ongoing notification, the text is not being updated any more. The countdown is still ongoing though, as I can see it both from the notification being still displayed and from the fact that I use an AlarmManager to wake the screen, and that's fired up correctly.

Any clue on what measures I should take?

Best Answer

I solved using a LocalBroadcastManager as outlined in this question: Android update activity UI from service