7

我刚刚开始通过我的 Android 手机连接到嵌入式 BT 设备。它连接正常,但是当我没有正确断开连接时我遇到了问题。我的意思是首先关闭套接字,然后打开任何 i/o 蒸汽。

但是当我在设备中突然关闭我的蓝牙时,我怎么知道蓝牙正在断开连接。有什么方法可以在APP中一直接收蓝牙断开监听。

有任何想法吗 ....?谢谢

mmSocket= device.createRfcommSocketToServiceRecord(uuidToTry);
try
{
    mmSocket.connect();
}
catch (IOException e)
{
    mmSocket.close();
}
4

1 回答 1

1

你可以这样做——在你的代码中创建一个广播接收器像这样:

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (!mBluetoothAdapter.isEnabled()) {
                // BT is turened off.
            }
            else{
                // BT is turened on.
              }
        }
 }
};

并为以下意图过滤器注册该广播接收器:

IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(mReceiver, filter);

于 2013-02-27T10:19:57.700 回答