绑定服务FragmentActivity或片段? [英] Bind service to FragmentActivity or Fragment?
问题描述
是更好地绑定服务 FragmentActivity
:
bindService(意向,ServiceConnection,INT);
或片段
:
getActivity()bindService(意向,ServiceConnection,INT)。
什么是更好的做法?
是更好地绑定服务FragmentActivity ......或片段
他们是一样的,你让他们写在这里。 getActivity()
不是片段
- 这是返回活动<方法/ code>。你可以不叫
bindService()
在片段
。
什么是更好的做法?
都不是。绑定到应用程序
对象,通过获得getApplicationContext()
,与 ServiceConnection
由管理(或者实际上的是的)保留的片段
。
原因是配置更改。绑定是状态。你需要保持整个配置更改的状态。虽然保留了片段
能守住 ServiceConnection
,有<$ C $之间的隐含领带系统C> ServiceConnection 和上下文
已注册它的约束力。由于活动可以被摧毁,重建对配置的修改,活动
不是上下文
这里的一个不错的选择。 应用程序
,这是系统全局,是一个更安全的选择,而一些地方在哪里选择一个应用程序
对另一上下文
是一个明智之举恕我直言。
<一个href="http://commonsware.com/blog/2010/09/29/another-use-getapplicationcontext-binding-rotation.html">Here是一个博客帖子矿井,从时间段之前,也进入这个有点多。 这里是展示该技术的示例项目。
Is it better to bind service to FragmentActivity
:
bindService(Intent, ServiceConnection, int);
or to Fragment
:
getActivity().bindService(Intent, ServiceConnection, int);
What is better practice?
Is it better to bind service to FragmentActivity... or to Fragment
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
.
What is better practice?
Neither. Bind to the Application
object, obtained via getApplicationContext()
, with the ServiceConnection
managed by (or perhaps actually being) a retained Fragment
.
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或片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!