views:

118

answers:

2

Hello all,

I'm trying to think of a way on how to sync in between a local service and the main activity.

The local service has,

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

The activity needs to display this data. So when the activity starts up it needs to attach or start the local service and fetch the list. It also needs to be notified if the list is updated.

I think I would need to sync my list somehow so the local service does not add a new entry to it while the activity fetches the list when connecting to the service.

Any ideas?

Thanks.

+2  A: 

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

  • Intents. You can send ( by sendBroadcast (Intent intent) and receive ( by BroadcastReceiver ) Intents. Example scenario: Your activity at boot moment send a broadcast "GIVE_ME_ALL_DATA" and the service sends a response. If the service has new data, it also broadcasts "HEY_I_HAVE_NEW_DATA".
  • ContentProvider. The service and the activity read and write parallel from it. You can attach observer to specific data-url, so every listener will be informed about changes. If You use CursorAdapter for binding data to ui components, user interface will be updated automatically.
  • AIDL. It's a android'a IPC. You define interface for the service which be exposed to clients. Client at the beginning: establishes connection with the service, asks for data, register call-backs. If the service has new data, it invokes call-backs registered by clients.
Damian Kołakowski
+2  A: 

I answered a somewhat similar question here. In this answer is a link to a presentation hold by mark brady on the droidconf in berlin. In his slides he describes a framework that manages this kind of things. He also offers the source for this on github.

He proposes the following solution. Build a controller object that lives in the scope of an custom application class. The controller starts the service or a simple worker thread and notifies the UI if it gets notified by the service that something changed. He advises against the use of AIDL if it is not absolutely necessary.

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

Janusz