我是android开发的初学者,我正在尝试实现一个android udp客户端,它连接到java服务器并从中发送/接收一些数据包。在这个过程中它收集一些数据(如往返延迟等) ,用于衡量特定网络的 QoS。我尝试使用 Java 线程实现连接和发送/接收数据,但是如果我尝试使用超过 2 个线程,应用程序会崩溃并挂起。所以我正在寻找替代品。在浏览此站点以及其他一些链接时,我发现在 android 中可以使用 AsyncTask、Handler 等实现多个线程。此外,我发现 Service 类还有助于在应用程序中运行后台服务。请建议其中哪种方法最能实现我的目的。提前致谢。
2 回答
There is not one right answer that can be applied as a broad stroke to how to do Android multi-threading. There are a few different ways to approach it based on what your specific needs are.
Any long running, blocking call, in Android will result in the application crashing.
The most common solution is to use an AsyncTask though. For example, when I want to make a call out to a web API endpoint for some XML data within an Activity I would in this case use an AsyncTask and kick off the calls from within doInBackground.
This is not an appropriate solution though if the wait time is longer, or possibly an unknown wait time. Or in a situation where there will always be waiting such as a message queuing service. In this type of situation it may be best to write a separate app based on extending the Service class. Then you can send/receive notifications to/from the service from your primary application in a similar manner to how you would communicate with a web service.
您可以使用 AasyncTask 来执行此操作,并且正如您所提到的,服务也可能很有用,您可以让您的应用程序在后台执行任何操作,如果用户需要通过其界面使用应用程序,则必须使用 AsyncTask 以避免崩溃