I have a service which is running in the background and an Activity that opens up every couple of minutes. When the activity opens the user pushes a button which needs to send a message to the service. The problems is that after the user pushes the button the activity closes. It appears that the activity is closing before the Activity can bind to the service so I am not able to send a message using my Messenger.
Is the best way to handle this to have the service listen to a broadcast receiver and then trigger that broadcast from my activity?
Thanks for any help you can offer!
-Nathan
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.end_activity_button:
endActivity();
break;
}
}
private void endActivity() {
sendMessageToService(ActivityService.MSG_CANCEL_ACTIVITY);
getActivity().finish();
}
/**
* Send data to the service
*
* @param intvaluetosend The data to send
*/
private void sendMessageToService(int intvaluetosend) {
if (mIsBound) {
if (mServiceMessenger != null) {
try {
Message msg = Message.obtain(null, intvaluetosend, 0, 0);
msg.replyTo = mMessenger;
mServiceMessenger.send(msg);
} catch (RemoteException e) {
}
}
}
}
Edit I have implemented Ricardo's solution but I am using localbroadcasts. Everything is now working properly. Thanks for the help!