0

卡在一个问题上,

我正在使用BluetoothSocket类,我在输入和输出流的帮助下发送和接收数据。

当应用程序从输入流中接收到大量数据时,我会强行杀死我的应用程序,之后我会再次重新启动我的应用程序,但InputStream会返回以前的数据,这些数据不再需要了。如何丢弃旧数据?

有没有人解决这个问题?

以下是我的源代码:

public class MyBluetoothService {
private static final String TAG = "MY_APP_DEBUG_TAG";
private Handler mHandler; // handler that gets info from Bluetooth service

// Defines several constants used when transmitting messages between the
// service and the UI.
private interface MessageConstants {
    public static final int MESSAGE_READ = 0;
    public static final int MESSAGE_WRITE = 1;
    public static final int MESSAGE_TOAST = 2;

    // ... (Add other message types here as needed.)
}

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
    private byte[] mmBuffer; // mmBuffer store for the stream

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams; using temp objects because
        // member streams are final.
        try {
            tmpIn = socket.getInputStream();
        } catch (IOException e) {
            Log.e(TAG, "Error occurred when creating input stream", e);
        }
        try {
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "Error occurred when creating output stream", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        mmBuffer = new byte[1024];
        int numBytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs.
        while (true) {
            try {
                // Read from the InputStream.
                numBytes = mmInStream.read(mmBuffer);
                // Send the obtained bytes to the UI activity.
                Message readMsg = mHandler.obtainMessage(
                        MessageConstants.MESSAGE_READ, numBytes, -1,
                        mmBuffer);
                readMsg.sendToTarget();
            } catch (IOException e) {
                Log.d(TAG, "Input stream was disconnected", e);
                break;
            }
        }
    }

    // Call this from the main activity to send data to the remote device.
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);

            // Share the sent message with the UI activity.
            Message writtenMsg = mHandler.obtainMessage(
                    MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer);
            writtenMsg.sendToTarget();
        } catch (IOException e) {
            Log.e(TAG, "Error occurred when sending data", e);

            // Send a failure message back to the activity.
            Message writeErrorMsg =
                    mHandler.obtainMessage(MessageConstants.MESSAGE_TOAST);
            Bundle bundle = new Bundle();
            bundle.putString("toast",
                    "Couldn't send data to the other device");
            writeErrorMsg.setData(bundle);
            mHandler.sendMessage(writeErrorMsg);
        }
    }

    // Call this method from the main activity to shut down the connection.
    public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "Could not close the connect socket", e);
            }
        }
    }
}
4

2 回答 2

1
// Keep listening to the InputStream until an exception occurs

问题就在这里。您应该继续从流中读取,直到流结束或发生异常。read()如果返回 -1 ,则需要跳出读取循环。

目前,您正在读取超出流的末尾,并且完全忽略了条件,因此最后一次成功读取时缓冲区中的数据当然仍然存在。

为了让您的应用程序继续看到该数据,您还必须忽略读取计数并假设缓冲区已填满,这也是无效的。

于 2018-03-21T22:30:09.580 回答
-1

我认为你应该关闭套接字来管理错误。

我建议您在终结器中执行此操作,如下面的代码。

private class ConnectedThread extends Thread
 {
 private final BluetoothSocket mmSocket;
 private final InputStream mmInStream;
 private final OutputStream mmOutStream;
 private byte[] mmBuffer; // mmBuffer store for the stream
 @override
 protected void finalize() throws Throwable
 {
   try
   {
       cancel();
   }
   finally
   {
        super.finalize();
   }
 }
...

同样正如我在评论中提到的,stream在关闭套接字之前关闭每个 s 会更安全。

所以,试试这个cancel()方法。

// Call this method from the main activity to shut down the connection.
 public void cancel()
 {
     try {
        mmInStream.close();
     } catch( NullPointerException | IOException e) {}
    try {
        mmOutStream.close();
     } catch( NullPointerException | IOException e) {}

     try
     {
         mmSocket.close();
     } catch (IOException e) {
         Log.e(TAG, "Could not close the connect socket", e);
     }
 }

以及有关方法的更多信息。finalize

编辑:粗体比其他建议重要。

阅读 EJP 的评论,我明白了为什么当您获得大数据时您的应用程序会停止:您可能需要在调用之前清除缓冲区read()。他说终结器可能不会被系统调用(我不知道为什么)。 返回时如何 break循环read() -1

刚才我发现了一个有用的链接,关于正确的方法来读取流。我希望它有所帮助。

从链接引用的代码

private String extract(InputStream inputStream) throws IOException
 {
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
                      byte[] buffer = new byte[1024];
      int read = 0;
      while ((read = inputStream.read(buffer, 0, buffer.length)) != -1) {
          baos.write(buffer, 0, read);
      }   
          baos.flush();
        return new String(baos.toByteArray(), "UTF-8");
  }

此外 ,虽然在关闭之前finalizer可能无法通过系统关闭来调用它更安全(我之前读过一些 SO 线程)。streamssockets

于 2018-03-21T08:27:19.967 回答