I\'m writing my first Android application and trying to get my head around communication between services and activities. I have a Service that will run in the background an
There are three obvious ways to communicate with services:
In your case, I'd go with option 3. Make a static reference to the service it self and populate it in onCreate():
void onCreate(Intent i) {
sInstance = this;
}
Make a static function MyService getInstance()
, which returns the static sInstance
.
Then in Activity.onCreate()
you start the service, asynchronously wait until the service is actually started (you could have your service notify your app it's ready by sending an intent to the activity.) and get its instance. When you have the instance, register your service listener object to you service and you are set. NOTE: when editing Views inside the Activity you should modify them in the UI thread, the service will probably run its own Thread, so you need to call Activity.runOnUiThread()
.
The last thing you need to do is to remove the reference to you listener object in Activity.onPause()
, otherwise an instance of your activity context will leak, not good.
NOTE: This method is only useful when your application/Activity/task is the only process that will access your service. If this is not the case you have to use option 1. or 2.