unity3d 获取蓝牙 状态 android

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;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值