Unity3d 获取蓝牙状态

发表于2018-10-29
评论0 8.5k浏览
如何判断当前蓝牙状态是开启还是关闭,是未连接还是已连接呢,下面这篇文章给大家分享下使用Unity引擎开发安卓应用是获取蓝牙状态的实现,具体代码如下,一起来看看吧。

C#
    // 返回值:
    // -5: 未知
    // -4: (iOS)复位
    // -3: 没有蓝牙权限
    // -2: (Android)获取蓝牙适配器错误,(iOS)不支持蓝牙
    // -1: 蓝牙未开启
    //  0: 蓝牙已开启,未连接
    //  1: (Android)蓝牙连接中
    //  2: (Android)蓝牙已连接
    public static int GetBluetoothState()
    {
        int state = -5;
#if UNITY_ANDROID && !UNITY_EDITOR
        try
        {
            AndroidJavaClass tUtils = new AndroidJavaClass("java类全名");
            if (tUtils != null)
            {
                int tempState = tUtils.CallStatic<int>("GetBluetoothState");
                state = tempState;
            }
        }
        catch (Exception )
        {
            state = -5;
        }
#elif UNITY_IPHONE && !UNITY_EDITOR
#endif
        return state;
    }

Java
public static int GetBluetoothState()
    {
        BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
        if (ba == null) {
            return -2;
        }
        try {
            if (!ba.isEnabled()) {
                return -1;
            }
        } catch (Exception e) {
            return -3;
        }
        try {
            //可操控蓝牙设备,如带播放暂停功能的蓝牙耳机
            int a2dp = ba.getProfileConnectionState(BluetoothProfile.A2DP);
            if (a2dp == BluetoothProfile.STATE_CONNECTING || a2dp == BluetoothProfile.STATE_CONNECTED) {
                return a2dp;
            }
            //蓝牙头戴式耳机,支持语音输入输出
            int headset = ba.getProfileConnectionState(BluetoothProfile.HEADSET);
            if (headset == BluetoothProfile.STATE_CONNECTING || headset == BluetoothProfile.STATE_CONNECTED) {
                return headset;
            }
            //蓝牙穿戴式设备
            int health = ba.getProfileConnectionState(BluetoothProfile.HEALTH);
            if (health == BluetoothProfile.STATE_CONNECTING || health == BluetoothProfile.STATE_CONNECTED) {
                return health;
            }
        } catch (Exception e) {
        }
        return BluetoothProfile.STATE_DISCONNECTED;
    }
来自:https://blog.csdn.net/qqo_aa/article/details/78483568

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引