使用绑定来保持前台服务持续运行

5
我已经构建了一个服务,使用startForeground()来保持其运行,但我需要使用绑定方法将其连接到我的活动。
事实证明,即使服务在前台运行,当所有活动都取消绑定时,它仍然会被杀死。 我该如何保持服务的运行,即使没有任何活动与其绑定?

1
这里非常重要的一点是,文档中没有任何地方指定这个问题。一旦前台服务被绑定到客户端,它就失去了作为前台服务的纯粹性。 - Talha
1个回答

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 );    
            }
        }
    }
}

只是为了明确:这是否解决了您先绑定服务,然后在服务内部决定将其设置为前台的场景? - android developer
这不是问题的答案。 - Vlad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接