user200658 user200658 - 1 year ago 242
Android Question

Android update activity UI from service

I have a service which is checking for new task all the time. If there is new task, I want to refresh the activity UI to show that info.
I did find this example. Is that a good approch ? Any other examples?


Answer Source

In your service: (using COPA as service in example below).

Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster:

broadcaster = LocalBroadcastManager.getInstance(this);

When you want to notify the UI of something:

static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";

static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";

public void sendResult(String message) {
    Intent intent = new Intent(COPA_RESULT);
    if(message != null)
        intent.putExtra(COPA_MESSAGE, message);

In your Activity:

Create a listener on onCreate:

public void onCreate(Bundle savedInstanceState) {
    receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String s = intent.getStringExtra(COPAService.COPA_MESSAGE);
            // do something here.

and register it in onStart:

protected void onStart() {
        new IntentFilter(COPAService.COPA_RESULT)

protected void onStop() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download