通过绑定使前台服务保持活动状态

时间:2011-08-12 14:08:16

标签: android service

我已经构建了一个使用startForeground()保持活力的服务,但是我需要使用绑定将它连接到我的活动。

事实证明,即使服务在前台运行,当所有活动都解除绑定时,它仍然会被杀死。即使没有绑定任何活动,我怎样才能保持服务的活力?

1 个答案:

答案 0 :(得分:5)

我对此有点惊讶,但您实际上可以从您正在启动的服务中调用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 );    
            }
        }
    }
}