我正在尝试在我的应用中实施蓝牙开发者入门套件。 但是我有以下错误。
java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.le.BluetoothLeScanner android.bluetooth.BluetoothAdapter.getBluetoothLeScanner()' on a null object reference
运行以下功能:
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);
}
致电:
scanner = bluetooth_adapter.getBluetoothLeScanner();
你知道为什么我的蓝牙适配器是空的吗?
答案 0 :(得分:0)
我解决了这个问题: 在BLEFragment中的onCreateView:
ble_scanner = new BLEScanner(this.getContext());
在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");
}