为什么来自蓝牙插座的输入/输出流被评估为非空,然后抛出空指针异常?



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

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);
}

无论蓝牙设备是否已连接或在范围内,输出流都将被评估为 NOT null,并将尝试写入它。此写入尝试触发空指针异常。

为什么会这样?为什么输出流在一行上计算为不为空,然后在下一行立即抛出空指针异常?我已经用几个不同的配对蓝牙设备尝试过这个,并得到了相同的结果。

java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[], int, int)' on a null object reference
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(对于 API 级别>= 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)使用null并导致异常的mSocketOS。 使用 API>= 21,您将获得消息"在空输出流上调用写入"IOException

您可以使用btsocket.connect()启动传出连接,这将初始化所需的mSocketOS

在写入套接字之前,您应该调用isConnected()仅当与远程设备存在活动连接时才返回 true。

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

最新更新