Android periodically sends data from a service to Activity

I have an application that starts the service the first time it starts. After that, it periodically retrieves data from the server.

  • I opened my activity, and if there is an update button, I already have a service that already receives data in the background at the moment when I want to disable the button, and as soon as new data is downloaded, I have to show it in action and activate refresh button.

  • If the action is not running, it should show a notification.

So, the second point was the simplest and most fulfilled. I’m stuck in step 1. How do I periodically send activity data from a service? I use a database to store data.

Any help on this?

+4
source share
1 answer
  • You can send your “Your Messages” service to your Messenger activity so that it responds as soon as the service detects new content (see this section on Android developers’s help / activity about Messenging).

Here are examples for two-way messaging (from service to activity and from activity to service). Quoting a document:

You can see an example of how to provide two-way messaging in MessengerService.java (service) and MessengerServiceActivities.java (client) samples.

Here are the relevant parts.

Inbound handler in action:

  /** * Activity Handler of incoming messages from service. */ class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case MessengerService.MSG_SET_VALUE: mCallbackText.setText("Received from service: " + msg.arg1); break; default: super.handleMessage(msg); } } } /** * Activity target published for clients to send messages to IncomingHandler. */ final Messenger mMessenger = new Messenger(new IncomingHandler()); 

In a service showing only the relevant parts:

 /** * Handler of incoming messages from clients. */ class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { //obtain Activity address from Message Messenger mClient=msg.replyTo; try { // try to send it some mValue mClient.send(Message.obtain(null,MSG_SET_VALUE, mValue, 0)); } catch (RemoteException e) { // The client is dead. Remove it mClient=null; } } } /** * Target we publish for clients to send messages to IncomingHandler. */ final Messenger mMessenger = new Messenger(new IncomingHandler()); 
  • You can also bind to your service from your activities and periodically call one of your service methods to check for new content. To do this, if your service is another application, you should use helpl (this is more complicated). If it is in one package, I advise you to use the local service binding much easier
+10
source

All Articles