Răsfoiți Sursa

安卓连接蓝牙检测提示逻辑修改

lvjincheng 3 ani în urmă
părinte
comite
13203a31e9

+ 27 - 21
Assets/BowArrow/Scripts/Bluetooth/BluetoothAim.cs

@@ -171,22 +171,25 @@ public class BluetoothAim : MonoBehaviour
 
     void ConnectBleHelper()
     {
-        try
+        #if UNITY_ANDROID
+        if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
         {
-            #if UNITY_ANDROID
-            using (var helper = new AndroidJavaClass("com.example.smartbowlib.BluetoothHelper")) 
+            HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception1"));
+            return;
+        }
+        if (BluetoothHelperAndroid.RequestBluetoothPermissions(ConnectBleHelper, (permission) => {
+            if (permission.Contains("LOCATION"))
             {
-                using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) 
-                {
-                    using (var context = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity")) 
-                    {
-                        bool ok = helper.CallStatic<bool>("requestPermissions", context);
-                        if (!ok) throw new Exception("安卓12的蓝牙权限-尚未授权");
-                    }
-                }
+                HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception2"));
             }
-            #endif
-            
+            else if (permission.Contains("BLUETOOTH"))
+            {
+                HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception3"));
+            }
+        })) return;
+        #endif
+        try
+        {
             BluetoothHelper.BLE = true;
             bluetoothHelper = BluetoothHelper.GetNewInstance();
 
@@ -284,16 +287,19 @@ public class BluetoothAim : MonoBehaviour
         }
         catch (Exception e)
         {
-            Debug.LogError(e.Message);
-            Debug.LogError(e.StackTrace);
-            scanLock = false;
-            canConnect = true;
-            // SetStatus(BluetoothStatusEnum.ConnectFail);
-            status = BluetoothStatusEnum.Connect;
-            userDoConnect = false;
-            PopupMgr.ins.ShowTip(TextAutoLanguage2.GetTextByKey("ble-please-open-ble"));
+            Debug.LogError(e);
+            HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-please-open-ble"));
         }
     }
+    void HandleConnectException(string errorText)
+    {
+        scanLock = false;
+        canConnect = true;
+        // SetStatus(BluetoothStatusEnum.ConnectFail);
+        status = BluetoothStatusEnum.Connect;
+        userDoConnect = false;
+        PopupMgr.ins.ShowTip(errorText);
+    }
 
     void ConnectBleByUDP()
     {

+ 108 - 0
Assets/BowArrow/Scripts/Bluetooth/BluetoothHelperAndroid.cs

@@ -0,0 +1,108 @@
+using System.Collections;
+using System.Collections.Generic;
+using UnityEngine;
+using UnityEngine.Events;
+using UnityEngine.Android;
+
+public class BluetoothHelperAndroid
+{
+    public static bool IsBluetoothEnabled()
+    {
+        using (var classBluetoothAdapter = new AndroidJavaClass("android.bluetooth.BluetoothAdapter"))
+        using (var bluetoothAdapter = classBluetoothAdapter.CallStatic<AndroidJavaObject>("getDefaultAdapter"))
+        {
+            if (bluetoothAdapter == null)
+            {
+                Debug.Log("当前设备不支持蓝牙功能");
+                return false;
+            }
+            bool isEnabled = bluetoothAdapter.Call<bool>("isEnabled");
+            return isEnabled;
+        }
+    }
+
+    public static bool RequestBluetoothPermissions(UnityAction onAllGranted, UnityAction<string> onDenied)
+    {
+        using (var buildVersion = new AndroidJavaClass("android.os.Build$VERSION"))
+        {
+            int sdkInt = buildVersion.GetStatic<int>("SDK_INT");
+            List<string> permissionListA = new List<string>();
+            List<string> permissionListB = new List<string>();
+            List<string> permissionListC = new List<string>();
+            if (sdkInt >= 23)
+            {
+                permissionListA.Add(Permission.CoarseLocation);
+                permissionListA.Add(Permission.FineLocation);
+                if (sdkInt >= 29)
+                    permissionListB.Add("android.permission.ACCESS_BACKGROUND_LOCATION");
+                if (sdkInt < 31)
+                {
+                    permissionListC.Add("android.permission.BLUETOOTH");
+                    permissionListC.Add("android.permission.BLUETOOTH_ADMIN");
+                }
+                else
+                {
+                    permissionListC.Add("android.permission.BLUETOOTH_SCAN");
+                    permissionListC.Add("android.permission.BLUETOOTH_ADVERTISE");
+                    permissionListC.Add("android.permission.BLUETOOTH_CONNECT");
+                }
+            }
+            if (IsPermissionsGranted(permissionListA)
+                && IsPermissionsGranted(permissionListB)
+                && IsPermissionsGranted(permissionListC)) return false;
+            RequestUserPermissions(permissionListA.ToArray(), () =>
+            {
+                RequestUserPermissions(permissionListB.ToArray(), () =>
+                {
+                    RequestUserPermissions(permissionListC.ToArray(), onAllGranted, onDenied);
+                }, onDenied);
+            }, onDenied);
+            return true;
+        }
+    }
+
+    private static bool IsPermissionsGranted(List<string> permissions)
+    {
+        foreach (var permission in permissions)
+            if (!Permission.HasUserAuthorizedPermission(permission)) return false;
+        return true;
+    }
+
+    private static void RequestUserPermissions(string[] permissions, UnityAction onAllGranted, UnityAction<string> onDenied)
+    {
+        bool hasExecuteOnDenied = false;
+        List<string> permissionsNeedRequest = new List<string>();
+        foreach (var permission in permissions)
+            if (!Permission.HasUserAuthorizedPermission(permission)) permissionsNeedRequest.Add(permission);
+        if (permissionsNeedRequest.Count > 0)
+        {
+            var requestCallback = new PermissionCallbacks();
+            requestCallback.PermissionGranted += (permission) =>
+            {
+                Debug.Log("用户同意" + permission);
+                permissionsNeedRequest.Remove(permission);
+                if (permissionsNeedRequest.Count == 0) onAllGranted?.Invoke();
+            };
+            requestCallback.PermissionDenied += (permission) =>
+            {
+                Debug.LogWarning("用户拒绝" + permission);
+                if (!hasExecuteOnDenied)
+                {
+                    hasExecuteOnDenied = true;
+                    onDenied?.Invoke(permission);
+                }
+            };
+            requestCallback.PermissionDeniedAndDontAskAgain += (permission) =>
+            {
+                Debug.LogWarning("用户拒绝且要求不再询问" + permission);
+                if (!hasExecuteOnDenied)
+                {
+                    hasExecuteOnDenied = true;
+                    onDenied?.Invoke(permission);
+                }
+            };
+            Permission.RequestUserPermissions(permissionsNeedRequest.ToArray(), requestCallback);
+        }
+        else onAllGranted?.Invoke();
+    }
+}

+ 11 - 0
Assets/BowArrow/Scripts/Bluetooth/BluetoothHelperAndroid.cs.meta

@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 693ae16e5e35d1143b4822a312c2e2b8
+MonoImporter:
+  externalObjects: {}
+  serializedVersion: 2
+  defaultReferences: []
+  executionOrder: 0
+  icon: {instanceID: 0}
+  userData: 
+  assetBundleName: 
+  assetBundleVariant: 

+ 3 - 0
Assets/BowArrow/Scripts/Components/TextAutoLanguage2/Resources/TextAutoLanguage2/cn.json

@@ -140,6 +140,9 @@
     "tip_phone-menu-back_quit-app": "再按一次退出APP",
     "about-us_content": "<color=#FFFFFF00>缩进</color>青凤鸾是一个技能运动智能硬件品牌。产品包含智能弓箭、智能射击、智能滑雪、智能高尔夫等。青凤鸾希望通过创新的智能硬件,让技能运动变得触手可及。并在疫情的大环境下,让人们的室内运动生活更加丰富有趣。",
     "ble-please-open-ble": "请求蓝牙失败,可能原因:\n1.未打开手机蓝牙\n2.未授予蓝牙定位权限",
+    "ble-exception1": "未打开手机蓝牙开关",
+    "ble-exception2": "需要始终允许<定位>权限",
+    "ble-exception3": "需要始终允许<连接附近的设备>权限",
 
     "MagInterferenceTip_content": "由于地磁计初始化易受到周围环境的影响,因此在初始化过程中请按照以下步骤来做:\n1、请在初始化过程中,保持周围环境的稳定,远离金属物体和磁场干扰。\n2、请保持智能弓箭模块和手机、电视等电子设备0.5米以上的距离。\n3、请将安装了模块的智能弓箭或单独模块沿着XYZ三轴进行充分地旋转,直到提示完成为止。\n4、如多次无法完成初始化,也可继续使用,只是瞄准的精度会受到影响,游戏中需多做一次视角归位的操作。",
     "MagInterferenceTip_ok": "确定",

+ 3 - 0
Assets/BowArrow/Scripts/Components/TextAutoLanguage2/Resources/TextAutoLanguage2/en.json

@@ -140,6 +140,9 @@
     "tip_phone-menu-back_quit-app": "Press again to exit the app",
     "about-us_content": "Qingfengluan is a skill sports intelligent hardware brand. Products include intelligent bow and arrow, intelligent shooting, intelligent skiing, intelligent golf, etc. Qingfengluan hopes to make skill sports accessible through innovative intelligent hardware. And in the context of the epidemic, make people's indoor sports life more rich and interesting.",
     "ble-please-open-ble": "Failed to request Bluetooth. Possible causes:\n1.Bluetooth is not turned on\n2.Bluetooth location permission not granted",
+    "ble-exception1": "Bluetooth switch of mobile phone is not turned on",
+    "ble-exception2": "Need to always allow <Get location info> permission",
+    "ble-exception3": "Need to always allow <Connect to nearby devices> permission",
 
     "MagInterferenceTip_content": "Since the initialization of the magnetometer is vulnerable to the influence of the surrounding environment, please follow the following steps in the initialization process: \n1. Please keep the surrounding environment stable and away from metal objects and magnetic field interference during the initialization process. \n2. Please keep a distance of more than 0.5m between the smart bow module and electronic devices such as mobile phones and televisions. \n3. Please fully rotate the smart bow or individual module with the module installed along the XYZ axis until the prompt is completed. \n4. If the initialization cannot be completed for many times, it can still be used. However, the accuracy of aiming will be affected, and the game needs to do one more angle of view homing operation.",
     "MagInterferenceTip_ok": "OK",