我无法在 Lollipop 之前的设备上获得 iBeacon 的 UUID
,但下面我的代码在 Marshmallow Nexus 5x 中工作。
我不想使用任何像 AltBeacon 或相关的库。
BluetoothManager bm = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter = bm.getAdapter();
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
// scan for devices
scanner.startScan(new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
// get the discovered device as you wish
// this will trigger each time a new device is found
BluetoothDevice device = result.getDevice();
if (device.getType() == BluetoothDevice.DEVICE_TYPE_LE) { //int the device type DEVICE_TYPE_CLASSIC, DEVICE_TYPE_LE DEVICE_TYPE_DUAL. DEVICE_TYPE_UNKNOWN if it's not available
if (device.fetchUuidsWithSdp()) {
System.out.println(device.getName());
List<ParcelUuid> uuids = result.getScanRecord().getServiceUuids();
System.out.println(uuids);
System.out.println(getMajor(result.getScanRecord().getBytes()));
System.out.println(getMinor(result.getScanRecord().getBytes()));
} else {
System.out.println("failed");
}
}
}
});
}
最佳答案
BluetoothManager bm = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter = bm.getAdapter();
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
BluetoothLeScanner scanner = mBluetoothAdapter.getBluetoothLeScanner();
// scan for devices
scanner.startScan(new ScanCallback() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onScanResult(int callbackType, ScanResult result) {
// get the discovered device as you wish
// this will trigger each time a new device is found
BluetoothDevice device = result.getDevice();
if (device.getType() == BluetoothDevice.DEVICE_TYPE_LE)//int the device type DEVICE_TYPE_CLASSIC, DEVICE_TYPE_LE DEVICE_TYPE_DUAL. DEVICE_TYPE_UNKNOWN if it's not available
{
if (device.fetchUuidsWithSdp()) {
System.out.println(device.getName());
List<ParcelUuid> uuids = result.getScanRecord().getServiceUuids();
System.out.println(uuids);
System.out.println(getMajor(result.getScanRecord().getBytes()));
System.out.println(getMinor(result.getScanRecord().getBytes()));
} else {
System.out.println("failed");
}
}
}
});
} else {
// targetting kitkat or bellow
mBluetoothAdapter.startLeScan(new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
// get the discovered device as you wish\
}
});
}
}