Solution 1 :
What you need to do is binding your activities to the service (in your case: DatabaseService). Highly recommend you follow [this dev guide] https://developer.android.com/guide/components/bound-services and choose the simplest way to create a bound service: extending the binder class. So for short, what you need to do:
- implement your service following the sample LocalService
- config in AndroidManifest.xml:
<service android_name=".YourNewService" android_enabled="true"/>
- for activities needs to interact with the service, just implement them similar to BindingActivity of the guide. (No worries on service instantiation, singleton, etc.)
- Please note that you always can create a base BindingActivity class that handles all binding cores and let other activities extend the base binding class.
Happy coding!
Problem :
I have:
- a
MainActivity
- a
OtherActivity
- a
DatabaseService
, which is instantiated in MainActivity and which holds Sqliteconnection and functions likeList<data> getData()
How do I pass the DatabaseService to my OtherActivity ?
So far my DatabaseService was a Singleton and I referenced that Singleton from the OtherActivity, but I dont like that Solution.
I can’t also pass it with putExtra, because the Object is too complex to serialize.
There should be a more easier way to inject or pass the Service to the activity.
Does anyone have any hint for me ?
Comments
Comment posted by mcfly soft
Please comment when negate. Whats wrong with this question ?
Comment posted by March3April4
I don’t know the PROPER way to do so, but will using eventbus or something like eventbus using livedata do the job?
Comment posted by mcfly soft
Thank you. You guided me to the right way. I always used Singletons for this, but this is better.
Comment posted by Tech4Happie
I guess you started with AIDL. In case your app/service requires IPC and really needs to use AIDL, you can use singleton at the application level where an instance of service is held and handled there: start, bind, broadcast to registered activities to inform that service was bound, and stop, etc. For activities that need interaction with the service, they need to register a callback when the service is bounded and get bounded service from the singleton application. Be thread-safe in code then.