我可以通過從片段中使用LocationListener和LocationManager
獲取用戶位置嗎?或者,我是否需要在底層活動中使用LocationListener
,並使用接口(或其他某種方法)將數據傳輸回片段?由於更改應用UI,我正在將活動轉換爲片段。當我使用獨立活動時,獲取位置並不是問題,但是,現在我無法獲取任何返回的位置,因爲我已將該活動製作爲片段。在片段中使用LocationListener
以下是我如何添加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;
}
您可以使用片段內的LocationManager&LocationListener。可能需要更多的代碼才能找出爲什麼你沒有得到一個位置。 – paul 2013-02-26 21:12:08
首先發布您的locationListener的代碼。 – paul 2013-02-26 21:20:16