0

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!

Nath5
  • 1,665
  • 5
  • 28
  • 46

1 Answers1

0

Is this mServiceMessenger a service of yours to send a message? I have exactly the same scenario as you but I do it differently.

On my Service, I register a BroadcastReceiver like in this post: https://stackoverflow.com/a/4805733/362298

Then, in my activity, whenever I need to send a message, I simply call:

Intent myIntent = new Intent("MY_ACTION_FOR_THE_SERVICE_TO_HANDLE");
//Put some extra here
sendBroadcast(myIntent);

I actually do this right before calling finish() on my activity as well. Is there any reason why you are not using sendBroadcast?

Community
  • 1
  • 1
Ricardo
  • 7,785
  • 8
  • 40
  • 60
  • Only because I though that it was more efficient to send messages by using a Messenger and binding to the service. If that doesn't work in this case, I guess I will be switching to your approach. Thanks for the feedback! – Nath5 Nov 30 '13 at 16:04
  • I'm not sure the bind will work in your case because you are finishing the activity. – Ricardo Nov 30 '13 at 16:06