【发布时间】:2017-08-07 21:37:57
【问题描述】:
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;
如果我在三星手机中使用 Marshmallow 测试此代码会发生什么情况,它可以正常工作并且即使在蓝牙关闭时也不会抛出任何异常,而是在 ScanCallback 中返回蓝牙扫描结果。 但是当我用 Moto 和 android N 和 Lava 和 android Lollipop 测试它时,当蓝牙关闭时它会抛出 NullPointerException。
问题是当我试图在此语句中获取 BluetoothLeScanner 时:
scanner = bluetooth.getBluetoothLeScanner();
这里,当蓝牙关闭时,getBluetoothLeScanner 方法返回 null。 谁能告诉我这是怎么回事?
【问题讨论】:
-
不用担心这种极端情况。只需确保在开始扫描之前启用蓝牙(以及位置)
-
谢谢蒂姆,但我只是想知道这怎么可能?是否与厂商定制操作系统有关?
标签: android nullpointerexception bluetooth-lowenergy android-bluetooth