Bin*_* R. 5 android bluetooth bluetooth-lowenergy
我的蓝牙应用程序有问题。当我在启动应用程序之前启用蓝牙时,一切正常。但是当我不这样做时,我的应用程序将通过开启方法请求启用蓝牙的许可。但是当我按下 onScan 按钮时,我收到一条错误消息:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeScanner.startScan(android.bluetooth.le.ScanCallback)' on a null object reference
Run Code Online (Sandbox Code Playgroud)
这是我的 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();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,BTScanner 是在调用 turnOn 方法之前创建的,使 BTScanner 成为空对象。
关于这个问题的任何帮助都会很大。
亲切的问候,
便便
试试这个(取自我的一个项目):
类变量:
private BluetoothAdapter mBtAdapter = null;
Run Code Online (Sandbox Code Playgroud)
里面onCreate:
final BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBtAdapter = btManager.getAdapter();
checkBt(); // called at the end of onCreate
Run Code Online (Sandbox Code Playgroud)
方法checkBt():
private void checkBt() {
if (mBtAdapter == null || !mBtAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当单击“扫描”按钮时:
public void onScanButton(){
if (mBtAdapter.isEnabled()){
scanLeDevice(true);
}
}
Run Code Online (Sandbox Code Playgroud)
然后scanLeDevice调用mBtAdapter.startLeScan(mLeScanCallback);
注意:其中一些现已弃用,但可以更新以符合新的 API。我还没有花时间这样做。