算法:
/** * 功能:根据rssi计算距离 * Created by liuhuichao on 2017/1/17. */ public class RssiUtil { //A和n的值,需要根据实际环境进行检测得出 private static final double A_Value=50;/**A - 发射端和接收端相隔1米时的信号强度*/ private static final double n_Value=2.5;/** n - 环境衰减因子*/ /** * 根据Rssi获得返回的距离,返回数据单位为m * @param rssi * @return */ public static double getDistance(int rssi){ int iRssi = Math.abs(rssi); double power = (iRssi-A_Value)/(10*n_Value); return Math.pow(10,power); } }
扫描蓝牙过程中获得信号强度:
/*监听扫描过程中的变化*/ private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent // 通过EXTRA_DEVICE附加域来得到一个BluetoothDevice设备 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // If it's already paired, skip it, because it's been listed already // 如果这个设备是不曾配对过的,添加到list列表 /* if (device.getBondState() != BluetoothDevice.BOND_BONDED) {*/ //信号强度 int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
Map map=new HashMap(); map.put("deviceName",deviceName); map.put("deviceAddress",deviceAddress); map.put("bluetooth_status",distance); deviceList.add(map); Collections.sort(deviceList,new Comparator() { public int compare(Object a, Object b) { Map one=(HashMap)a; Map two=(HashMap)b; if((((double)one.get("bluetooth_status"))-((double)two.get("bluetooth_status")))>0){ return 1; }else if((((double)one.get("bluetooth_status"))-((double)two.get("bluetooth_status")))==0){ return 0; }else{ return -1; } } }); listItemAdapter.notifyDataSetChanged();