我已经建立了一个使用startForeground()
保持生命的服务,但是我需要使用绑定(bind)将其连接到我的 Activity 。
事实证明,即使该服务在前台运行,当所有 Activity 从该服务取消绑定(bind)时,该服务仍会被杀死。即使没有任何 Activity 绑定(bind),我如何保持该服务的生命力?
最佳答案
我对此工作感到有些惊讶,但是实际上您可以从正在启动的服务中调用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 );
}
}
}
}
关于android - 通过绑定(bind)使前台服务保持 Activity 状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7041285/