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)