绑定服务FragmentActivity或片段?绑定、片段、FragmentActivity

2023-09-13 23:40:39 作者:羁旅客

是更好地绑定服务 FragmentActivity

  bindService(意向,ServiceConnection,INT);
 

片段

  getActivity()bindService(意向,ServiceConnection,INT)。
 

什么是更好的做法?

解决方案   

是更好地绑定服务FragmentActivity ......或片段

他们是一样的,你让他们写在这里。 getActivity()不是片段 - 这是返回活动。你可以不叫 bindService()片段

  

什么是更好的做法?

都不是。绑定到应用程序对象,通过获得getApplicationContext(),与 ServiceConnection 由管理(或者实际上的是的)保留的片段

原因是配置更改。绑定是状态。你需要保持整个配置更改的状态。虽然保留了片段能守住 ServiceConnection ,有 ServiceConnection 上下文已注册它的约束力。由于活动可以被摧毁,重建对配置的修改,活动不是上下文这里的一个不错的选择。 应用程序,这是系统全局,是一个更安全的选择,而一些地方在哪里选择一个应用程序对另一上下文是一个明智之举恕我直言。

Here是一个博客帖子矿井,从时间段之前,也进入这个有点多。 这里是展示该技术的示例项目。

Android Fragment 基本了解 图文介绍

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.