如果禁用,Android 获取位置或提示启用位置服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3470693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:19:50  来源:igfitidea点击:

Android get location or prompt to enable location service if disabled

androidgeolocationgps

提问by DougW

I've found bits and pieces of this answer scattered through other posts, but I wanted to record it here for others.

我发现这个答案的零碎散布在其他帖子中,但我想在这里记录下来供其他人使用。

How can I simply request the user's GPS and/or Network location and, if they haven't enabled the service, prompt them to do so?

我如何简单地请求用户的 GPS 和/或网络位置,如果他们尚未启用该服务,则提示他们这样做?

回答by DougW

If you want to capture the location on a button push, here's how you'd do it. If the user does not have a location service enabled, this will send them to the settings menu to enable it.

如果您想在按下按钮时捕获位置,请按以下步骤操作。如果用户没有启用定位服务,这会将他们发送到设置菜单以启用它。

First, you must add the permission "android.permission.ACCESS_COARSE_LOCATION" to your manifest. If you need GPS (network location isn't sensitive enough), add the permission "android.permission.ACCESS_FINE_LOCATION" instead, and change the "Criteria.ACCURACY_COARSE" to "Criteria.ACCURACY_FINE"

首先,您必须将权限“android.permission.ACCESS_COARSE_LOCATION”添加到您的清单中。如果您需要 GPS(网络位置不够敏感),请添加权限“android.permission.ACCESS_FINE_LOCATION”,并将“Criteria.ACCURACY_COARSE”更改为“Criteria.ACCURACY_FINE”

Button gpsButton = (Button)this.findViewById(R.id.buttonGPSLocation);
gpsButton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // Start loction service
        LocationManager locationManager = (LocationManager)[OUTERCLASS].this.getSystemService(Context.LOCATION_SERVICE);

        Criteria locationCritera = new Criteria();
        locationCritera.setAccuracy(Criteria.ACCURACY_COARSE);
        locationCritera.setAltitudeRequired(false);
        locationCritera.setBearingRequired(false);
        locationCritera.setCostAllowed(true);
        locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT);

        String providerName = locationManager.getBestProvider(locationCritera, true);

        if (providerName != null && locationManager.isProviderEnabled(providerName)) {
            // Provider is enabled
            locationManager.requestLocationUpdates(providerName, 20000, 100, [OUTERCLASS].this.locationListener);
        } else {
            // Provider not enabled, prompt user to enable it
            Toast.makeText([OUTERCLASS].this, R.string.please_turn_on_gps, Toast.LENGTH_LONG).show();
            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            [OUTERCLASS].this.startActivity(myIntent);
        }
    }
});

My outer class has this listener set up

我的外班设置了这个监听器

private final LocationListener locationListener = new LocationListener() {

    @Override
    public void onLocationChanged(Location location) {
        [OUTERCLASS].this.gpsLocationReceived(location);
    }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}

};

Then, whenever you want to stop listening call this. You should at least make this call during your activity's onStop method.

然后,每当您想停止收听时,请调用此方法。您至少应该在活动的 onStop 方法期间进行此调用。

LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this.locationListener);

回答by Yankee

After going through a lot of answers on Stack Overflow, I found this method to work perfectly fine and doesn't even require a lot of code.
Declare int GPSoff = 0as a global variable.
Now wherever you need to check for the present status of the GPS and re-direct the user to turn the GPS on, use this :

在 Stack Overflow 上查阅了很多答案后,我发现这种方法非常好用,甚至不需要很多代码。
声明int GPSoff = 0为全局变量。
现在,无论您需要检查 GPS 的当前状态并重新引导用户打开 GPS,请使用以下命令:

try {
                GPSoff = Settings.Secure.getInt(getContentResolver(),Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
            }
            if (GPSoff == 0) {
                showMessageOKCancel("You need to turn Location On",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(onGPS);
                            }
                        });
            }

回答by JavierSP1209

To prompt the user to enable location services you should use the new LocationRequest included in google play services, you can found the complete guide in LocationRequest

要提示用户启用位置服务,您应该使用 google play 服务中包含的新 LocationRequest,您可以在LocationRequest 中找到完整指南