iBeacon使用蓝牙连接范围精确到1-3米

Lani ·
更新时间:2024-09-21
· 785 次阅读

最近再写一个项目,需要自动签到。用的就是iBeacon,刚开始的时候比较懵比,不知道iBeacon是用来干啥的。因为iBeacon就是一个小盒盒,还是密封好的,就感觉自己懵了。然后上网查资料,才知道iBeacon就是一个小型的基站,手机打开蓝牙之后,如果你在这个基站的范围之内,会自动匹配上。你对iBeacon不需要做任何的操作,因为里面有电池,说是可以使用5年左右。

以上就是大概的情况,接下来介绍的是代码展示部分。

首先,在你的主清单中AndroidManifest.xml中添加权限:

<uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

权限添加完毕之后,接下来就是代码部分了

public class MainActivity extends Activity { private BluetoothAdapter bluetoothAdapter; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.textView1); BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = manager.getAdapter(); if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, 1); } bluetoothAdapter.startLeScan(mLeScanCallback); } public void playVibator(Context context, long timeLong) { Vibrator vib = (Vibrator) context .getSystemService(Service.VIBRATOR_SERVICE); vib.vibrate(timeLong); } private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) { int startByte = 2; boolean patternFound = false; // 寻找ibeacon while (startByte <= 5) { if (((int) scanRecord[startByte + 2] & 0xff) == 0x02 && ((int) scanRecord[startByte + 3] & 0xff) == 0x15) { patternFound = true; break; } startByte++; } // 如果找到了的话 if (patternFound) { String ibeaconName = device.getName(); int txPower = (scanRecord[startByte + 24]); if (ibeaconName.equals("E-Beacon_CE6D94")) { System.out.println(calculateAccuracy(txPower, rssi)); if (calculateAccuracy(txPower, rssi) > 1) {//这里是指iBeacon超过1米之后,textView字体变化 textView.setText("设备有危险!"); playVibator(MainActivity.this, 1000); } else { textView.setText("设备正常!");//在1米范围内 } } } } }; protected static double calculateAccuracy(int txPower, double rssi) { if (rssi == 0) { return -1.0; // if we cannot determine accuracy, return -1. } double ratio = rssi * 1.0 / txPower; if (ratio < 1.0) { return Math.pow(ratio, 10); } else { double accuracy = (0.89976) * Math.pow(ratio, 7.7095) + 0.111; return accuracy; } } }

以上就是全部代码展示,布局文件里面就是一个TextView,这里就不贴布局文件的代码了。

希望对大家的学习有所帮助,也希望大家多多支持软件开发网。

您可能感兴趣的文章:Android检测IBeacon热点的方法android获取ibeacon列表的方法Android提高之BLE开发Android手机搜索iBeacon基站android实现主动连接和被动连接的蓝牙聊天功能Android开发实现实时检测蓝牙连接状态的方法【附源码下载】Android 扫描附近的蓝牙设备并连接蓝牙音响的示例Android 蓝牙连接 ESC/POS 热敏打印机打印实例(ESC/POS指令篇)Android 蓝牙连接 ESC/POS 热敏打印机打印实例(蓝牙连接篇)Android手机通过蓝牙连接佳博打印机的实例代码Android系统中的蓝牙连接程序编写实例教程



ibeacon 蓝牙 连接

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章