我有一个从蓝牙套接字创建的输入流和输出流,在检查套接字是否为空后,我尝试向其中写入一些内容(这全部在 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 并尝试写入它。此写入尝试会触发空指针异常。
为什么会发生这种情况?为什么outputStream在一行上计算为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
永远不会为 null,因此您的 null 检查将始终返回 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 >= 21 时,您将收到 IOException
并显示消息“在 null OutputStream 上调用 write”
您可以使用btsocket.connect()
to initiate the outgoing connection这将初始化所需的mSocketOS
。
在写入套接字之前,您应该调用 isConnected()
,仅当与远程设备存在 Activity 连接时,该函数才会返回 true。
if(btsocket.isConnected()) {
outputStream.write(1);
}
关于java - 为什么来自BluetoothSocket的输入/输出流被评估为NOT null,然后抛出空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42570426/