Skip to content Skip to sidebar Skip to footer

Send Message Not Reaching The Handler In Activity

I am having the service and activity. inside service i am sending the message. I am trying to catch it inside the main activity. But message is not reaching the handler in activity

Solution 1:

All messages you are sending using Handler.sendMessageXXX will be handled by the same Handler object. So you have to pass the Handler from Activity to Service. It can be done using Messenger class.

Activity:

publicclassMyActivityextendsActivity {
    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        finalHandlerhandler=newHandler() {
            @OverridepublicvoidhandleMessage(Message msg) {
                Toast.makeText(MyActivity.this, "handleMessage " + msg.what, Toast.LENGTH_SHORT).show();
            }
        };

        finalIntentintent=newIntent(this, MyService.class);
        finalMessengermessenger=newMessenger(handler);

        intent.putExtra("messenger", messenger);
        startService(intent);
    }
}

Service:

publicclassMyServiceextendsIntentService {
    publicMyService() {
        super("");
    }

    @OverrideprotectedvoidonHandleIntent(Intent intent) {
        finalMessengermessenger= (Messenger) intent.getParcelableExtra("messenger");
        finalMessagemessage= Message.obtain(null, 1234);


        try {
            messenger.send(message);
        } catch (RemoteException exception) {
            exception.printStackTrace();
        }
    }
}

Post a Comment for "Send Message Not Reaching The Handler In Activity"