Sending a simple message from Service to Activity

后端 未结 1 2089
感动是毒
感动是毒 2021-02-13 16:02

I am trying to find a way to send an integer value from my Service to my MainActivity, yet I can\'t figure it out with the tutorials on the internet. I am using a Handler to rec

相关标签:
1条回答
  • 2021-02-13 16:45

    Assuming that your Activity and Service are in the same package...

    Service side

    // Supposing that your value is an integer declared somewhere as: int myInteger;
    private void sendMessage() {
      // The string "my-message" will be used to filer the intent
      Intent intent = new Intent("my-message");
      // Adding some data
      intent.putExtra("my-integer", myInteger);
      LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
    

    Activity side

    @Override
    public void onResume() {
      super.onResume();
      // This registers messageReceiver to receive messages.
      LocalBroadcastManager.getInstance(this)
                           .registerReceiver(messageReceiver, new IntentFilter("my-message"));
    }
    
    // Handling the received Intents for the "my-integer" event 
    private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        // Extract data included in the Intent
        int yourInteger = intent.getIntExtra("my-integer", -1); // -1 is going to be used as the default value
      }
    };
        
    @Override
    protected void onPause() {
      // Unregister since the activity is not visible
      LocalBroadcastManager.getInstance(this).unregisterReceiver(messageReceiver);
      super.onPause();
    }
    
    0 讨论(0)
提交回复
热议问题