从Android设备连接嵌入式蓝牙设备

7

我刚刚开始通过我的安卓手机连接嵌入式蓝牙设备。连接很顺利,但是当我没有正确断开连接时会遇到问题。我的意思是首先关闭套接字,然后关闭任何打开的输入/输出流。

但是当我突然关闭设备中的蓝牙时,我怎么知道蓝牙已经断开连接呢?是否有一种方法可以在应用程序中始终接收蓝牙断开连接的监听器?

有任何想法吗?谢谢

mmSocket= device.createRfcommSocketToServiceRecord(uuidToTry);
try
{
    mmSocket.connect();
}
catch (IOException e)
{
    mmSocket.close();
}
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);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接