我正在为Android KitKat版本(最低API级别19)开发Android应用程序,我需要在不询问用户的情况下自动打开用户设备的位置访问选项。我已经尝试过这段代码(如下所示),但它会弹出一个对话框并询问用户。因此,请告诉我如何在不询问用户的情况下打开设备的位置访问权限。
代码:
public static void enableDeviceLocation(final Activity activity) {
final GoogleApiClient googleApiClient = new GoogleApiClient.Builder(activity.getApplicationContext()).addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
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) {
Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
//All location settings are satisfied.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
//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(activity, LocationRequest.PRIORITY_HIGH_ACCURACY);
}
catch (IntentSender.SendIntentException e) {
//PendingIntent unable to execute request.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
//Location settings are inadequate, and cannot be fixed here. Dialog not created.
break;
}
googleApiClient.disconnect();
}
});
}
答案 0 :(得分:3)
在标准的无根Android设备上,出于隐私和安全原因,您无法在没有用户参与的情况下自动启用任何位置提供商。