我正在尝试获取用户位置,但似乎没有调用LocationListener列表器类的onLocationChanged()。
我已在下面发布了我的代码,我们将非常感谢您的帮助。
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
checkForNetwork();
setLocationProvider();
检查哪个位置提供商可用的代码。
private void checkForNetwork() {
try {
fromGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception e){
Toast.makeText(getActivity(), "GPS not available, trying to get location from network", Toast.LENGTH_SHORT).show();
}
try {
fromNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception e) {
Toast.makeText(getActivity(), "Network not available", Toast.LENGTH_SHORT).show();
}
}
请求位置更新的代码:
private void setLocationProvider() {
if (fromGPS){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, locationListener);
net.setText("Location from GPS");
} else if (fromNetwork){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, locationListener);
net.setText("Location from network");
} else {
net.setText("No location provider is enabled");
}
}
LocationListener类:
private class myLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
Toast.makeText(getActivity(), "Location changed", Toast.LENGTH_SHORT).show();
if (location != null){
} else {
lat.setText("Location is null");
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}