My app is terminating due to permission issue on A

2020-05-03 12:07发布

问题:

I'm writing this code for getting gps location, I've marked ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION on Android properties and I also confirmed if it was in AndroidManifest.xml but the application is terminating:

10-08 19:52:50.048 I/mono-stdout( 2905): Currently does not have Location permissions, requesting permissionsCurrently does not have Location permissions, requesting permissions

Location permission denied, can not get positions async.10-08 19:52:50.103 I/mono-stdout( 2905): Location permission denied, can not get positions async.

If I go to Configuration>Applications>Permissions and give location permission it works properly but it isn't asking for permissions at the installation time.

The code:

using Plugin.Geolocator;
using Plugin.Geolocator.Abstractions;
using System;
using Xamarin.Forms;

namespace AppName
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        Position position;
        private async void GetPosition(object sender, EventArgs e)
        {
            try
            {
                var locator = CrossGeolocator.Current;
                locator.DesiredAccuracy = 50;
                position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
            }
            catch(Exception)
            {
                throw;
            }
            finally { 
                LongitudeLabel.Text = string.Format("{0:0.0000000}", position.Longitude);
                LatitudeLabel.Text = string.Format("{0:0.0000000}", position.Latitude);
            }
        }
    }
}

Can anyone see what I'm doing wrong?

回答1:

Starting with Android Marshmallow, you need to request permissions from the user as-well-as marking it in the manifest. Doing this will show the user a prompt asking to access the resource (location in this case) that they can either allow or deny. You should have code in place handling both situations.

Xamarin provides some documentation on how to do this here.

EDIT: Newer documentation is also available from Microsoft