简体   繁体   中英

How to call function in main activity from service?

I start a service from my main activity using startService(). The service checks for sockets on localhost. When it receives a socket, it reads data from it. I would like to hide the notification bar when it receives socket with specific data. I already coded a function hideNotificationBar() which is located in my main activity. The problem is I don't know how to call this function in main activity from service. Thanks for any help!

Send a Broadcast from Service. Register your Activity to receive this broadcast and act upon it.

This approach solves the problem of storing/acquiring the reference to Activity, which might become inactive during the lifetime of your Service.

The downside is that you can only send simple types, Bundle or classes implementing Parcelable via a broadcast Intent.

I suggest you have a look at MessengerService and MessengerServiceActivities from API Demos application.
Basically, idea is to have Handler class inside both your activity and service that handles communication between the two. Use ServiceConnection in the activity to establish connection with 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