今天在学习有关蓝牙的通信方面的知识,参考了网上的一些蓝牙开发的一些代码自己写了个手机蓝牙通讯的代码
做成了一个聊天的效果,两手机通过蓝牙互发信息来练习蓝牙方面的知识,在实践中遇到了一个很棘手的问题,让我头疼
了很久,后来终于解决了
问题如下:
就是写蓝牙服务端的时候BluetoothServerSocket的accept方法时。老是出现空指针异常,我明明已经在构造方法里面初始化
BluetoothServerSocke 的 serverSocket对象了呀,怎么还会出现为空呢,后来才发现是没有打开蓝牙的缘故,我的确调用了蓝牙适配器
的enable()方法,为什么会出现这样的情况呢,后来查看的api,自习阅读了enable()方法,终于明白了怎么回事,请看下面一段说明:
This is an asynchronous call: it will return immediately, and clients should listen for ACTION_STATE_CHANGED to be notified of subsequent adapter state changes. If this call returns true, then the adapter state will immediately transition from STATE_OFF to STATE_TURNING_ON, and some time later transition to either STATE_OFF or STATE_ON. If this call returns false then there was an immediate problem that will prevent the adapter from being turned on - such as Airplane mode, or the adapter is already turned on.
意思是说这是一个异步的方法,他会立即返回结果,但是蓝牙打开有一个过程,要通过接受广播才能判断是否是真正的打开了蓝牙,所以要注册一个action为ACTION_STATE_CHANGED的广播,接收到广播之后再去开启服务端的线程,这时在去调用accept方法就不会出现空指针异常了