Android 如何获取已连接的蓝牙地址

本文探讨了在Android项目中如何获取已连接蓝牙设备的地址。通过分析源码,发现BluetoothAdapter的mService是关键,实际操作由AdapterServiceBinder执行。重点关注BluetoothProfile接口及其子类如BluetoothHeadset和BluetoothA2dp,它们定义了不同类型的蓝牙连接。当使用默认方法无效时,可以尝试使用BluetoothAdapter的隐藏方法直接调用AdapterProperties的getConnectionState方法。
摘要由CSDN通过智能技术生成

项目中有一个需求,就是获取已连接的蓝牙地址

private void getConnectBt() {
        LogUtil.i("getConnectBt");

        int a2dp = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
        int headset = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
        int health = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH);
        int flag = -1;
        if (a2dp == BluetoothProfile.STATE_CONNECTED) {
            flag = a2dp;
        } else if (headset == BluetoothProfile.STATE_CONNECTED) {
            flag = headset;
        } else if (health == BluetoothProfile.STATE_CONNECTED) {
            flag = health;
        }

        Log.d(TAG,"flag:"+flag);
        if (flag != -1) {
        _bluetoothAdapter.getProfileProxy(_context, new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceDisconnected(int profile) {

            }

            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
                if (mDevices != null && mDevices.size() > 0) {
                    for (BluetoothDevice device : mDevices) {
                        Log.d(TAG,device.getName() + "," + device.getAddress());
                    }
                } else {

                }
            }
        }, flag);

        }
    }

从网上看到这段代码并没有作用,由于flag一直等于-1,所以一直返回BluetoothProfile.STATE_DISCONNECTED。也就是说
        int a2dp = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
        int headset = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
        int health = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH);
这三个方法都是返回的BluetoothProfile.STATE_DISCONNECTED


                
  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值