2

我正在寻找一种从 GPS 中获取其经度和纬度变量的方法,该变量来自不在主要活动中的分离类。每当用户更改位置时,我都必须获取这些值。

4

2 回答 2

4

这是访问经度和纬度的单独类。

public class AppLocationManager implements LocationListener {

    private LocationManager locationManager;
    private String latitude;
    private String longitude;
    private Criteria criteria;
    private String provider;

    public AppLocationManager(Context context) {
        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        provider = locationManager.getBestProvider(criteria, true);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1,
                0, this);
        setMostRecentLocation(locationManager.getLastKnownLocation(provider));

    }

    private void setMostRecentLocation(Location lastKnownLocation) {

    }

    public String getLatitude() {
        return latitude;
    }

    public String getLongitude() {
        return longitude;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.location.LocationListener#onLocationChanged(android.location.
     * Location)
     */
    @Override
    public void onLocationChanged(Location location) {
        double lon = (double) (location.getLongitude());/// * 1E6);
        double lat = (double) (location.getLatitude());// * 1E6);

//      int lontitue = (int) lon;
//      int latitute = (int) lat;
        latitude = lat + "";
        longitude = lon + "";

    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.location.LocationListener#onProviderDisabled(java.lang.String)
     */
    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * android.location.LocationListener#onProviderEnabled(java.lang.String)
     */
    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    /*
     * (non-Javadoc)
     * 
     * @see android.location.LocationListener#onStatusChanged(java.lang.String,
     * int, android.os.Bundle)
     */
    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }

}

您从您的 mian Activity 类中调用经度和纬度。

AppLocationManager appLocationManager = new AppLocationManager(YourActivity_name.this);
appLocationManager.getLatitude()
  appLocationManager.getLongitude();

谢谢

于 2012-06-13T21:24:09.067 回答
1

要在 Toast 中显示参数,请使用以下代码。

lat = appLocationManager.getLatitude();
lng = appLocationManager.getLongitude();
Toast.makeText(ct, lat, Toast.LENGTH_LONG).show();
Toast.makeText(ct, lng, Toast.LENGTH_LONG).show();

但问题是 GPS,而不是 NETWORK Provider。不知道为什么这被标记为“最佳答案”

于 2014-04-19T01:49:29.383 回答