Android 經典藍芽簡單整合

jf1011發表於2017-12-08

藍芽裝置配對

1、設定藍芽許可權

permission.bluetooth
permission.bluetooth_admin
permission.coarse.location
複製程式碼

2、檢查裝置是否支援藍芽裝置

BluetoothAdapter.getDefaultAdapter() == null//該裝置不支援藍芽
複製程式碼

3、檢查裝置是否開啟藍芽

boolean enabled =BluetoothAdapter.getDefaultAdapter().isEnalbed();
複製程式碼

//藍芽未開啟,開啟藍芽

if(!enabled) {
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, REQUST_BLUETOOTH_OPEN);
}
複製程式碼

4、查詢裝置

查詢裝置之前 可以檢查已經配對裝置

Set<BluetoothDevice> devices =  Bluetooth.getDefaultAdapter().getBondedDevices();
複製程式碼

查詢裝置

BluetoothAadpter.getDefaultAdapter().startDiscovery();
複製程式碼

該查詢裝置為非同步操作,立即返回boolean通知是否開啟查詢裝置成功。 查詢結果註冊廣播獲取(BluetoothDevice,BluetoothClass)

BroadcastReceiver br = new BroadcastReceiver {
    public void onReceive (Context context, Intent intent) {
        switch (action) {
            case BluetoothDevice.ACTION_FOUND://發現裝置
                break;
            case BluetoothDevice.ACTION_ACL_CONNECTED://連線成功
                break;
            case BluetoothDevice.ACTION_ACL_DISCONNECTED://斷開連線
                break;
            case BluetoothDevice.ACTION_PAIRING_REQUEST://正在配對
                break;
        }
    }
}
複製程式碼

5、配對裝置

配對裝置,作為服務端進行配對(此處僅考慮客戶端情況)

作為客戶端進行配對

利用拿到到掃描到的BluetoothDevice 以及UUID獲取該裝置的BluetoothSocket 虛擬碼:

BluetoothDevice device = new BluetoothDevice();//實際該裝置由掃描獲取。
BluetoothSocket socket = device.createRfcommSocketToServceRecord(DEVICE_UUID);
socket.connet();//阻塞方法,非同步呼叫
複製程式碼

6、裝置會話

裝置配對後,進行通訊會話,利用socket 中的讀寫流進行會話 socket.getInputStream();//讀取(接受裝置資料)非同步進行 socket.getOutputStream();//傳送(傳送裝置命令),可非同步。

相關文章