How can I prompt the user to turn on Location?
The app is supposed to filter a list of locations with the current location of the user. If the user has the Location service turned off, the app should prompt the user asking for the Location to be turned on.
For instance Trip Advisor app does this:
( Not sure if I can post other apps screenshots here, but if I shouldn't be doing it, please say so. And apologize for the full sized images, tried to make them smaller, but SO didn't liked it... )
In the first image, you can see I have the Location service turned off. The, after opening the Trip Advisor app, and tapping the Near me now option, I'm prompted with the second image, where I'm asked to Turn on Location services. After I tap the button, a dialog shows up so I can allow, or disallow, the Location service to be turned on. If I tap OK, the Location service is turned on on the device, and the app consumes it.
How can I achieve this?
Found the solution I was asking for.
Requirements
Nuget Xamarin.GooglePlayServices.Location
Code
Int64
interval = 1000 * 60 * 1,
fastestInterval = 1000 * 50;
try {
GoogleApiClient
googleApiClient = new GoogleApiClient.Builder( this )
.AddApi( LocationServices.API )
.Build();
googleApiClient.Connect();
LocationRequest
locationRequest = LocationRequest.Create()
.SetPriority( LocationRequest.PriorityBalancedPowerAccuracy )
.SetInterval( interval )
.SetFastestInterval( fastestInterval );
LocationSettingsRequest.Builder
locationSettingsRequestBuilder = new LocationSettingsRequest.Builder()
.AddLocationRequest( locationRequest );
locationSettingsRequestBuilder.SetAlwaysShow( false );
LocationSettingsResult
locationSettingsResult = await LocationServices.SettingsApi.CheckLocationSettingsAsync(
googleApiClient, locationSettingsRequestBuilder.Build() );
if( locationSettingsResult.Status.StatusCode == LocationSettingsStatusCodes.ResolutionRequired ) {
locationSettingsResult.Status.StartResolutionForResult( this, 0 );
}
} catch( Exception exception ) {
// Log exception
}
With this code, if the locationSettingsResult.Status.StatusCode
is LocationSettingsStatusCodes.ResolutionRequired
( 6
) it means -- probably -- that the Location is turned off, although I've found one situation that it didn't return the value when the device had the option turned off. After turning on and off, it worked, might be a bug on the device, or not.