我已经构建了一个服务,使用
事实证明,即使服务在前台运行,当所有活动都取消绑定时,它仍然会被杀死。 我该如何保持服务的运行,即使没有任何活动与其绑定?
startForeground()
来保持其运行,但我需要使用绑定方法将其连接到我的活动。事实证明,即使服务在前台运行,当所有活动都取消绑定时,它仍然会被杀死。 我该如何保持服务的运行,即使没有任何活动与其绑定?
我有点惊讶这个方法能够奏效,但实际上你可以从你要启动的服务中调用startService()
。即使没有实现onStartCommand()
,这仍然有效;只需确保在其他时间调用stopSelf()
来进行清理。
以下是一个示例服务:
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 );
}
}
}
}