Android 用于连接多个蓝牙设备的服务与 Intent 服务

Android Service versus Intent Service for connecting to multiple Bluetooth devices

我的应用程序连接到多个 SPP 蓝牙设备,所有这些设备都流式传输数据。有四台设备流式传输,一台为 250 Hz,其余为 100 Hz。我想将它们放在 Service 中,但也希望每个设备 运行 放在单独的 Thread 中。每个 Thread 还必须连接到 SQLite 数据库以实时插入数据。这些设备可以长时间连接,并且可以随时断开连接并随时重新连接。一旦启动,该应用程序可能会 运行 持续 24 小时或更长时间,并始终寻找已配对设备的可用性。

问题是:在单独的 Service 运行 多个 Thread 中执行此操作是否性能更好(每个连接设备一个 Thread ) 还是 运行 一个单独的 IntentService 更好(这当然会 运行 在它自己的 worker Thread 中?

我已经在 SO 和其他地方阅读了许多其他问题和答案,并且可以看到每种方法的优点和缺点,但我找不到专门回答我的问题的答案。我不确定 运行 在 Service 中设置多个 Thread 是否有时仍会阻塞主 Thread。另一方面,我不认为我可以在 IntentService 中同时 运行 多个 Thread

在您预期的场景中,IntentService 不是一个坏主意,但不是您提议的方式。基于 documentation:

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

This "work queue processor" pattern is commonly used to offload tasks from an application's main thread. The IntentService class exists to simplify this pattern and take care of the mechanics. To use it, extend IntentService and implement onHandleIntent(Intent). IntentService will receive the Intents, launch a worker thread, and stop the service as appropriate.

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time.

因此,为每个蓝牙设备启动 IntentService 将意味着一个或另一个将被阻止。每当我与多个套接字(设备)通信时,我都会为每个套接字分配一个线程......然后该线程负责根据需要连接到套接字,与之通信并重新连接到套接字。这种模式与任何服务器程序中使用的相同:每个连接都有一个 ClientThread,它由连接侦听器生成。

但是,IntentService 也有一个好地方:将数据传送到您的 sqlite 数据库非常棒。将数据放在意图中,将其发送到您的 IntentService,它会在需要时打开数据库(甚至可能启动事务),然后 post 所有数据,当它用完时工作,提交事务并关闭数据库。 API.

提供了许多必要的管道