简体   繁体   English

如何为Android实现后台套接字侦听器?

[英]How to implement a background socket listener for Android?

I have an android app that listens for json commands over a socket. 我有一个Android应用程序,可通过套接字监听json命令。 I am wondering how I can implement this as a background service. 我想知道如何将其实现为后台服务。 The service would receive the commands and depending on which commands they are, notify the user, or update data within the main program. 该服务将接收命令,并取决于它们是哪个命令,通知用户或更新主程序中的数据。 Some code examples would be great if anyone has them. 如果有人的话,一些代码示例会很棒。 I've got an example of how to build a background service however it uses timers. 我有一个如何构建后台服务的示例,但是它使用计时器。 I'd like for socket to always be listening. 我希望套接字始终在监听。

In this case you would use a Service which responds to events sent over the socket. 在这种情况下,您将使用服务来响应通过套接字发送的事件。

The service should be started by the activity (could also be started on boot if needed). 该服务应由活动启动(如果需要,也可以在启动时启动)。

For code example I would recommend commonwares projects on GitHub . 对于代码示例,我建议在GitHub上使用commonwares项目 There are many great examples using Services there. 那里有使用服务的许多很好的例子。

(There is also a service example in an ongoing app I have here .) (我在这里正在运行的应用程序中也有一个服务示例。)

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

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