需要的權限
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
串口協議UUID
String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
需要監聽的相關廣播
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND);
intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(searchDevices, intent);
獲取藍牙適配器
btAdapt = BluetoothAdapter.getDefaultAdapter();
藍牙未打開時,調用系統打開藍牙提示
if (btAdapt != null && btAdapt.isEnabled() == false) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, RQ_CODE_OPEN_BT);
return;
}
當然,你也可以不使用系統的打開藍牙提示而直接打開藍牙
btAdapt.enable();
關閉藍牙
btAdatp.disable();
調用系統藍牙設置
Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(intent);
獲取綁定設備列表:
Set<BluetoothDevice> pairedDevices = btAdapt.getBondedDevices();
和指定藍牙設備建立socket連接
private void connect(BluetoothDevice btDev) { UUID uuid = UUID.fromString(SPP_UUID); try { btSocket = btDev.createRfcommSocketToServiceRecord(uuid); MyLog.i("開始連接..."); if (btSocket != null) { btSocket.connect(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
讀取數據
private readData(){ InputStream is = null; byte[] buffer = new byte[1024]; InputStream is = null; try { is = BTConfigActivity.btSocket.getInputStream(); // 得到藍牙數據輸入流 num = is.read(buffer); // 讀入數據 is.close(); } catch (IOException e) { } }
一般讀取數據可開一線程循環讀取,建立連接的一方藍牙一次發送的數據,另一方可能分多次接收數據,這里需要注意處理。如果使用循環處理,可以使用InputStream的available()方法判斷可以讀取的字節流的長度從而判斷是否有數據輸入。
發送數據
private void sendData(byte[] cmd){ try { OutputStream os = BTConfigActivity.btSocket.getOutputStream(); // 藍牙連接輸出流 os.write(cmd); } catch (IOException e) { } }