检测到蓝牙设备已断开连接

时间:2013-01-14 10:43:28

标签: android bluetooth

我试图找出是否可以可靠地检测到(非音频)设备的蓝牙连接何时丢失。 Android SDK提供了一个蓝牙聊天示例,该示例使用此代码段:

public void run() {
    Log.i(TAG, "BEGIN mConnectedThread");
    byte[] buffer = new byte[1024];
    int bytes;

    // Keep listening to the InputStream while connected
    while (true) {
        try {
            // Read from the InputStream
            bytes = mmInStream.read(buffer);

            // Send the obtained bytes to the UI Activity
            mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            Log.e(TAG, "disconnected", e);
            connectionLost();
            break;
        }
    }
}

当我启动线程并在12小时后断开设备而不使用应用程序(该服务在后台运行)时,此方法的可靠性如何。这项服务总是会被杀死?

然后有广播。我的应用程序是否会一直收到这些广播?什么时候不呢?我已尝试在AndroidManifest中使用它来实现它:

    <receiver android:name="MyReceiver" >
        <intent-filter>
            <action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
            <action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
            <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
        </intent-filter>
    </receiver>

我在短时间内测试了这两种方法,两者都有效。 如前所述,当手机闲置很长时间时,我不确定这些是否可靠。

谁能说清楚这一点?

1 个答案:

答案 0 :(得分:1)

蓝牙中的每个活动都有与之相关的超时。它因设备而异。

只要您启用了蓝牙服务,蓝牙服务就会在后台运行。 ACL [Asynchronous Connection Less]数据包通常用于传输非语音相关数据。 ACL就像两个蓝牙设备之间的连接通道。这可能会根据不活动计时器或超时值断开连接。

您可以在调用HCI createConnection API时读取连接超时集。可以通过执行hcidump tool.http://www.bluez.org/download/

获取此信息。
相关问题