In my experience, I have found that it is best to associate your actions with a service using
bindService(new Intent( this, ClassroomService.class), mConnection, Context.BIND_AUTO_CREATE );
Once the service is bound, I send a message from my activity to the service registering the action message handler in the Activity ServiceConnection onServiceConnected ().
public void onServiceConnected( ComponentName className, IBinder service ) { MyService mService = new Messenger(service); Message msg = Message.obtain(null, MyService.MSG_REGISTER_CLIENT ); msg.replyTo = mMessenger; mService.send(msg); }
On the service side, when he received this message, I save the handler passed in the replyTo member and use this handler to send messages back to the “registered” activity. If no activity is currently registered, the message is ignored.
When disconnecting from the service, I will also send a MyService.MSG_UNREGISTER_CLIENT message to tell the service to clear the stored handler link.
If you get attached to the service in your onResume () actions and disable onPause (), then the activity will receive messages only in the foreground.
Hope this helps.
source share