BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();
if(bta != null) {
Set<BluetoothDevice> devices = bta.getBondedDevices();
for (final BluetoothDevice device : devices) {
BluetoothClass btClass = device.getBluetoothClass();
if (btClass.getMajorDeviceClass() == 0x1f00) {
//Only look at devices which are considered uncategorized, so we don't screw up any bt headset, leyboard, mouse, etc
new DeviceThread(device).start();
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_NONE);
if (state == BluetoothDevice.BOND_BONDED) {
new DeviceThread(device).start();
} else if (state == BluetoothDevice.BOND_NONE) {
DeviceThread thread = threadMap.get(device.getAddress());
if (thread != null) {
thread.interrupt();
}
}
}
}, filter);
}
private class DeviceThread extends Thread {
private BluetoothDevice device;
public DeviceThread(BluetoothDevice device) {
this.device = device;
threadMap.put(device.getAddress(), this);
}
@Override
public void run() {
try {
BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
socket.connect();
InputStream inputStream = socket.getInputStream();
while (!Thread.interrupted() && socket.isConnected()) {
inputStream.skip(5);
String data = "";
do {
int code = inputStream.read();
char character = (char) code;
data = data + character;
} while (inputStream.available() > 0);
data = data.substring(0, data.length() - 2);
if (scannerEventListener != null) {
scannerEventListener.onScan(data);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
Log.d("GABE", "Exiting thread");
}
}
此代码将注册配对蓝牙设备,然后检查并查看它们是否是未知设备类型(扫描仪没有设备类)。如果是这样,它将启动一个线程来监听该设备。当它没有绑定时,它会中断该线程。在线程上,它打开与设备的SPP连接并等待输入。当它得到它时,它解析输入并将结果发送给一个监听器。
为此,扫描仪需要处于SPP模式。有些扫描仪支持它,有些则不支持,并且如何将其设置为该模式(我桌上的扫描仪有一个控制条码,我需要扫描以设置模式)。通常我会编写它来接受任何类型的输入 - 硬件键盘模式或SPP。
用户不想按回车,扫描仪本身不会按任何其他按钮期望条码数字...关于SPP我不知道,这里是没有关于这个文件(或我找不到)因此,我需要以某种方式进行测试 – Nininea
扫描仪本身发送回车键作为条形码的最后一个字符。所以你可以捕捉到。这是onKeyUp实际工作的极少数情况之一。至于SPP-我会为此发布第二个答案,实际上我是在几周前自己做的。 –