我可以使用 LocationListenerLocationManager
从片段中获取用户位置吗?或者我是否需要LocationListener
在底层活动中使用 from 并使用接口(或其他方法)将数据传输回片段?由于更改应用程序 UI,我正在将活动转换为片段。当我使用独立活动时,获取位置没有问题,但是,现在我已经将活动变成了一个片段,我无法返回任何位置。
下面是我如何添加 LocationListener。它在前面声明为 LocationListener locationListener。
private void addLocationListener(){
locationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location) {
GeoPoint userLoc = processNewLocation(location);
if(userLoc != null){
Log.d("USERLOC", userLoc.toString());
//do something with the location
}
}
@Override
public void onProviderDisabled(String provider) {
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
@Override
public void onProviderEnabled(String provider) {
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
}
注意:processNewLocation 只是将位置转换为 GeoPoint。它甚至没有走那么远,因为没有获得任何位置。
这是向位置管理器注册侦听器的代码
public void addLocationManager(){
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
}
private void getLocationFromNetwork(){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, locationListener);
Log.d("GET NETWORK", "Listener registered");
}
private void getLocationFromGPS(){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME, LOCATION_REFRESH_DISTANCE, locationListener);
Log.d("GET GPS", "Listener registered");
}
private Location getLastLocation(){
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
return lastKnownLocation;
}