将服务绑定到 FragmentActivity 还是 Fragment? [英] Bind service to FragmentActivity or Fragment?
问题描述
服务绑定到FragmentActivity
是否更好:
bindService(Intent, ServiceConnection, int);
或Fragment
:
getActivity().bindService(Intent, ServiceConnection, int);
什么是更好的做法?
推荐答案
将服务绑定到 FragmentActivity... 还是绑定到 Fragment
Is it better to bind service to FragmentActivity... or to Fragment
它们与您在此处写的相同.getActivity()
不是 Fragment
—— 它是一种返回 Activity
的方法.您不能在 Fragment
上调用 bindService()
.
They are the same as you have them written here. getActivity()
is not a Fragment
-- it is a method that returns the Activity
. You cannot call bindService()
on a Fragment
.
什么是更好的做法?
都没有.绑定到通过 getApplicationContext()
获得的 Application
对象,ServiceConnection
由(或者实际上被管理)) 一个保留的Fragment
.
Neither. Bind to the Application
object, obtained via getApplicationContext()
, with the ServiceConnection
managed by (or perhaps actually being) a retained Fragment
.
原因是配置更改.绑定是状态.您需要在配置更改时保持该状态.虽然保留的 Fragment
可以保留 ServiceConnection
,但系统中 ServiceConnection
和 Context
之间存在隐式联系code> 将其注册为绑定.由于 Activity 可以在配置更改时被销毁和重新创建,因此 Activity
在这里不是 Context
的好选择.Application
是系统全局的,是一个更安全的选择,并且选择 Application
而不是另一个 Context
是明智之举的少数地方之一恕我直言.
The reason is configuration changes. A binding is state. You need to maintain that state across configuration changes. While a retained Fragment
can hold onto the ServiceConnection
, there is an implicit tie in the system between the ServiceConnection
and the Context
that registered it for a binding. Since activities can be destroyed and recreated on configuration changes, the Activity
is not a good choice of Context
here. Application
, which is system-global, is a safer choice, and one of the few places where choosing Application
over another Context
is a wise move IMHO.
这是我的一篇博文,来自在碎片之前的时间,这更深入一点.这是一个示例项目,演示了该技术.
Here is a blog post of mine, from a time before fragments, that gets into this a bit more. Here is a sample project demonstrating the technique.
这篇关于将服务绑定到 FragmentActivity 还是 Fragment?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!