我的蓝牙应用有问题。当我启用蓝牙之前,启动应用程序,一切正常。但是当我不这样做时,我的应用程序将通过turnOn方法请求允许启用蓝牙。但是,当我按下我的onScan按钮时,我会得到一个错误声明:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeScanner.startScan(android.bluetooth.le.ScanCallback)' on a null object reference下面是我的onCreate方法:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set layout
setContentView(R.layout.activity_main);
//Bluetooth
// BluetoothManager
final BluetoothManager BTManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BTAdapter = BTManager.getAdapter();
// BluetoothLescanner
BTScanner = BTAdapter.getBluetoothLeScanner();
//Turn on BT
turnOn();
//Ask permission for location.
requestPermission();
}我的问题是,BTScanner是在调用turnOn方法之前创建的,使BTScanner成为一个空对象。
在这个问题上任何帮助都是很大的。
致以亲切的问候,
宾森托
发布于 2016-09-22 18:13:48
试试这个(摘自我的一个项目):
类变量:
private BluetoothAdapter mBtAdapter = null;内部onCreate
final BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBtAdapter = btManager.getAdapter();
checkBt(); // called at the end of onCreatecheckBt()方法:
private void checkBt() {
if (mBtAdapter == null || !mBtAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}然后,当单击“扫描”按钮时:
public void onScanButton(){
if (mBtAdapter.isEnabled()){
scanLeDevice(true);
}
}然后scanLeDevice调用mBtAdapter.startLeScan(mLeScanCallback);
注意:现在已经不再推荐其中的一些内容,但是可以根据新的API进行更新。我没有花时间去做那件事。
发布于 2018-05-09 04:34:59
我面临着同样的问题,它困扰了我很长一段时间,我今天就修复了它。
设备:华为nonor 8
当我打电话的时候
sLeScanner.stopScan(scanCallback);
sLeScanner.startScan(scanCallback);我得到了一个NullPointerException,根本原因是- sLeScanner == null。
因此,在启动“停止扫描”之前,只需添加以下代码:
if (sLeScanner == null) sLeScanner = sBluetoothAdapter.getBluetoothLeScanner();那就修好它。
https://stackoverflow.com/questions/39603070
复制相似问题