Android 通过方向改变保持服务连接

Android mantain service connection through orientation change

我正在开发一个需要 Activity 绑定到 Service 的应用程序。我使用的是通常的 bindServiceunbindService。但是,我试图通过方向更改来保持绑定。为此,我将覆盖 onRetainCustomNonConfigurationInstance。但我面临着问题。要调用 unbind,我检查 Activity 是否以 isFinishing() 结束并且工作正常,但抛出 Exception 警告 ServiceConnection 已泄漏.我不知道这是否可以解决。

我的主要问题是,如果轮换调用 unbind 后,我会收到 IllegalArgumentException 消息 服务未注册

我正在保留并取消绑定原始 ServiceConnection 但它不起作用。

通过方向更改保持绑定,因为附加到 ActivityFragment 也在使用 Service

有办法解决这个问题吗?或者我也应该在 Fragment 中做一个 ServiceConnection 吗?

谢谢

您遇到异常 ServiceConnection 已泄露 是因为当您尝试将服务与 serviceconnection 绑定时 对象,您已使用 Activity 上下文。因此,当您的设备方向发生变化并且您正在保存 ServiceConnection 时,这将造成泄漏。

为避免泄漏,在绑定解除绑定服务期间Activity,使用Application Context(getApplicationContext()) ,这将解决您的问题并且您不会泄漏 ServiceConnection

绑定:

getApplicationContext().bindService(new Intent(this, TestService.class), serviceConnection, BIND_AUTO_CREATE); 

解绑:

getApplicationContext().unbindService(serviceConnection)