所以我正在开发一个直接通过蓝牙连接的应用程序,以接受来自 RFCOMM 通道的字符串命令并发送响应。
所以这些是我目前正在使用的 2 个课程
蓝牙_管理器
import android.bluetooth.*;
import android.content.Intent;
public class Reader_BluetoothManager {
protected Reader_MainScreen main;
protected BluetoothAdapter bAdapter;
private Reader_AcceptThread bAccept;
public Reader_BluetoothManager(Reader_MainScreen main) {
this.main = main;
initiate();
}
public void initiate(){
checkForBluetooth();
enableBluetooth();
}
public void log(String l){
main.log(l);
}
public void checkForBluetooth(){
bAdapter = BluetoothAdapter.getDefaultAdapter();
if (bAdapter == null) {
main.log("No Bluetooth supported!");
return;
}
main.log("Bluetooth supported...");
}
public void enableBluetooth(){
if (!bAdapter.isEnabled()) {
main.log("Bluetooth not enabled... requesting activation");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
main.startActivityForResult(enableBtIntent, main.BLUETOOTH_ENABLE_CODE);
}
}
public void enableConnection(){
main.log("Connecting...");
if (bAccept != null)
bAccept.interrupt();
bAccept = new Reader_AcceptThread(this);
bAccept.start();
}
public void stopConnection(){
if (bAccept != null)
bAccept.interrupt();
}
}
并接受线程
import java.io.IOException;
import java.util.UUID;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
public class Reader_AcceptThread extends Thread{
private BluetoothServerSocket serverSocket;
private BluetoothSocket socket;
private BluetoothDevice device;
private Reader_BluetoothManager main;
public Reader_AcceptThread(Reader_BluetoothManager main) {
this.main = main;
}
public void run(){
try {
serverSocket = main.bAdapter.listenUsingRfcommWithServiceRecord("XXXXXX", UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
main.log("checkPoint 1");
socket = serverSocket.accept();
main.log("checkPoint 2");
device = socket.getRemoteDevice();
main.log("checkPoint 3");
main.log("connection established...");
main.log(socket.toString());
} catch (IOException e) {
main.log("error...");
main.log(e.toString());
main.main.stopConnection();
interrupt();
}
while (!isInterrupted()){
try {
sleep(2000);
} catch (InterruptedException e) {
interrupt();
break;
}
main.log("ping");
}
}
}
我根据 Google Docs Guide 构建了这些。同样在我的笔记本电脑上,我正在执行以下操作:
这就是我的手机上发生的事情:
这是我尝试从我的 Windows PC 连接时发生的情况:
正如您在手机屏幕截图中看到的那样,我被困在了socket = serverSocket.accept()
。