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