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-我會爲此發佈第二個答案,實際上我是在幾周前自己做的。 –