绑定服务FragmentActivity或片段? [英] Bind service to FragmentActivity or Fragment?

查看:163
本文介绍了绑定服务FragmentActivity或片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是更好地绑定服务 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆