简体   繁体   中英

Using a singleton to talk to an Android Service

My Android app runs a service instance that is not accessible from other apps. I know that the service runs in the same process the app's Activity, because I can read and write to a static variable on the Service class from the activity and the Service sees the changes.

Communicating with the service via static variables/methods (or more properly singletons), is much, much simpler than communicating with it using a Handler or an Intent, which requires making all passed parameters Parcelable. It seems like these two communication methods are really designed for services running in a separate process, and are unnecessary overhead for an in-process service.

It seems like I must be missing something big. What is wrong with using a singleton to talk to a service if you know it is local to your app?

服务和活动之间的通信是使用绑定服务的主要原因之一:您可以构建一个Binder类,该类定义服务和活动之间的接口,并在它们之间传递您想要的任何对象,而不必担心将它们拆分(因为粘合剂要求两者都在同一过程中进行)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM