anand
anand

Reputation: 1459

Check location permission is ON in Android device through C# in Xamarin.Forms

I am creating an app and I am trying to get that Location permission is ON or not in device (in Settings) in my Android app. I am using Xamarin.Forms. How I can get this through C# in Xamarin?

Upvotes: 1

Views: 1932

Answers (2)

wishmaster
wishmaster

Reputation: 1303

Use the permission plugin from James montemagno. Available here

Particularly the below snippet will help you:

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(new [] {
   Permission.Location
  });
  status = results[Permission.Location];
 }
 if (status == PermissionStatus.Granted) {
  var results = await CrossGeolocator.Current.GetPositionAsync(10000);
  LabelGeolocation.Text = "Lat: " + results.Latitude + " Long: " + results.Longitude;
 } else if (status != PermissionStatus.Unknown) {
  await DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
 }
} catch (Exception ex) {
 LabelGeolocation.Text = "Error: " + ex;
}

Upvotes: 1

Jason
Jason

Reputation: 89204

use the GeoLocator plugin and check the IsGeoLocationEnabled property

var locator = CrossGeolocator.Current;

if (locator.IsGeoLocationEnabled) {
  ...
}

Upvotes: 1

Related Questions