4

bluetoothChat サンプル アプリでは、送受信されたデータが という ArrayAdapter に追加されmConversationArrayAdapterます。そこで、各文字が配列に追加されます。

私の場合、複数のデータを送受信する必要がなく、1 つの文字列を送信し、毎回 1 つの文字列を受信するだけでよいため、配列の代わりに文字列を使用しています。

私が得ている問題は、最初に のような文字列hello worldを受け取り、次に短い文字列を受け取った場合、最初の文字列を削除して新しい文字列を書き込むのではなく、最初の文字列が 2 番目の文字列によって上書きされることです。

したがって、最初に を受け取りhello world、次に を受け取る必要があると仮定するとbye、実際に受け取るのはbyelo worldです。

では、必要なものを受信するたびにバッファをクリアするにはどうすればよいですか?

コード スニペット

データを送る:

    byte[] send1 = message_full1.getBytes();
    GlobalVar.mTransmission.write(send1);

書き込み呼び出し:

public void write(byte[] out) {
    /**Create temporary object*/
    ConnectedThread r;
    /**Synchronize a copy of the ConnectedThread*/
    synchronized (this) {
        if (GlobalVar.mState != GlobalVar.STATE_CONNECTED) return;
        r = GlobalVar.mConnectedThread;
    }
    /**Perform the write unsynchronized*/
    r.write(out);
}

書き込みスレッド:

    public void write(byte[] buffer) {
    try {
        GlobalVar.mmOutStream.write(buffer);

        /**Share the sent message back to the UI Activity*/
        GlobalVar.mHandler.obtainMessage(GlobalVar.MESSAGE_WRITE, -1, -1, buffer).sendToTarget();

    } catch (IOException e) {}
}

最後に、スレッドを読んでください:

    public void run() {
    byte[] buffer = new byte[12];  // buffer store for the stream
    int bytes; // bytes returned from read()

    /**Keep listening to the InputStream until an exception occurs*/
    while (true) {
        try {
            /**Read from the InputStream*/
            bytes = GlobalVar.mmInStream.read(buffer);

            /**Send the obtained bytes to the UI activity*/
            GlobalVar.mHandler.obtainMessage(GlobalVar.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
        } catch (IOException e) {
            GlobalVar.mTransmission.connectionLost();
            /**Start the service over to restart listening mode*/
            //GlobalVar.mTransmission.start();
            break;
        }
    }
}
4

1 に答える 1