BluetoothAdapter bluetooth = null;
private BluetoothLeScanner scanner;
private ScanCallback scanCallback;
private BluetoothAdapter.LeScanCallback leScanCallback;
if (Build.VERSION.SDK_INT >= 18) {
BluetoothManager bluetoothMan = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
bluetooth = bluetoothMan.getAdapter();
} else {
bluetooth = BluetoothAdapter.getDefaultAdapter();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
scanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
btDevices.add(new BluetoothDeviceModel(result.getDevice().getName(), result.getDevice().getAddress(), result.getRssi()));
timeStamp = System.currentTimeMillis();
}
};
}else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
leScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
btDevices.add(new BluetoothDeviceModel(device.getName(), device.getAddress(), rssi));
timeStamp = System.currentTimeMillis();
}
};
}
if (!allPermissionsGranted(applicationContext, REQUIRED_PERMISSIONS)) {
return false;
}
try {
if (!applicationContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
return false;
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (permissionGranted(applicationContext, Manifest.permission.ACCESS_FINE_LOCATION)) {
scanner = bluetooth.getBluetoothLeScanner();
scanner.startScan(scanCallback);
return true;
}
}
else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
bluetooth.startLeScan(leScanCallback);
return true;
}
} catch (Exception e) {
}
return false;
如果我测试的三星手机与棉花糖这个代码,所以会发生什么,它工作正常,并不会引发任何异常,即使blueooth是关闭的,而返回蓝牙扫描结果在ScanCallback中。 但是,当我测试它与Android N和Lava与Android棒棒糖摩托,它会抛出一个NullPointerException当蓝牙关闭。提供Android的蓝牙扫描的结果,即使蓝牙功能已关闭
问题是,当我试图在这一声明得到BluetoothLeScanner:
scanner = bluetooth.getBluetoothLeScanner();
这里,蓝牙功能已关闭的方法是getBluetoothLeScanner返回null。 有人可以告诉我它是如何发生的吗?
不要担心这种拐角的情况。在开始扫描之前,只要确保蓝牙已启用(以及位置) –
谢谢提姆,但我只是想知道怎么可能?它与供应商定制操作系统有关吗? –