Location permission for Android above 6.0 with Xamarin.Forms.Maps
You wrote a lot of code about permission but I can't find where you request the permission, you need request the permission before you use it.
When you set IsShowingUser
property to true, you should request the permission first, here are three solutions.
Solution 1:
I notice that you are using PermissionsPlugin in your code, if you need request this permission in PCL
, you could refer to the PermissionsPlugin official sample.
Add this code in your MainActivity
:
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
Request permission when you need it:
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{
if(await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
{
await DisplayAlert("Need location", "Gunna need that location", "OK");
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
status = results[Permission.Location];
}
if (status == PermissionStatus.Granted)
{
//Permission granted, do what you want do.
}
else if(status != PermissionStatus.Unknown)
{
await DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
}
}
catch (Exception ex)
{
//...
}
Solution 2:
When you open your application, request the permission first, in MainActivity
OnStart
method:
protected override void OnStart()
{
base.OnStart();
if (ContextCompat.CheckSelfPermission(this, permission) != Permission.Granted)
{
ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.AccessCoarseLocation, Manifest.Permission.AccessFineLocation }, 0);
}
else
{
System.Diagnostics.Debug.WriteLine("Permission Granted!!!");
}
}
Solution 3:
Use DependencyService to request the permission when you need it, here is the sample related to the tutorial you have read. In this example, it requests permission when execute this line:
buttonGetLocation.Click += async (sender, e) => await TryGetLocationAsync();