在 Android 上获取当前 GPS 位置 [英] Getting the current GPS location on Android

查看:28
本文介绍了在 Android 上获取当前 GPS 位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 GPS 功能获取用户的当前位置,

I'm trying to get the user's current location via GPS capability,

写了一个实现LocationListener

public class LocationManagerHelper implements LocationListener {

    private static double latitude;
    private static double longitude;

    @Override
    public void onLocationChanged(Location loc) {
        latitude = loc.getLatitude();
        longitude = loc.getLongitude();
    }

    @Override
    public void onProviderDisabled(String provider) { }

    @Override
    public void onProviderEnabled(String provider) { }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    public static double getLatitude() {
        return latitude;
    }

    public static double getLongitude() {
        return longitude;
    }

}

通过一个简单的操作,我正在访问这些经度和纬度值

and from a simple Action I'm accessing these longitude and latitude values

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /** create a TextView and write Hello World! */
    TextView tv = new TextView(this);

    LocationManager mlocManager = 
                    (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    LocationListener mlocListener = new LocationManagerHelper();

    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            mlocListener);

    if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            tv.append("Latitude:- " + LocationManagerHelper.getLatitude()
                    + '
');
            tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
                    + '
');
    } else {
        tv.setText("GPS is not turned on...");
    }

    /** set the content view to the TextView */
    setContentView(tv);

但它总是返回 0.0 作为结果.无法找出问题所在.

But it always returns 0.0 as the result.Couldn't figure out the problem.

推荐答案

直到 onCreate() 返回后才能触发位置更新回调.如果您将 lat/long 变量初始化为虚拟值,您可能会看到您正在打印这些值.

Your location update callbacks can't be fired until after onCreate() returns. If you initialize your lat/long variables to dummy values you will probably see you are printing those values.

在您的 onLocationChanged 中添加一些日志记录,以便您可以看到它正在被触发,然后阅读一些关于 android 应用程序如何在回调和更新 UI 方面的工作.

Put some logging in your onLocationChanged so that you can see it's being fired, then read up a bit on how android applications work with regard to callbacks and updating the UI.

还要确保您的应用在其清单中具有适当的权限.

Also make sure your application has appropriate permissions in its manifest.

这篇关于在 Android 上获取当前 GPS 位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆