I am confused on how I am supposed to request permissions access on the main thread of an android app if it needs to be async. I want to do this as soon as my application opens, but as is I am getting the following error: "Permission request must be invoked on main thread."
How do I do this? My understanding is that RequestAsync
requires a separate thread (Since it's an async method call).
public partial class SplashPage : ContentPage
{
PermissionStatus LocationPermission;
public SplashPage()
{
InitializeComponent();
LocationPermission = PermissionStatus.Unknown;
}
protected override void OnAppearing()
{
var result = Task.Run(async () => await CheckLocationPermission());
result.Wait();
var resultval = result.Result;
result = Task.Run(async () => await RequestLocationPermission());
result.Wait();
}
public async Task<PermissionStatus> CheckLocationPermission()
{
LocationPermission = await Permissions.CheckStatusAsync<Permissions.LocationWhenInUse>();
return LocationPermission;
}
public async Task<PermissionStatus> RequestLocationPermission()
{
try
{
if (LocationPermission == PermissionStatus.Granted)
return LocationPermission;
if (Permissions.ShouldShowRationale<Permissions.LocationWhenInUse>())
{
await Shell.Current.DisplayAlert("Needs Permissions", "BECAUSE!!!", "OK");
}
LocationPermission = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
}
catch (Exception ex)
{
//Error that permissions request must be on main thread **
Console.WriteLine(ex.Message);
}
return LocationPermission;
}
}
AppShell.xaml:
<?xml version="1.0" encoding="UTF-8" ?>
<Shell
x:Class="CellularSignal1.AppShell"
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:CellularSignal1"
Shell.FlyoutBehavior="Disabled">
<TabBar x:Name="MyTabBar">
<Tab x:Name="CellularInfo" Title="Cellular Info">
<ShellContent ContentTemplate="{DataTemplate local:SplashPage}" Route="SplashPage"/>
<ShellContent ContentTemplate="{DataTemplate local:CellularInfo}" Route="CellularInfo"/>
<ShellContent ContentTemplate="{DataTemplate local:BSInfo}" Route="BSInfo"/>
</Tab>
</TabBar>
</Shell>
AppShell.xaml.cs:
namespace CellularSignal1;
#if ANDROID
public partial class AppShell : Shell
{
public AppShell()
{
InitializeComponent();
}
}
#endif