从活动中正确解绑服务

问题描述

我有一个简单的 android 应用程序,其中包含一个绑定服务的 Activity。基本代码是这样的:

public class MyActivity extends AppCompatActivity {
    private MyService service;
    private boolean serviceIsBound;

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name,IBinder binder) {
            service = ((MyService.LocalBinder) binder).getService();
            serviceIsBound = true;
        }

        @Override
        public void onServicedisconnected(ComponentName name) {
            serviceIsBound = false;
        }
    };
    
    // Service gets bound via intent in onCreate()

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (serviceIsBound) {
            service.unbindService(serviceConnection);
        }
    }
}

当我关闭 Activity 时,这会在调用 java.lang.IllegalArgumentException: Service not registered 中产生错误 service.unbindService(...)

我尝试了 onStop() 而不是 onDestroy() --> 相同的错误。 我尝试删除 onDestroy() --> 我收到错误 android.app.ServiceConnectionLeaked。这个错误当然是有道理的——毕竟你应该清理你的服务连接。我只是不知道如何。

解决方法

在您调用 unbindService() 的同一个 Context 上调用 bindService()。据推测,鉴于您的样本结构,您正在 bindService() 实例上调用 MyActivity;如果是这样,也请对该 unbindService() 实例调用 MyActivity


请注意,您可能不应该这样做。在配置更改(例如,屏幕旋转)时,您的 MyActivity 实例将被销毁并重新创建。这意味着您将从服务解除绑定,然后再次绑定到它。如果没有其他任何东西绑定到该服务,并且该服务没有启动,则该服务将被销毁(当它未绑定时)然后重新创建(当新的活动实例再次绑定时)。

很可能您不需要绑定服务,特别是如果该服务与您的应用程序的其余部分在同一进程中。如果您确定需要绑定服务,请从配置更改后仍然存在的内容(例如 AndroidViewModel)进行绑定和解除绑定。在那里,您可以使用 Application 作为绑定/取消绑定调用的 Context。或者,如果您使用依赖倒置 (DI) 框架(例如 Dagger/Hilt、Koin),您可能会从中获得 Context。或者,如果合适,从一些 DI 管理的单例绑定和解除绑定,再次使用 Application 作为您的 `Context。

FWIW,this sample app 包含绑定服务。它由 this client app 使用,它绑定和解除绑定 ViewModel