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

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

问题描述

我想通过GPS功能来获取用户当前位置,

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

写了一个简单的类,它实现 LocationListener的

Wrote a simple class that implements 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()
                    + '\n');
            tv.append("Longitude:- " + LocationManagerHelper.getLongitude()
                    + '\n');
    } else {
        tv.setText("GPS is not turned on...");
    }

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

但它总是返回0.0作为result.Couldn't找出问题。

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

推荐答案

您的位置更新回调不能被解雇之前的onCreate()返回之后。如果您初始化您的纬度/长变量来虚值,你可能会看到您打印这些值。

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天全站免登陆