Search code examples
androidserviceandroid-activitybroadcastreceiver

Service to Activity communication


I am trying to update the UI (Activity) after some action has been performed in the service. This is very simple example but it doesn't seem to work for me. What am I missing here?

ExampleService:

  public class ExampleService extends IntentService{
    @Override
    protected void onHandleIntent(Intent intent) {
        notifyActivity();
    }

    private void notifyActivity() {
        Intent broadcast = new Intent(this, ExampleActivity.class);
        sendBroadcast(broadcast);
    }
  }

ExampleActivity:

public class ExampleActivity extends ListActivity {
         private BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
         Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }

    @Override
    public void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        registerReceiver(receiver, filter);
    }
}

Solution

  • You cannot send a broadcast to an anonymous dynamic receiver that way. You will need to define an action string in the Intent and use that action string in the IntentFilter.

    You might consider using LocalBroadcastManager for this scenario, for better performance. Here is a sample project demonstrating this.