17

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 receive my messages which I'm sending from a Thread in my Service.

My code for the Thread in the service:

private class ServiceThread extends Thread {
    @Override
    public void run() {
        super.run();
        try{
            Log.i("Service", "TASK PERFORMED");

            int x = 0;
            for (int i = 0; i < 20; i++){
                x += (random.nextInt(20) + 20);
            }
            theInteger = x/20;
            Message msg = Message.obtain();
            msg.what = MY_RND_INT;
            msg.arg1 = theInteger;
            handler.sendMessage(msg);
        }catch(Exception e){
            e.getMessage();
        }
    }
}

My code for attempting to receive the message:

public Messenger mMessenger = new Messenger(new IncomingHandler());


class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SimpleService.MY_RND_INT:
                rndInt.setText(msg.arg1);
                break;
            default:
                super.handleMessage(msg);
        }
    }
}
1
  • @AnixPasBesoin Sorry, it was late just checked back in again! Thanks for your reply <3 Jun 4, 2015 at 8:38

1 Answer 1

40

Here's how you do it:

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();
}
4
  • Hi, I tried to used this code but when I use sendMessage() the app crashes. Does the receiver needs to be registered? Jul 8, 2018 at 18:30
  • @user1527152 yup it does.Check the sample code I provided with the answer. Nov 23, 2020 at 1:06
  • How to proceed if they are not on the same package? Jan 2, 2021 at 11:46
  • developer.android.com/reference/kotlin/androidx/… This class is deprecated. LocalBroadcastManager is an application-wide event bus and embraces layer violations in your app: any component may listen events from any other. You can replace usage of LocalBroadcastManager with other implementation of observable pattern, depending on your usecase suitable options may be androidx.lifecycle.LiveData or reactive streams.
    – lwei
    Apr 19 at 7:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.