Android 中线程或服务中的蓝牙通信?
我正在开发涉及蓝牙通信的应用程序。即使建立连接的活动关闭,蓝牙通信也应该继续。首先,我想到使用服务来实现此目的,这似乎是正确的方法。但是,在蓝牙聊天示例中,通信发生在另一个线程中,而不是在服务中。我已经在我的应用程序中使用了该代码并且它工作正常。使用线程进行蓝牙通信是否正确,还是我只需要使用服务?蓝牙通信应该处于活动状态,直到我的应用程序位于 RAM 中,并且如果我在活动之间切换应该没有关系。
I am developing app which has bluetooth communication involved. The bluetooth communication should go on even if the Activity that sets up the connection closes down. First, I have thought of using Service for this and that seemed to be right way. But, in Bluetooth chat example the communication happens in another thread and not in Service. I have used that code in my app and its working properly. Is using Thread for bluetooth communication proper or do I need to make use of Service only? The bluetooth communication should be active till my app is in RAM and it should not matter if I switch between activities.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,在您的情况下,单独的线程与服务没有什么不同,只是它遵循 Android 的活动生命周期,但线程可能会被终止,并且无法恢复任何状态。一旦服务被终止,Android 将尝试重新启动该服务。
Well a seperated Thread is not differnd then a service in you case, except that it follows the activity life cycle of Android, but a Thread might be killed and no state can be recovered. Android will try to restarted a service once it was killed.
回答你的问题有点晚了,但我想迟总比不好。
我曾经开发过一个在两个设备之间进行蓝牙通信的应用程序,我想总结一下我的经验。
当我们想要执行一些不是很繁重的后台进程时,我们通常使用的服务,在某种程度上,我的意思是该服务(如果它很大)会阻塞我的主 UI 线程,从而减慢您的操作系统或 ANR 可能,这是我们不想要什么。
蓝牙通信是一个不断运行的进程,应该仅使用线程来完成,因为它将作为单独的线程工作,并且不会对主 UI 线程产生任何影响。
如果我错了,请纠正我。
A little too late to answer your query, but better late than never I suppose.
I have worked on an application that has the bluetooth communication between two devices and I would like to summarize my experience.
A service we use normally when we want do some background process that is not very heavy, in a way, I mean the service (if it is huge) will block my main UI thread hence slowing down your OS or ANR may be, which is what we don't want.
The bluetooth communcation is an ever running process which should be done using a Thread only as this will work as a separate thread and wont have any impact on the main UI thread.
Please correct me if I am wrong.