如何以编程方式判断蓝牙设备是否已连接? (Android 2.2)

时间:2011-01-17 17:13:45

标签: android android-bluetooth

我了解如何获取配对设备列表,但如何判断它们是否已连接?

必须可以,因为我看到它们列在我手机的蓝牙设备列表中,并说明了它们的连接状态。

8 个答案:

答案 0 :(得分:131)

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

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

//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
        }           
    }
};

一些注意事项:

  • 在应用程序启动时无法检索已连接设备的列表。蓝牙API不允许您进行查询,而是允许您收听更改。
  • 解决上述问题的一个愚蠢的工作是检索所有已知/配对设备的列表...然后尝试连接到每个设备(以确定您是否已连接)。
  • 或者,您可以让后台服务观看蓝牙API并将设备状态写入磁盘,以便日后使用。

答案 1 :(得分:21)

在我的使用案例中,我只想查看是否为VoIP应用程序连接了蓝牙耳机。以下解决方案对我有用:

public static boolean isBluetoothHeadsetConnected() {
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    return mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()
            && mBluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED;
} 

当然,您需要获得蓝牙许可:

<uses-permission android:name="android.permission.BLUETOOTH" />

答案 2 :(得分:10)

非常感谢Skylarsutton的回答。我发布此作为对他的回复,但因为我发布的代码我无法回复评论。我已经提出了他的答案,所以我不是在寻找任何积分。只是向前付钱。

由于某些原因,Android Studio无法解析BluetoothAdapter.ACTION_ACL_CONNECTED。也许它在Android 4.2.2中被弃用了?这是他的代码的修改。注册码是一样的;接收者代码稍有不同。我在一项服务中使用它来更新应用程序的其他部分引用的蓝牙连接标志。

    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 BTReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            //Do something if connected
            Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            //Do something if disconnected
            Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
        }
        //else if...
    }
};

答案 3 :(得分:1)

此代码用于耳机配置文件,可能也适用于其他配置文件。 首先,您需要提供配置文件侦听器(科特琳代码):

private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) 
            mBluetoothHeadset = proxy as BluetoothHeadset            
    }

    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null
        }
    }
}

然后在检查蓝牙时:

mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
    return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}

在调用onSeviceConnected之前需要花费一些时间。之后,您可以从以下位置获取已连接的耳机设备的列表:

mBluetoothHeadset!!.connectedDevices

答案 4 :(得分:0)

currentNode.setNext(node);-> 蓝牙打开时返回true

BluetoothAdapter.getDefaultAdapter().isEnabled为 AudioManager

val audioManager = this.getSystemService(Context.AUDIO_SERVICE)-> 连接设备后返回true

答案 5 :(得分:0)

我知道这个线程有点旧,但是我真的需要知道在我的应用程序启动时是否已连接设备,并且找到了解决方案!

//List of Paired Devices
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.

    for (BluetoothDevice device : pairedDevices) {
        String deviceName = device.getName();
        String deviceHardwareAddress = device.getAddress(); // MAC address
    }
}
else {
//There are no paired devices.
}

也可以在Kotlin上找到它:https://developer.android.com/guide/topics/connectivity/bluetooth#QueryPairedDevices

答案 6 :(得分:0)

https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/bluetooth/BluetoothDevice.java的BluetoothDevice系统API中有一个 isConnected 功能。

如果您想知道有界(配对)的设备当前是否已连接,以下功能对我来说很好用:

public static boolean isConnected(BluetoothDevice device) {
    try {
        Method m = device.getClass().getMethod("isConnected", (Class[]) null);
        boolean connected = (boolean) m.invoke(device, (Object[]) null);
        return connected;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

答案 7 :(得分:0)

我真的在寻找一种方法来获取设备的连接状态,而不是监听连接事件。这是对我有用的东西:

BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bm.getConnectedDevices(BluetoothGatt.GATT);
int status = -1;

for (BluetoothDevice device : devices) {
  status = bm.getConnectionState(device, BLuetoothGatt.GATT);
  // compare status to:
  //   BluetoothProfile.STATE_CONNECTED
  //   BluetoothProfile.STATE_CONNECTING
  //   BluetoothProfile.STATE_DISCONNECTED
  //   BluetoothProfile.STATE_DISCONNECTING
}