<分区>
我一直在努力通过 android 建立蓝牙连接。
我尝试构建它几个星期,但只有一半的代码可以正常工作。
工作的部分是:
打开/关闭蓝牙;
查找配对设备;
扫描可用设备。
谁能给我发一份源代码,其中包含通过 Bluetoothsocket
连接的部分?
这对我很有帮助
<分区>
我一直在努力通过 android 建立蓝牙连接。
我尝试构建它几个星期,但只有一半的代码可以正常工作。
工作的部分是:
打开/关闭蓝牙;
查找配对设备;
扫描可用设备。
谁能给我发一份源代码,其中包含通过 Bluetoothsocket
连接的部分?
这对我很有帮助
最佳答案
通过蓝牙套接字连接的异步类
UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
BluetoothSocket socket = null;
class UserInterface extends Thread {
BluetoothDevice bdDevice;
public UserInterface() {
bdDevice = your pair device;
}
@Override
public void run() {
Looper.prepare();
try {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
if (socket != null && socket.isConnected()) {
is1.close();
os1.close();
socket.close();
}
try {
socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (Exception e) {
Log.e("", "Error creating socket");
}
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
try {
socket.connect();
Log.e("", "Connected Rfcomm");
} catch (IOException e) {
Log.e("", e.getMessage());
try {
Log.e("", "trying fallback...");
socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
socket.connect();
Log.e("", "Connected serial UDID");
} catch (Exception e2) {
Log.e("", "Couldn't establish Bluetooth connection!");
}
}
if (socket.isConnected()) {
dismissProgressDialog();
//code after socket connect
} else {
dismissProgressDialog();
showProgressDialogToast("Please restart polaroid bluetooth");
closeSocket();
Log.i("TAG", "Socket Disconnected");
}
Log.i("Log", "Removed" + bdDevice.getName());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("Log", "Under Catch of thread");
e.printStackTrace();
dismissProgressDialog();
}
}
}
像这样使用线程类
UserInterface userInterface = new UserInterface();
userInterface.start();
关于java - 安卓蓝牙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34011610/