开发者

How to call function in main activity from service?

开发者 https://www.devze.com 2023-04-09 02:30 出处:网络
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 w

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 co开发者_StackOverflow社区ded 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号