在Android上获取当前的GPS位置


问题内容

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

编写了一个实现的简单类 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;
    }

}

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

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作为结果。无法找出问题所在。


问题答案:

您必须在onCreate()返回之后才能触发您的位置更新回调。如果您将经纬度变量初始化为虚拟值,则可能会看到您正在打印这些值。

在onLocationChanged中添加一些日志记录,以便可以看到它已被触发,然后仔细阅读有关回调和更新UI的android应用程序的工作方式。

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