使用对话框禁用GPS(Android)

时间:2019-07-14 22:24:30

标签: android gps android-gps

诸如Google Maps显示对话框之类的应用程序可启用GPS。

是否可以制作一个显示此类对话框以禁用GPS的应用程序?

1 个答案:

答案 0 :(得分:0)

您不应该直接尝试启用/禁用gps,相反,official docs建议您的应用指定所需的准确性/功耗水平和所需的更新间隔,然后设备会自动对系统设置。

我将在此处添加official docs中的代码以供立即参考

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
// ...
SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
    @Override
    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
        // All location settings are satisfied. The client can initialize
        // location requests here.
        // ...
    }
});

task.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        if (e instanceof ResolvableApiException) {
            // Location settings are not satisfied, but this can be fixed
            // by showing the user a dialog.
            try {
                // Show the dialog by calling startResolutionForResult(),
                // and check the result in onActivityResult().
                ResolvableApiException resolvable = (ResolvableApiException) e;
                resolvable.startResolutionForResult(MainActivity.this,
                        REQUEST_CHECK_SETTINGS);
            } catch (IntentSender.SendIntentException sendEx) {
                // Ignore the error.
            }
        }
    }
});