I'm starting a service in my application using startService.
I do not want to use bindService as I want to handle the service life time myself.
How can I get an instance to the service started if I do not use bindService? I want to be able to get a handler I've created in the service class to post messages from the activity.
Thanks.
/ Henrik
I do not want to use bindService as I
want to handle the service life time
myself.
That does not mean you have to avoid bindService()
. Use both startService()
and bindService()
, if needed.
How can I get an instance to the
service started if I do not use
bindService?
Either use bindService()
with startService()
, or use a singleton.
Here's another approach:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
private Binder binder;
@Override
public void onCreate() {
super.onCreate();
binder = new Binder();
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class Binder extends android.os.Binder {
public MyService getService() {
return MyService.this;
}
}
}
onServiceConnected(...) can cast its argument to MyService.Binder
and call getService()
on it. This avoids the potential memory leak from having a static reference to the service. Of course, you still have to make sure your activity isn't hanging onto a reference.