Binding a Service to an android.app.Activity vs Binding it to an android.app.Application

与世无争的帅哥 提交于 2019-11-30 13:15:17

问题


Is there any fundamental difference in binding a service to an android.app.Activity vs binding it to an android.app.Application. I want to bind the service to an Application because I want to keep some global state/data in the Application instead of duplicating it in all my activities.

Thanks.


回答1:


No. There is no fundamental difference.

That said, subclassing android.app.Application is a very good place to store global/state data. There is only one instance and everything that derives from Context has access to it.

I'm also sure that binding a service to an application will result in some odd lifetimes if you aren't careful. What I mean is that even though your app is out of sight and has no activities alive, your application could still exist because your service still exists. Your service still exists because your application still exists. You would have to manually shut down the service based on some event other than onDestroy.




回答2:


answer of @Jere.Jones is not 100% correct. You have one Instance of Application class per Process. So if you run your service in a seperate Process e.g. with

 <service
        android:name=".engine.NetworkService"
        android:exported="false"
        android:process=":xxxService" />

you have two seperate Instances of Appliaction, which means if you need to "hold a state" you must ensure its either not Process crossing, or you have to use IPC to sync these sates.



来源:https://stackoverflow.com/questions/3154899/binding-a-service-to-an-android-app-activity-vs-binding-it-to-an-android-app-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!