2013年3月19日 星期二

藍牙相關 - Android 新手學習筆記

之前從來沒碰過藍牙的程式,一點基本概念也沒有
結果有一些問題應該是跟基本觀念有關的

取得 BluetoothAdapter
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Alert user that Bluetooth is not available
Toast.makeText(this.getApplicationContext()
, "Sorry, your device does not support Bluetooth."
, Toast.LENGTH_LONG).show();
}

檢查藍牙是否有啟動

if(!bluetoothAdapter.isEnabled()){
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
//這會彈出一個確認框讓使用者啟動藍牙
}

取得所有已配對的裝置

Set<BluetoothDevice> srcDevices = bluetoothAdapter.getBondedDevices();

如果知道MAC Address,也可以這麼取得Device

BluetoothDevice device = bluetoothAdapter.getRemoteDevice(macAddr);

與裝置連線
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();

這個UUID讓我疑惑了,我要怎麼知道藍牙裝置的UUID?
雖然從 API level 15 (Android 4.0.3) 以後,有 device.getUuids()
但我的還只是 Android 2.3,怎麼取得啊?
後來才找到這一篇
How to find the UUID of serial port Bluetooth device?
才知道原來特定種類的藍牙裝置的UUID其實是固定的
參考 javax.bluetooth.UUID

不過,某些 Android 裝置用這樣的方式似乎是連不到
像我的會出現
Unable to start Service Discovery
後來查到一篇,提供了另一個方法,就能成功連線了
註:我的是HTC Wildfire S,網路上似乎還有另一些 HTC 的手機也會如此

Method m = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
BluetoothSocket socket = (BluetoothSocket)m.invoke(device, Integer.valueOf(1));
socket.connect();

接收資料的部份待補...



沒有留言:

張貼留言

廣告訊息會被我刪除

Related Posts with Thumbnails