如何以编程方式判断一个蓝牙设备连接? (安卓2.2) [英] How to programmatically tell if a Bluetooth device is connected? (Android 2.2)

查看:213
本文介绍了如何以编程方式判断一个蓝牙设备连接? (安卓2.2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何获得配对设备列表,但我怎么能知道,如果他们有联系吗?

I understand how to get a list of paired devices but how can I tell if they are connected?

因为我看到他们在我的手机的蓝牙设备列表中列出它必须是可能的,它指出他们的连接状态。

It must be possible since I see them listed in my phone's Bluetooth device list and it states their connection status.

推荐答案

使用意图过滤器来听ACTION_ACL_CONNECTED,ACTION_ACL_DISCONNECT_REQUESTED和ACTION_ACL_DISCONNECTED广播:

Use intent filters to listen to the ACTION_ACL_CONNECTED, ACTION_ACL_DISCONNECT_REQUESTED, and ACTION_ACL_DISCONNECTED broadcasts:

public void onCreate() {
    ...
    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(mReceiver, filter1);
    this.registerReceiver(mReceiver, filter2);
    this.registerReceiver(mReceiver, filter3);
}

//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
           ... //Device found
        }
        else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
           ... //Device is now connected
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
           ... //Done searching
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
           ... //Device is about to disconnect
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
           ... //Device has disconnected
        }           
    }
};

的几个注意事项:

A few notes:

  • 没有方法来检索在应用程序启动连接的设备的列表。蓝牙API不允许你查询,相反,它可以让你听的变化。
  • 系统hoaky工作围绕上述问题将是获取所有已知/配对设备的列表...,然后尝试连接到每一个(以确定是否已连接)。
  • 或者,你可以有一个后台服务观看蓝牙API和写入设备状态到硬盘为您的应用在日后使用。

这篇关于如何以编程方式判断一个蓝牙设备连接? (安卓2.2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆