按钮上的GPS位置按

时间:2014-08-15 07:21:11

标签: java android android-activity gps location

我目前正在编写一个应用程序,只需按一下按钮即可访问当前位置,然后将其打印出来。我现在拥有的是一种获取最后已知位置的方法。我在许多地方已经看到,一个是实现一个获取位置的类。我当前的代码将其作为字符串返回,但它只获取手机上次更新的位置。我怎么能改变这个,这样当我按下按钮并调用一个使用这个String的方法时,它将获得currentLocation而不是lastLocation? 非常感谢! 此外,这是我的第一个Android应用程序,我只有Java和类实现的中级知识。

public String getLocation(){
    String userLocation;

    try {
        LocationManager locMgr = (LocationManager) this.getSystemService(LOCATION_SERVICE);
        Location recentLoc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        String userLocator = recentLoc.toString();
        userLocation = compressString(userLocator);
        //userLocation = recentLoc.toString();

    }
            catch(Exception e) {
        userLocation = "Location failed";
    }

    return userLocation;
}

3 个答案:

答案 0 :(得分:0)

我认为您的GPS现在已关闭。如果您打开设备的位置服务,它将打印出您附近的最后一个位置。如果它不起作用,则必须为您的活动实现LocationListener类。就像this link一样。

答案 1 :(得分:0)

尝试使用此代码:

LocationManager locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener=new LocationListener() {

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

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLocationChanged(Location location) {
        double lat=location.getLatitude();
        double lng=location.getLongitude();

    }
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);//or LocationManager.NETWORK_PROVIDER

}

答案 2 :(得分:0)

在onClick方法中试试这个

private void _getLocation() {
// Get the location manager
LocationManager locationManager = (LocationManager) 
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
LocationListener loc_listener = new LocationListener() {

public void onLocationChanged(Location l) {}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
    };
    locationManager
            .requestLocationUpdates(bestProvider, 0, 0, loc_listener);
    location = locationManager.getLastKnownLocation(bestProvider);
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();
    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;
    }
}