Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

android - Bind service to FragmentActivity or 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...