android 藍芽通訊(二)
阿新 • • 發佈:2019-01-24
實現功能:藍芽配對
在上篇的基礎上,配對第一個找到的藍芽裝置
1、重寫Handler中找到藍芽裝置後的邏輯
/** 判斷是否是第一個發現的藍芽裝置*/
private boolean hasFindOneDevice = false;
case ACTION_FOND:
Intent intentFond = (Intent) msg.obj;
if (!hasFindOneDevice) {// //連線該藍芽裝置
BluetoothDevice findFirstdevice = intentFond
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i(TAG,"第一個發現的藍芽:" + findFirstdevice.getName());
if (findFirstdevice.getBondState() == BluetoothDevice.BOND_NONE) {
// 利用反射方法呼叫 BluetoothDevice.createBond(BluetoothDevice remoteDevice);
Method createBondMethod;
try {
createBondMethod = BluetoothDevice.class
.getMethod("createBond" );
createBondMethod.invoke(findFirstdevice);
} catch (Exception e) {
e.printStackTrace();
}
hasFindOneDevice = true;
} else {
BluetoothDevice finddevice = intentFond
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.i(TAG, "find device:" + finddevice.getName());
}
}
獲取配對資訊:首先,在BroadCast中註冊該Action
btDiscoveryFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);// 指明一個遠端裝置的連線狀態的改變
在自定義的receiver中新增裝置狀態改變的情況
else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED
.equals(action)) {// 遠端裝置的連線狀態改變
Log.e(TAG, "接收到 action=BluetoothDevice.ACTION_BOND_STATE_CHANGED");
msg.what = BOND_STATE_CHANGE;
handler.sendMessage(msg);
}
設定狀態改變時要執行的邏輯程式碼
case BOND_STATE_CHANGE:
Intent intent2 = (Intent) msg.obj;
final BluetoothDevice stateChangeDevice = intent2
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e(TAG, "藍芽裝置的狀態" + stateChangeDevice.getBondState());
switch (stateChangeDevice.getBondState()) {
case BluetoothDevice.BOND_BONDING:
Log.e(TAG, "正在配對......");
break;
case BluetoothDevice.BOND_BONDED:
Log.e(TAG, "完成配對");
break;
case BluetoothDevice.BOND_NONE:
Log.e(TAG, "取消配對");
break;
default:
break;
}