为什么来自BluetoothSocket的输入/输出流被评估为NOT null,然后抛出空指针异常?

时间:2017-03-03 04:00:52

标签: java android sockets bluetooth nullpointerexception

我有一个从蓝牙套接字创建的输入流和输出流,我在检查套接字是否为空后尝试写入内容(这都在OnCreate函数中):

{% load socialaccount %}

{% get_providers as socialaccount_providers %}

{% for provider in socialaccount_providers %}
{% if provider.id == "openid" %}
{% for brand in provider.get_brands %}
<li>
  <a title="{{brand.name}}" 
     class="socialaccount_provider {{provider.id}} {{brand.id}}" 
     href="{% provider_login_url provider.id openid=brand.openid_url process=process action="reauthenticate" %}"
     >{{brand.name}}</a>
</li>
{% endfor %}
{% endif %}
<li>
  <a title="{{provider.name}}" class="socialaccount_provider {{provider.id}}" 
     href="{% provider_login_url provider.id process=process scope=scope auth_params=auth_params %}">{{provider.name}}</a>
</li>
{% endfor %}

无论蓝牙设备是连接还是在范围内,输出流都将被评估为非空,并尝试写入蓝牙设备。此写入尝试是触发空指针异常的原因。

为什么会这样?为什么outputStream在一行上被评估为NOT null,然后在下一行立即抛出空指针异常?我已尝试使用几种不同的配对蓝牙设备,并获得相同的结果。

BluetoothDevice btDevice = ...//get bluetooth device from user's selection of paired devices

UUID MY_UUID = btDevice.getUuid();

BluetoothDevice remotedevice = btAdapter.getRemoteDevice(btDevice.getAddress());

BluetoothSocket btsocket = remotedevice.createRfcommSocketToServiceRecord(MY_UUID);

InputStream inputStream = btsocket.getInputStream();
OutputStream outputStream = btsocket.getOutputStream();

if (outputStream != null){
         outputStream.write(1);
}

1 个答案:

答案 0 :(得分:1)

OutputStream outputStream = btsocket.getOutputStream();

outputStream永远不会为空,因此您的空检查将始终返回true。

OutputStream getOutputStream ()
Get the output stream associated with this socket.

The output stream will be returned even if the socket is not yet connected, but operations on that stream will throw IOException until the associated socket is connected.

理想情况下,根据文档,它应该抛出IOException (and it does so for API LEVEL >= 21)

public void write(int oneByte) throws IOException {
    byte b[] = new byte[1];
    b[0] = (byte)oneByte;
    mSocket.write(b, 0, 1);
}

mSocket.write(b, 0, 1)使用mSocketOS null并导致异常。 使用API​​&gt; = 21,您将获得带有消息&#34的IOException;在null OutputStream上调用write&#34;

您可以使用btsocket.connect() to initiate the outgoing connection来初始化所需的mSocketOS

在写入socket之前,你应该调用isConnected(),只有与远程设备有活动连接时才会返回true。

 if(btsocket.isConnected()) {
     outputStream.write(1);
 }