Skip to content

Instantly share code, notes, and snippets.

@thsbrown
Created October 24, 2024 18:39
Show Gist options
  • Save thsbrown/8da183b6b1cab784ac3b1a159e4a978b to your computer and use it in GitHub Desktop.
Save thsbrown/8da183b6b1cab784ac3b1a159e4a978b to your computer and use it in GitHub Desktop.
Converts unity android runtime permission API to async
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Android;
//see https://docs.unity3d.com/ScriptReference/Android.Permission.html
//see https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Android.PermissionCallbacks.html
public static class AndroidRuntimeAsyncPermissionService
{
public static async Task<PermissionResult> RequestPermissionAsync(string permission)
{
// If the user has already granted permission, return Granted
if (Permission.HasUserAuthorizedPermission(permission))
{
return PermissionResult.Granted;
}
// Otherwise, request permission
var tcs = new TaskCompletionSource<PermissionResult>();
var callbacks = new PermissionCallbacks();
// Define the callback events
callbacks.PermissionGranted += OnPermissionGranted;
callbacks.PermissionDenied += OnPermissionDenied;
callbacks.PermissionDeniedAndDontAskAgain += OnPermissionDeniedAndDontAskAgain;
// Request the permission
Permission.RequestUserPermission(permission, callbacks);
// Await the completion of the permission request
return await tcs.Task;
// Local callback methods
void OnPermissionGranted(string permissionName)
{
if (permissionName == permission)
{
tcs.SetResult(PermissionResult.Granted);
CleanupCallbacks();
}
}
void OnPermissionDenied(string permissionName)
{
if (permissionName == permission)
{
tcs.SetResult(PermissionResult.Denied);
CleanupCallbacks();
}
}
void OnPermissionDeniedAndDontAskAgain(string permissionName)
{
if (permissionName == permission)
{
tcs.SetResult(PermissionResult.DeniedAndDontAskAgain);
CleanupCallbacks();
}
}
void CleanupCallbacks()
{
callbacks.PermissionGranted -= OnPermissionGranted;
callbacks.PermissionDenied -= OnPermissionDenied;
callbacks.PermissionDeniedAndDontAskAgain -= OnPermissionDeniedAndDontAskAgain;
}
}
public enum PermissionResult
{
Granted,
Denied,
DeniedAndDontAskAgain
}
}
// Example usage:
// var result = await AndroidRuntimeAsyncPermissionService.RequestPermissionAsync("android.permission.POST_NOTIFICATIONS");
// Debug.Log($"Push notification permission result: {result}");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment