将服务绑定到FragmentActivity或Fragment?

时间:2013-03-05 22:57:21

标签: android service android-fragments android-fragmentactivity

将服务绑定到FragmentActivity是否更好:

bindService(Intent, ServiceConnection, int);

Fragment

getActivity().bindService(Intent, ServiceConnection, int);

什么是更好的做法?

1 个答案:

答案 0 :(得分:38)

  

将服务绑定到FragmentActivity ...还是Fragment

更好

它们和你在这里写的一样。 getActivity()不是Fragment - 它是一种返回Activity的方法。您无法在bindService()上致电Fragment

  

什么是更好的做法?

都不是。绑定到Application对象,通过getApplicationContext()获取,ServiceConnectionFragment托管(或者实际上 )保留Fragment

原因是配置更改。绑定是状态。您需要跨配置更改维护该状态。虽然保留的ServiceConnection可以保留在ServiceConnection上,但ContextActivity之间的系统存在隐含关系,并为绑定注册了它。由于可以在配置更改时销毁和重新创建活动,因此Context不是Application的好选择。系统全局的Application是一个更安全的选择,选择Context而非另一个{{1}}的少数几个地方之一是恕我直言的明智之举。

我的Here is a blog post,从碎片之前的时间开始,进入这一点。 Here is a sample project展示了这项技术。