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

发布于 2024-09-14 02:39:27 字数 101 浏览 5 评论 0原文

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

笨死的猪 2024-09-21 02:39:27

如果您想通过按下按钮来捕获位置,请按以下方法操作。如果用户没有启用位置服务,这会将他们发送到设置菜单以启用它。

首先,您必须将权限“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);
        }
    }
});

我的外部类设置了此侦听器

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) {}

};

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

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

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"

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.

LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this.locationListener);
冰雪之触 2024-09-21 02:39:27

在查阅了 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);
                            }
                        });
            }

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 = 0 as 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 :

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);
                            }
                        });
            }
旧街凉风 2024-09-21 02:39:27

要提示用户启用位置服务,您应该使用 google play 服务中包含的新 LocationRequest,您可以在 位置请求

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文