简体   繁体   English

如何从服务中调用主要活动中的函数?

[英]How to call function in main activity from service?

I start a service from my main activity using startService(). 我使用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. 我已经编写了位于主活动中的函数hideNotificationBar()。 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. 缺点是只能通过广播Intent发送简单类型,Bundle或实现Parcelable的类。

I suggest you have a look at MessengerService and MessengerServiceActivities from API Demos application. 我建议您从API演示应用程序中查看MessengerServiceMessengerServiceActivities
Basically, idea is to have Handler class inside both your activity and service that handles communication between the two. 基本上,想法是在您的活动和服务中都包含Handler类,以Handler两者之间的通信。 Use ServiceConnection in the activity to establish connection with the service. 在活动中使用ServiceConnection建立与服务的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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