0

Ich versuche, Bluetooth-Entwickler-Starter-Kit in meiner App zu implementieren. Aber ich habe den folgenden Fehler.BLE BluetoothAdapter.getBluetoothLeScanner() Fehler

java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.le.BluetoothLeScanner android.bluetooth.BluetoothAdapter.getBluetoothLeScanner()' on a null object reference 

Rrunning diese folgende Funktion:

public void startScanning(final ScanResultsConsumer scan_results_consumer, long stop_after_ms) { 
    if (scanning) { 
     Log.d(Constants.TAG, "Already scanning so ignoring startScanning request"); 
     return; 
    } 
    Log.d(Constants.TAG, "Scanning..."); 
    if (scanner == null) { 
     scanner = bluetooth_adapter.getBluetoothLeScanner(); 
     Log.d(Constants.TAG, "Created BluetoothScanner object"); 
    } 
    handler.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      if (scanning) { 
       Log.d(Constants.TAG, "Stopping scanning"); 
       scanner.stopScan(scan_callback); 
       setScanning(false); 
      } 
     } 
    }, stop_after_ms); 

    this.scan_results_consumer = scan_results_consumer; 
    List<ScanFilter> filters; 
    filters = new ArrayList<ScanFilter>(); 
    /*ScanFilter filter = new ScanFilter.Builder().setDeviceName("SP5").build(); 
    filters.add(filter);*/ 
    ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(); 
    setScanning(true); 
    scanner.startScan(filters, settings, scan_callback); 
} 

Beim Ruf:

scanner = bluetooth_adapter.getBluetoothLeScanner(); 

Haben Sie eine Ahnung, warum mein Bluetooth-Adapter null ist?

+0

bluetooth_adapter nicht null ist? –

Antwort

0

löste ich das Problem: In onCreateView in BLEFragment:

 ble_scanner = new BLEScanner(this.getContext()); 

In BLEScanner:

public BLEScanner(Context context) { 
    this.context = context; 

    final BluetoothManager bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); 
    bluetooth_adapter = bluetoothManager.getAdapter(); 

    // check bluetooth is available and on 
    if (bluetooth_adapter == null || !bluetooth_adapter.isEnabled()) { 
     Log.d(Constants.TAG, "Bluetooth is NOT switched on"); 
     Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     enableBtIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     context.startActivity(enableBtIntent); 
    } 
    Log.d(Constants.TAG, "Bluetooth is switched on"); 
}