简体   繁体   中英

UI update without using Broadcast Receiver or Handler from Service in android

I know service is running on main thread so why are we using Broadcast Receiver or Handler to update UI in android. can we directly update UI without using handler or Broadcast Receiver from service in android. I am confused so please clarify on this discussion.

Answer: Create your activity, register your broadcast receiver et voilà !

Details: In you question, your refer to service and handlers, which can be started in another thread. -> Handlers are used for interprocess communications, when a service running outside of the UI thread, should talk with the UI thread. -> Services are designed for long process cases.

In you question, your refer to broadcast receiver, which can be started from within a service, or from an activity. ->You will always need a broadcast receiver if you want to update the UI with some System (and other custom) events. ->If its just capturing the event and updating a field, this is not a long process. However if it's about capturing and read a database, or accessing a webservice (very asynchrones ops), it's a long process.

to update the UI, you need to have a reference to the view. You can't get references to the views in the service. But you can do it the Activity. That's why you have to enforce the Activity to update UI prior to doing it in the service (since service has no UI itself).

You can pass the reference to the UI into the service, but it will likely lead to memory leaks because of Activity and the Service lifecycles can be different, and you may end up with a deadlock where your Service locks the Activity from being GCed, and Activity locks the service.

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