How to call a method in activity from a service

Upvote picture Upvote · Feb 15, 2013 · Viewed 32.7k times · Source

There is a service that listens for some voice. If voice matches a string a certain method is invoked in the service object.

public class SpeechActivationService extends Service {

     public static Intent makeStartServiceIntent(Context pContext){    

         return new Intent(pContext, SpeechActivationService.class);
     }

     //...

     public void onMatch(){
         Log.d(TAG, "voice matches word");
     }

     //...
}

This is how I start the service in my activity:

Intent i = SpeechActivationService.makeStartServiceIntent(this);
startService(i);

From this service method, how can I invoke a method that resides in the activity object? I don't want access from activity to service, but from service to activity. I already read about handlers and broadcasters but could not find/understand any example. Any ideas?

Answer

Tony Wickham picture Tony Wickham · Aug 7, 2014

Assuming your Service and Activity are in the same package (i.e. the same app), you can use LocalBroadcastManager as follows:

In your Service:

// Send an Intent with an action named "my-event". 
private void sendMessage() {
  Intent intent = new Intent("my-event");
  // add data
  intent.putExtra("message", "data");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

In your Activity:

@Override
public void onResume() {
  super.onResume();

  // Register mMessageReceiver to receive messages.
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("my-event"));
}

// handler for received Intents for the "my-event" event 
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Extract data included in the Intent
    String message = intent.getStringExtra("message");
    Log.d("receiver", "Got message: " + message);
  }
};

@Override
protected void onPause() {
  // Unregister since the activity is not visible
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onPause();
}

From section 7.3 of @Ascorbin's link: http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#ownreceiver_localbroadcastmanager