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。 有人可以告訴我它是如何發生的嗎?
不要擔心這種拐角的情況。在開始掃描之前,只要確保藍牙已啓用(以及位置) –
謝謝提姆,但我只是想知道怎麼可能?它與供應商定製操作系統有關嗎? –