最近公司在搞人人摇的芯片,但是目前为止公司没有人事接触过这一点的,刚好那会我比较闲,所以就接手来研究研究Ibeacon 。
因为一开是没有接触过这个东西,所以看不懂啊。只好各种百度关于蓝夜低功耗蓝牙消耗设备的资料
好了废话不多说,直接上:
(1)打开蓝牙
这步不多说什么了。
获取BluetoothManager、BluetoothAdapter
/**
* Initializes a reference to the local Bluetooth adapter.
*
* @return Return true if the initialization is successful.
*/
public boolean initialize()
{
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))
{
Log.e(TAG, "Unable to initialize Bluetooth.");
return false;
}
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
if (mBluetoothManager == null)
{
mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null)
{
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null)
{
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
然后打开蓝牙
public boolean OpenBlue()
{
//开启蓝牙
if (!mBluetoothAdapter.isEnabled())
return mBluetoothAdapter.enable();
else
return true;
}
(2)扫描
private void scanLeDevice(final boolean enable)
{
if (enable)//enable =true就是说要开始扫描
{
// Stops scanning after a pre-defined scan period.
// 下边的代码是为了在 SCAN_PERIOD 后,停止扫描的
// 如果需要不停的扫描,可以注释掉
mHandler.postDelayed(new Runnable()
{
@Override
public void run()
{
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
// 这个是重置menu,将 menu中的停止按钮->扫描按钮
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;//此变量指示扫描是否进行
mBluetoothAdapter.startLeScan(mLeScanCallback);//这句就是开始扫描了
}
else
{
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);//这句就是停止扫描
}
// 这个是重置menu,将 menu中的扫描按钮->停止按钮
invalidateOptionsMenu();
}
这里有个变量 mLeScanCallback,这个是什么呢?
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback()
{
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord)
{
iBeacon iBeacon = fromScanData(device, rssi, scanRecord);20 }
};
通过探索呢,这个东西就是一个回调函数,当蓝牙接收到某广播时,就会调用 mLeScanCallback.onLeScan()函数。device当然就是广播的设备了,rssi是信号强度,scanRecord是广播的信息。
然后通过解析scanRecord就可以知道设备的详情了。
获取到IBeacon以后,你就可以把他放到列表里,该怎么显示就是你的问题了。