通过方向更改在 Android 中维护 ServiceConnection
我有一个 Activity,它保存到服务的 ServiceConnection。当方向改变时,ServiceConnection 似乎丢失并重新创建。
这是不可取的。我希望通过重新创建活动来维护 ServiceConnection。我正在寻找解决这个问题的好模式。
I have an Activity that holds a ServiceConnection to a Service. When the orientation changes the ServiceConnection appears to get lost and gets re created.
This is not desirable. I'd like to have it such that the ServiceConnection is maintained through the recreation of the Activity. I'm looking for a good pattern that solves this problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看一下 Activity.onRetainNonConfigurationInstance() 和关联的 getLastNonConfigurationInstance() 方法 - 它们可能有用。
Take a look at Activity.onRetainNonConfigurationInstance() and the associated getLastNonConfigurationInstance() methods - they may be of use.
不幸的是,使用 onRetainNonConfigurationInstance/getLastNonConfigurationInstance 可能会涉及泄漏。
就我而言(我使用 IntentService 在远程服务器上上传文件),我在所考虑的 Activity 中声明了我的连接,例如:
mServiceMessenger 是 Messenger 的一个实例,它允许我向上传任务发送取消订单。
尽管如此,当我使用 onRetainNonConfigurationInstance 和 getLastNonConfigurationInstance 测试该解决方案时,我跟踪(感谢 Eclipse 中的 MAT 插件)屏幕旋转涉及到我的 Activity 上下文的大量泄漏。
为了解决这个问题(并且因为我的应用程序复杂性允许我这样做),我创建了一个单例,将处理与 IntentService 的连接(以及与我的 Activity 的通信)所需的所有元素分组在一起。因此,当旋转屏幕时,创建的新 Activity 会取回单例管理的连接,并且可以使用它而不会丢失信息。
Unfortunately, using onRetainNonConfigurationInstance/getLastNonConfigurationInstance can involve leaks.
In my case (I use an IntentService to upload a file on a remote server), I was declaring my connection in the considered Activity such as :
The mServiceMessenger is an instance of Messenger that allows me to send a cancel order to the upload task.
Nevertheless, when I tested the solution using onRetainNonConfigurationInstance and getLastNonConfigurationInstance, I tracked (thanks to MAT plug-in in Eclipse) that a screen rotation involves a lot of leaks of my Activity context.
To solve this problem (and because my Application complexity allows me to do so), I created a singleton grouping together all the elements I need to handle the connection to my IntentService (and communication with my Activity). So, when rotating the screen, the new Activity created gets back the connection managed by the singleton and can use it without losing information.
在清单中的活动属性中使用 android:configChanges="orientation"。
Use android:configChanges="orientation" in activity property in manifest.