所以我正在开发一个应用程序,通过蓝牙直接连接,接受来自RFCOMM频道的字符串命令并发送回复。
所以这些是我目前正在使用的2个课程
Bluetooth_Manager
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();
}
}
AcceptThread
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文档指南构建了这些内容。 另外在我的笔记本电脑上,我正在做以下事情:
这就是我手机上发生的事情:
以下是我尝试从Windows PC连接时发生的情况:
正如您在手机屏幕截图中看到的那样,我被困在socket = serverSocket.accept()
。
答案 0 :(得分:2)
您使用的UUID是服务的UUID - 如果您想使用默认的RFCOMM频道,您应该使用SPP UUID "00001101-0000-1000-8000-00805F9B34FB"
而不是UUID.randomUUID();
serverSocket = main.bAdapter.listenUsingRfcommWithServiceRecord("Connection Test", UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));