从单独的类 - Android获取GPS经度和纬度

时间:2012-06-13 21:16:13

标签: android gps latitude-longitude

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

2 个答案:

答案 0 :(得分:3)

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

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活动类调用经度和纬度。

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

由于

答案 1 :(得分: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。不知道为什么这被标记为“最佳答案”