【发布时间】:2011-08-12 14:08:15
【问题描述】:
我已经构建了一个使用startForeground() 来维持生命的服务,但我需要使用绑定将它连接到我的活动。
事实证明,即使服务在前台运行,当所有活动都与它解除绑定时,它仍然会被杀死。即使没有绑定任何活动,我如何才能使服务保持活动状态?
【问题讨论】:
-
这里要提一下真的很重要,文档没有在任何地方指定这个问题。 一旦绑定到客户端,前台服务就失去了作为前台的纯粹性。
我已经构建了一个使用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 );
}
}
}
}
【讨论】: