【问题标题】:Keeping a foreground service alive with binding通过绑定保持前台服务活跃
【发布时间】:2011-08-12 14:08:15
【问题描述】:

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

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

【问题讨论】:

  • 这里要提一下真的很重要,文档没有在任何地方指定这个问题。 一旦绑定到客户端,前台服务就失去了作为前台的纯粹性

标签: android service


【解决方案1】:

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

【讨论】:

  • 只是为了明确一点:这是否解决了您首先绑定到服务,然后在服务内部决定将其设为前台的场景?
  • 这不是问题的答案
猜你喜欢
  • 1970-01-01
  • 2010-11-11
  • 2013-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 2018-01-21
相关资源
最近更新 更多