How to create a shared library in Android

Robin picture Robin · Dec 2, 2011 · Viewed 8.6k times · Source

I have a library, say LIB, which exposes the quite a few APIs and classes for use by application developers.

If there are more than one applications that use LIB on the phone, I want only one instance of LIB to be created and running. It is somewhat similar to what Android Platform Services like LocationManager, SensorManager, PackageManager etc.

Specifically, there are two problems that are to be addressed:-

  1. How to make sure that there is only one instance of LIB ?
  2. How to deploy LIB(separate apk/ bundled with every application that uses it, but only one of them creating the library instance at any point of time) etc.
  3. Is there any other way(other than service/AIDL) to make sure that only one instance of LIB runs irrespective of the number of applications using it.

Answer

Robin picture Robin · Dec 15, 2011

Okay, after spending time on this, here the answers to my questions:-

Q. How to make sure that there is only one instance of LIB ? - Only through exposing the LIB functionality through a service.

Q. How to deploy LIB(separate apk/ bundled with every application that uses it, but only one of them creating the library instance at any point of time) etc. -

For service, there would be a separate apk(or probably bundled with one of the service client app),

Q. Is there any other way(other than service/AIDL) to make sure that only one instance of LIB runs irrespective of the number of applications using it.

Yes, that would be like LIB is bundled with every application. But that would need a strong communication protocol between the libraries using intents, so that one of them acts as master, and shares the data with the other libraries. Effectively, the LIB packaged within an apk starts its engine, only if no other instance is running. One way of accomplishing this is using broadcasts and to maintain security, permissions can be associated with the involved broadcast actions.