问题描述
我还是新Android开发,但我目前工作的需要蓝牙接口是在与蓝牙设备不断的交流项目。我一直在阅读了关于服务
, IntentService
&安培; AsynTask
,但我仍然感到困惑。我想我不应该使用的AsyncTask
,因为它是为处理一个很短的任务吗?如果我使用 IntentService
,我怎么产生多个线程来检查,如果蓝牙设备连接,发送和接收?
I'm still new to Android development but I am currently working on a project that requires the Bluetooth interface to be in constant communication with a Bluetooth-device. I've been reading up on Service
, IntentService
& AsynTask
but I am still confused. I think I should not be using AsyncTask
as it is meant for processing a very short task? If I use IntentService
, how do I spawn multiple threads to check if the Bluetooth device is connected, sending and receiving?
我使用的是作为我的参考。在它 connectThread
是一个线程,当连接到蓝牙设备,随后将启动 connectedThread
。
I'm using the BluetoothViewer as my reference. In it connectThread
is a thread which, when connected to the Bluetooth device, would then start the connectedThread
.
感谢
肯
推荐答案
我使用ACTION_REQUEST_ENABLE意图startActivityForResult()。这就导致调用:
I use an ACTION_REQUEST_ENABLE intent to startActivityForResult(). This then results in a call to:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == imu.requestCode) {
if (resultCode == RESULT_OK) {
getPairedDevice(); // my function
initializeConnection(); // my function
}
}
}
initializeConnection()创建一个新的线程,它初始化我输入插口,支持蓝牙输入处理创建另一个线程,并创建我的输出线。从这些功能片段包括:
initializeConnection() creates a new thread that initializes my input socket, creates yet another thread for Bluetooth input processing, and creates my output thread. Snippets from those functions include:
myServerSocket = dev.createInsecureRfcommSocketToServiceRecord(uuid);
myBluetooth.cancelDiscovery();
myServerSocket.connect();
myBluetoothInputThread = new BluetoothInputThread(myServerSocket, handler); myBluetoothInputThread.setPriority(Thread.MAX_PRIORITY);
myBluetoothInputThread.start();
myBluetoothSocketOutputStream = myServerSocket.getOutputStream();
BluetoothInputThread扩展Thread创建一个单独的进程监视的输入流。这个类通过Handler.sendMessage与其父类通信
BluetoothInputThread extends Thread to create a separate process for monitoring the input stream. This class communicates with its parent class via the Handler.sendMessage
这篇关于背景蓝牙应用 - 穿线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!