簡體   English   中英

為什么來自BluetoothSocket的輸入/輸出流被評估為非空值,然后引發空指針異常?

[英]Why do input/outputstream from BluetoothSocket get evaluated as NOT null, then throw null pointer exception?

我有一個從藍牙套接字創建的輸入流和輸出流,在檢查套接字是否為空(這全部在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);
}

無論藍牙設備是否已連接或在范圍內,輸出流都將被評估為“非空”,並嘗試對其進行寫入。 這種寫嘗試是觸發空指針異常的原因。

為什么會這樣? 為什么outputStream的評估結果在一行中不為null,然后在下一行立即引發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 (並且對於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)使用null mSocketOS並導致異常。 使用API​​> = 21,您將獲得IOException並顯示消息“在null OutputStream上調用了寫操作”

您可以使用btsocket.connect() 發起傳出連接 ,這將初始化所需的mSocketOS

在寫入套接字之前,您應該調用isConnected() ,該方法僅在與遠程設備存在活動連接時才返回true。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM