在不导航到设置页面的情况下打开位置服务 [英] Turn on location services without navigating to settings page
问题描述
与提示用户进入设置页面并启用位置服务并再次返回的传统方法相反,我注意到在一些最新的应用程序中,执行相同操作的更简单方法.
Against the traditional approach of prompting user to go to the settings page and enable location services and come back again, I have noticed a simpler way of doing the same in some of the latest apps.
请参阅下面的屏幕截图,它会提示用户一个对话框,只需单击一下即可启用位置服务,并且可以在这些应用中使用.
Referring to below screenshot, it prompts a dialog to user to enable the location services with just one click and it works in those apps.
我怎么能达到同样的目的?
How can I achieve the same?
推荐答案
This dialog is created by LocationSettingsRequest.Builder available in the Google Play Services.
您需要向应用程序build.gradle
添加依赖项:
You need to add a dependency to your app build.gradle
:
compile 'com.google.android.gms:play-services-location:10.0.1'
然后您可以使用以下最小示例:
Then you can use this minimal example:
private void displayLocationSettingsRequest(Context context) {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(10000 / 2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(TAG, "All location settings are satisfied.");
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
break;
}
}
});
}
You can find the complete example here.
这篇关于在不导航到设置页面的情况下打开位置服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!