From 0b7b3b512754e78fff0adb03e2c64ce1d09a0873 Mon Sep 17 00:00:00 2001 From: Aurimas Cernius Date: Mon, 26 Sep 2022 12:16:28 +0300 Subject: [PATCH] Request permission on Android 13 --- .../Android/AndroidNotificationsPlatform.cs | 33 +++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/Assets/Scripts/Android/AndroidNotificationsPlatform.cs b/Assets/Scripts/Android/AndroidNotificationsPlatform.cs index 355c70c..164d38d 100644 --- a/Assets/Scripts/Android/AndroidNotificationsPlatform.cs +++ b/Assets/Scripts/Android/AndroidNotificationsPlatform.cs @@ -2,6 +2,8 @@ using System; using System.Collections; using Unity.Notifications.Android; +using UnityEngine; +using UnityEngine.Android; namespace NotificationSamples.Android { @@ -30,9 +32,34 @@ namespace NotificationSamples.Android public IEnumerator RequestNotificationPermission() { - var request = new PermissionRequest(); - while (request.Status == PermissionStatus.RequestPending) - yield return null; + const string notificationPermission = "android.permission.POST_NOTIFICATIONS"; + const int permissionRequiredSDK = 33; + + using (var version = new AndroidJavaClass("android/os/Build$VERSION")) + { + var deviceSdk = version.GetStatic("SDK_INT"); + if (deviceSdk < permissionRequiredSDK) + yield break; + } + + if (Permission.HasUserAuthorizedPermission(notificationPermission)) + yield break; + + using (var playerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) + { + using (var activity = playerClass.GetStatic("currentActivity")) + { + using (var appInfo = activity.Call("getApplicationInfo")) + { + var targetSdk = appInfo.Get("targetSdkVersion"); + if (targetSdk < permissionRequiredSDK) + yield break; + } + } + } + + Permission.RequestUserPermission(notificationPermission); + yield return null; } ///