I've built a service that uses startForeground()
to stay alive, but I need to use binding to connect it to my activities.
It turns out that even if the service is running in the foreground, it's still killed when all activities unbind from it. How can I keep the service alive, even when no activities are bound to it?
You can also call bindService() from MainActivity. kt to create a Service. Alternatively, you can call bindService() after startForeground() and then bind the Service by calling bindService() . (You can also create a Service with bindService() and then call startForeground() .
The Android system stops a service only when memory is low and it must recover system resources for the activity that has user focus. If the service is bound to an activity that has user focus, it's less likely to be killed; if the service is declared to run in the foreground, it's rarely killed.
Binding to a started service If you do allow your service to be started and bound, then when the service has been started, the system does not destroy the service when all clients unbind. Instead, you must explicitly stop the service by calling stopSelf() or stopService() .
I'm a bit surprised this works, but you can actually call startService()
from the service you're starting. This still works if onStartCommand()
is not implemented; just make sure that you call stopSelf()
to clean up at some other point.
An example service:
public class ForegroundService extends Service {
public static final int START = 1;
public static final int STOP = 2;
final Messenger messenger = new Messenger( new IncomingHandler() );
@Override
public IBinder onBind( Intent intent ){
return messenger.getBinder();
}
private Notification makeNotification(){
// build your foreground notification here
}
class IncomingHandler extends Handler {
@Override
public void handleMessage( Message msg ){
switch( msg.what ){
case START:
startService( new Intent( this, ForegroundService.class ) );
startForeground( MY_NOTIFICATION, makeNotification() );
break;
case STOP:
stopForeground( true );
stopSelf();
break;
default:
super.handleMessage( msg );
}
}
}
}
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