我已经构建了一个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 );
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4012 次 |
| 最近记录: |