首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BluetoothLeScanner空对象引用

BluetoothLeScanner空对象引用
EN

Stack Overflow用户
提问于 2016-09-20 20:17:58
回答 2查看 6.2K关注 0票数 5

我的蓝牙应用有问题。当我启用蓝牙之前,启动应用程序,一切正常。但是当我不这样做时,我的应用程序将通过turnOn方法请求允许启用蓝牙。但是,当我按下我的onScan按钮时,我会得到一个错误声明:

代码语言:javascript
复制
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeScanner.startScan(android.bluetooth.le.ScanCallback)' on a null object reference

下面是我的onCreate方法:

代码语言:javascript
复制
 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成为一个空对象。

在这个问题上任何帮助都是很大的。

致以亲切的问候,

宾森托

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-09-22 18:13:48

试试这个(摘自我的一个项目):

类变量:

代码语言:javascript
复制
private BluetoothAdapter mBtAdapter = null;

内部onCreate

代码语言:javascript
复制
final BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBtAdapter = btManager.getAdapter();

checkBt(); // called at the end of onCreate

checkBt()方法:

代码语言:javascript
复制
private void checkBt() {
    if (mBtAdapter == null || !mBtAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
}

然后,当单击“扫描”按钮时:

代码语言:javascript
复制
public void onScanButton(){
    if (mBtAdapter.isEnabled()){
        scanLeDevice(true);
    }
}

然后scanLeDevice调用mBtAdapter.startLeScan(mLeScanCallback);

注意:现在已经不再推荐其中的一些内容,但是可以根据新的API进行更新。我没有花时间去做那件事。

票数 3
EN

Stack Overflow用户

发布于 2018-05-09 04:34:59

我面临着同样的问题,它困扰了我很长一段时间,我今天就修复了它。

设备:华为nonor 8

当我打电话的时候

代码语言:javascript
复制
sLeScanner.stopScan(scanCallback);
sLeScanner.startScan(scanCallback);

我得到了一个NullPointerException,根本原因是- sLeScanner == null。

因此,在启动“停止扫描”之前,只需添加以下代码:

代码语言:javascript
复制
if (sLeScanner == null) sLeScanner = sBluetoothAdapter.getBluetoothLeScanner();

那就修好它。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39603070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档