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
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. By "using a singleton" you mean that I should declare my methods static in the service class?
You can do this by making your own Interface where you declare for example " isServiceRunning() ". You can then bind your Activity to your Service, run the method isServiceRunning(), the Service will check for itself if it is running or not and returns a boolean to your Activity.
To provide binding for a service, you must implement the onBind() callback method. This method returns an IBinder object that defines the programming interface that clients can use to interact with the service.
But in order to keep a service alive like playing a song in a background. You'll need to supply a Notification to the method which is displayed in the Notifications Bar in the Ongoing section. In this way the app will keep alive in background without any interuption.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With