我正在尝试使用 Android 蓝牙 API 从我的 T-Mobile Pulse Mini 手机打印到 HP DeskJet 450wbt 打印机。代码如下所示。连接失败并显示“服务发现失败”。如果我尝试在许多其他线程中提到的创建套接字的替代方法,我会得到“主机已关闭”。
我认为 BPP 的 UUID 是正确的,但我不确定。打印机是配对设备,并且已打开。我找不到我手机的 USB 驱动程序(有徽章的华为 8110),所以我无法在设备上进行调试,也无法查看日志。我被困在这一点上,如果有任何建议,我将不胜感激。
这是我的代码的概要:
final String UUID_BPP = "00001122-0000-1000-8000-00805F9B34FB";
final String printerName = "dj450 S/N SG..."; // name of paired printer
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
return 2; // phone does not support Bluetooth
}
if (!bluetoothAdapter.isEnabled()) {
return 3; // Bluetooth has not been enabled
}
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// Loop through paired devices
BluetoothDevice printer = null;
for (BluetoothDevice device : pairedDevices) {
String s = device.getName();
if (s.equals(printerName)) {
printer = device;
break;
}
}
if (printer == null)
return 4; // Paired printer not found
// create socket
UUID BPP = UUID.fromString(UUID_BPP);
BluetoothSocket socket;
try {
socket = printer.createRfcommSocketToServiceRecord(BPP);
} catch (IOException e) {
return 5; // Unable to create socket
}
/*
try {
Method m = printer.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
socket = (BluetoothSocket) m.invoke(printer, 1);
} catch (Exception e1) {
return 5; // Unable to create socket
}
*/
try {
socket.connect();
} catch (IOException e) {
return 6; // Unable to connect socket
}
最佳答案
我认为原因可能是您使用的 android 上的蓝牙堆栈可能不支持 BPP 配置文件,如果您使用的是标准 android 版本,它不支持 BPP。
套接字创建机制失败,因为打印机未实现 SPP 配置文件。 android 示例依赖于服务器端 SPP 来监听以便能够从客户端连接。打印机肯定不会有通用 SPP 服务器监听。
关于android - Android 上的蓝牙打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5229732/