提供Android的蓝牙扫描的结果,即使蓝牙功能已关闭

问题描述:

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。 有人可以告诉我它是如何发生的吗?

+0

不要担心这种拐角的情况。在开始扫描之前,只要确保蓝牙已启用(以及位置) –

+0

谢谢提姆,但我只是想知道怎么可能?它与供应商定制操作系统有关吗? –

Android上的蓝牙API将返回已知的BT设备,因此如果您之前与设备配对过,它也会显示在结果中。

我相信,就像蒂姆说的那样,你正面临一个角落的情况,你应该真的检查蓝牙是否打开以避免将来出现问题。

+0

谢谢Mauker,我会再次检查它。 –

+0

不客气!不要忘记标记为接受,如果它的作品:) – Mauker

+0

它工作@AmanKush? – Mauker