Transfer information from the service on which the foreground operation is performed

I have a service in android that constantly pulls out information about the sensor and sends them through the network interface.

On the other hand, I have several actions that will use these sensor values ​​in different ways. Since the service receives the values ​​in an event-driven path, how do I pass these values ​​only to activity that is in the foreground?

Thank you in advance

+4
source share
2 answers

I assume that this is the most common case of a "local" service, that is, it works in the same process as the actions.

There are two solutions: one with a service sending intentions to actions that register and unregister the correct BroadcastReceiver in onStart() and onStop() .

Another works with a listener mechanism. You can get a link to a service instance as described here . Writing the setListener(ServiceListener l) method setListener(ServiceListener l) in the service and the ServiceListener interface, you can implement the listener in your activity and install it in the service.

The purpose of the intent may be simpler and less risky, but you will have to adhere to the intent for sharing data.

The listener method is more flexible, but I read that you must unregister the listener, or you can end the mem. leakage of all activity.

+3
source

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.

+1
source

Source: https://habr.com/ru/post/1341230/


All Articles