Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping a foreground service alive with binding

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?

like image 651
derekerdmann Avatar asked Aug 12 '11 14:08

derekerdmann


People also ask

How do you bind a foreground service?

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() .

Can foreground service be killed by Android?

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.

How will you start and stop the bound service?

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() .


1 Answers

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 );    
            }
        }
    }
}
like image 128
derekerdmann Avatar answered Oct 11 '22 22:10

derekerdmann