Android TCP/本地服务

发布于 2024-12-17 10:33:48 字数 470 浏览 0 评论 0原文

我是 Android 开发新手,不确定处理以下问题的最佳方法。

背景: 我有一个在 Android 上运行的 TCP 客户端,与服务器通信。这是启动并运行得很好,但是当进入下一步时我不确定该怎么做。

问题: 我有一个基于用户触摸绘制的用户界面。我需要在手机上运行的 TCP 客户端将坐标和其他一些数据发送到服务器。此外,此过程中还有多个发送数据的活动。

处理这个问题的最佳方法是什么? 以下是我的一些想法。

1)一个具有在另一个线程上工作的可运行客户端的类(我认为这是一个无效的解决方案,因为在多个活动上使用相同的连接并不容易)

2)可以启动主活动的本地服务其余的活动可以与其绑定并向其发送数据。

如果正确答案是 2,我对这样的服务如何运作有点困惑。我的想法是,在服务的 OnCreate() 方法中,它将启动与服务器的 tcp 连接。建立套接字连接后,我有点不确定如何实际与服务保持通信并为其提供通过客户端发送所需的数据。

I am new to Android development and am not sure of the best way to go about handling the following problem.

Background:
I have a TCP client running on android talking to a server. this is up and running just fine however when moving to the next step i am unsure of what to do.

Problem:
I have a UI that draws based on a users touch. I need for the tcp client running on the phone to send the coordinates and some other data to the server. Also there are multiple activities in this process that would be sending data.

What would be the best way to handle this?
Here are some of my thoughts.

1) A class that would have a Runnable client that works on another thread (I think its is an invalid solution because it would not be easy to use the same connection on multiple activities)

2) A local service that can the main activity can start and the rest of the activities can bind to it and send data to it.

If the correct answer is number 2 I am a little confused on how a service like that would work. What I am thinking is that in the OnCreate() method of the service it will launch a tcp connection with the server. Once the socket connection is established I am a bit unsure of how to actually keep in communication with the service and give it the data it needs to send over the client.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

去了角落 2024-12-24 10:33:48

您可以使用 startService() 启动服务。包含在 Intent extra 中,其中包含要发送到服务器的数据。该服务将在 onStartCommand() 中检索这些额外内容,并让后台线程实际发送数据。

完成后请务必停止该服务。

You would start the service with startService(). Include in the Intent extras that contain your data to send to the server. The service would retrieve these extras in onStartCommand() and would have a background thread actually send the data.

Be sure to stop the service when you are done with it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文