Android 当应用程序转到后台时,使用公共基本活动停止服务

Android 当应用程序转到后台时,使用公共基本活动停止服务,android,android-activity,android-service,Android,Android Activity,Android Service,我有一个基本活动类来实现所有活动的通用行为。它们都扩展了这个基本活动 我在BaseActivity的onStart方法中绑定到服务,并在onStop方法中有条件地解除绑定。有条件地,我的意思是,根据用户选择的某些选项,当应用程序转到后台时,服务应该或不应该在后台运行 问题是,有时服务在不应该运行的情况下仍在运行(即,启用了终止服务的选项,并且有效地调用了unbindService()) 我认为在每一次活动更改中,服务都会被解除绑定并再次绑定。由于绑定的服务是引用计数的,可能我的服务绑定的次数多于

我有一个基本活动类来实现所有活动的通用行为。它们都扩展了这个基本活动

我在BaseActivity的onStart方法中绑定到服务,并在onStop方法中有条件地解除绑定。有条件地,我的意思是,根据用户选择的某些选项,当应用程序转到后台时,服务应该或不应该在后台运行

问题是,有时服务在不应该运行的情况下仍在运行(即,启用了终止服务的选项,并且有效地调用了unbindService())

我认为在每一次活动更改中,服务都会被解除绑定并再次绑定。由于绑定的服务是引用计数的,可能我的服务绑定的次数多于未绑定的次数,所以这就是为什么它在最后一直运行,即使我调用unbindService()

此外,报告还提到:

在匹配客户生命周期中的启动和终止时刻时,通常应该将绑定和解除绑定配对。例如:

如果只需要在活动可见时与服务交互,则应在onStart()期间绑定,在onStop()期间解除绑定

如果希望活动在后台停止时仍能收到响应,则可以在onCreate()期间绑定,在onDestroy()期间解除绑定。请注意,这意味着您的活动需要在其运行的整个时间内(甚至在后台)使用该服务,因此,如果该服务位于另一个进程中,则您会增加该进程的权重,系统更有可能会终止该进程


由于我正在尝试实现这两个选项,实现这一点的最佳方法应该是什么?

最后,我改变了方法,决定只使用
startService()
并使用本地广播接收器与服务通信

我在基本活动的
onCreate()
方法中启动服务,并在
onDestroy()
方法中停止服务。 然后,要从服务向活动发送消息,我使用以下命令:

private void sendBroadcastMessage(String msg) {
    Log.d(LOG_TAG, "send broadcast message: " + msg);
    Intent intent = new Intent(MyService.class.getSimpleName());
    // Add data
    intent.putExtra("message", msg);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
然后,在活动中通知:

// handler for the events launched by the service
private BroadcastReceiver mMyServiceReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Extract data included in the Intent
        String message = intent.getStringExtra("message");
        Log.d(LOG_TAG, "Got message: " + message);
        // Do stuff...
    }
};
@Override
public void onResume() {
    super.onResume();

    LocalBroadcastManager.getInstance(this).registerReceiver(mMonitorReceiver,
          new IntentFilter(MyService.class.getSimpleName()));
}
以及在活动中注册接收者:

// handler for the events launched by the service
private BroadcastReceiver mMyServiceReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Extract data included in the Intent
        String message = intent.getStringExtra("message");
        Log.d(LOG_TAG, "Got message: " + message);
        // Do stuff...
    }
};
@Override
public void onResume() {
    super.onResume();

    LocalBroadcastManager.getInstance(this).registerReceiver(mMonitorReceiver,
          new IntentFilter(MyService.class.getSimpleName()));
}

看看我的答案,我认为这是一个比不断绑定/解除绑定更好的方法。我的答案是错误的,请取消选中,这样我就可以删除它。该“某处”的链接是