Ask user to turn on Location

后端 未结 5 1917
情深已故
情深已故 2020-12-16 21:44

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

5条回答
  •  不知归路
    2020-12-16 22:26

    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.

提交回复
热议问题