Synchronization between local service with stream and activity

I am trying to understand a way to synchronize between a local service and the main action.

Local service has

  • A thread with a socket connection that could receive data at any time.
  • List / array with data.
  • At any time, the socket can receive data and add it to the list.

Activity should display this data. Therefore, when an action begins, it needs to connect or start a local service and get a list. It should also be notified if the list is updated.

I think I will need to somehow synchronize my list so that the local service does not add a new record to it, while the activity retrieves the list when connecting to the service.

Any ideas?

Thanks.

+4
source share
2 answers

I answered a somewhat similar question here . This answer has a link to the presentation held by the brady sign on droidconf in Berlin. In his slides, he describes the structure that governs such things. He also offers a source for this on github .

He offers the following solution. Create a controller object that is in the custom class area of ​​the application. The controller starts the service or a simple workflow and notifies the user interface if it receives a notification by the service that something has changed. He advises using AIDL if this is not absolutely necessary.

The android documentation also offers an example on how to start a local process.

+5
source

There are many ways to establish a connection between an activity and a service and exchange data between them. You can communicate using the following solutions:

  • Intentions. You can send ( sendBroadcast (intention of intention) and receive ( BroadcastReceiver ). Example: scenario: your activity sends a broadcast "GIVE_ME_ALL_DATA" at the time of loading, and the service sends a response. If the service has new data, it also sends "HEY_I_HAVE_NEW_DATA".
  • ContentProvider Service and activity are read and written in parallel with it. You can bind an observer to a specific data URL so that each listener is informed of the changes. If you use the CursorAdapter to bind data to ui components, the user interface will automatically update.
  • AIDL . This is android'a IPC. You define an interface for the service that should be open to clients. The client at the beginning: establishes a connection to the service, requests data, registers callbacks. If the service has new data, it calls the callbacks registered by clients.
+3
source

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


All Articles