How to call a method in activity from a service

前端 未结 4 731
失恋的感觉
失恋的感觉 2020-12-08 07:14

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 SpeechActivationSe         


        
4条回答
  •  旧巷少年郎
    2020-12-08 07:41

    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

提交回复
热议问题