因此需要用回呼函數來處理系統找到的藍牙裝置
以下程式是裝置搜尋回呼函數,每找到一項裝置就呼叫addDevice將資料加入裝置與信號強度的列表變數中
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
addDevice(device, rssi);
}
});
}
});
}
};
但在addDevice程序中,裝置資料與rssi資料是分開存放在deviceList與devRssiValues這兩個列表中
因此為了讓顯示裝置列表的時候能夠根據信號強度排序
需要以下做法
1.先讓信號雜湊列表devRssiValues進行排序,雜湊格式是 Address:Value
2.然後雙迴圈先依序取出信號列表的位址值
3.再到裝置列表中找到該筆裝置資料
4.將裝置資料複製一份到列表的尾巴
5.刪除舊位置的裝置資料
等到信號列表中的資料跑過一遍之後,所有裝置列表的資料就會根據信號強度排序了
// dahai: sort the deviceList
devRssiValues = sortByComparator(devRssiValues, true);
// Log.d("UUS-BLE:devRssiValues", devRssiValues.toString());
// List tmpDeviceList = deviceList;
for(Map.Entry entry : devRssiValues.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
for(int i=0; i<deviceList.size(); i++){
if(deviceList.get(i).getAddress().equals(key)){
deviceList.add(deviceList.get(i));
deviceList.remove(i);
}
}
}
Log.d("UUS-BLE:deviceList", deviceList.toString());
沒有留言:
張貼留言