I开发者_StackOverflow中文版'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?
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 );
}
}
}
}
精彩评论