Java 按按钮时的GPS定位
我目前正在编写一个应用程序,它将访问一个按钮的当前位置,并打印出来。我现在有一个方法,可以得到最后一个已知的位置。我在很多地方都看到,一个是实现一个获取位置的类。我当前的代码以字符串形式返回,但它只获取手机上次更新的位置。我怎样才能更改它,当我按下按钮并调用使用此字符串的方法时,它将获得currentLocation而不是lastLocation? 非常感谢你! 此外,这是我有史以来第一个android应用程序,我只有Java和类实现的中级知识Java 按按钮时的GPS定位,java,android,android-activity,gps,location,Java,Android,Android Activity,Gps,Location,我目前正在编写一个应用程序,它将访问一个按钮的当前位置,并打印出来。我现在有一个方法,可以得到最后一个已知的位置。我在很多地方都看到,一个是实现一个获取位置的类。我当前的代码以字符串形式返回,但它只获取手机上次更新的位置。我怎样才能更改它,当我按下按钮并调用使用此字符串的方法时,它将获得currentLocation而不是lastLocation? 非常感谢你! 此外,这是我有史以来第一个android应用程序,我只有Java和类实现的中级知识 public String getLocation
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;
}
我想你的GPS现在已经关机了。如果您打开设备的位置服务,它将打印出离您最近的位置。如果它不起作用,则必须对活动实现LocationListener类。类似于。尝试使用以下代码:
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
}尝试一下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;
}
}