0

Bluetooth デバイスから正常に切断する方法を探しています。私は BluetoothChat サンプルを使用しましたが、問題は、切断しようとするときにメソッドsocket.close()から呼び出すだけで、必然的に例外がスローされることです。cancel()IntputStream.read()

これが必要なのは主に、「接続が失われた」フェイルセーフとしても機能するためです。そのため、切断しようとすると、2 つの信号が表示されます。正常な切断に続いて接続が失われたという信号です。

基本的に私がやろうとしていることは、必然的に例外をスローするメソッドで例外をスローしないことです:

while(true)
{
    try
    {
        bytes = 0;
        while((ch = (byte) inStream.read()) != '\0')
        {
            buffer[bytes++] = ch;
        }

        String msg = new String(buffer, "UTF-8").substring(0, bytes);
        Log.v(TAG, "Read: " + msg);

    }
    catch(IOException e)
    {
        Log.e(TAG, "Failed to read");
        // Inform the parent of failed connection
        connectionEnd(STATE_LOST);
        break;
    }
}

そして非常に利己的cancel()

public void cancel()
{
    try
    {
        socket.close();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
}

編集

これは、私が入ったときに私が得るエラーコードe.printStackTrace();ですcatch:

09-06 13:05:58.557: W/System.err(32696): java.io.IOException: Operation Canceled
09-06 13:05:58.557: W/System.err(32696):    at android.bluetooth.BluetoothSocket.readNative(Native Method)
09-06 13:05:58.557: W/System.err(32696):    at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:333)
09-06 13:05:58.557: W/System.err(32696):    at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:60)
09-06 13:05:58.557: W/System.err(32696):    at com.bluetooth.BluetoothRemoteControlApp$ConnectedThread.run(BluetoothRemoteControlApp.java:368)
4

2 に答える 2

0

これを試してください: outOutputStream のinオブジェクトと InputStream のオブジェクトがあるとします。次に、キャンセル内で次のように接続を閉じます。

public void cancel()
{
    if(socket != null)
        {
            try {
                out.close();
                in.close();
                socket.getOutputStream().close();
                socket.close();
                socket = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace(); 
            }
        }
}

これがあなたを助けることを願っています

于 2012-09-06T03:25:49.403 に答える
0

解決策:完璧ではありませんが、例外を停止する方法がないため、切断条件を作成しました:

catch(IOException e)
{
    if(!disconnecting)
    {
        Log.e(TAG, "Failed to read");
        e.printStackTrace();
        // Inform the parent of failed connection
        connectionEnd(STATE_LOST);
    }
    break;
}

disconnectingtrueメソッドを呼び出す前にに設定されcancel()ます。私はそれに満足していませんが、それほど醜いわけではありません。Bluetooth の切断が処理される方法 (機能するか壊れるか) に満足していません。

于 2012-09-06T12:18:46.607 に答える