您好,当我开始片段时(在 onResume() 中),我需要获取当前坐标。我接下来尝试:
public class FragmentNear extends Fragment implements LocationListener{
View v;
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView tvLess1;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_near, null);
tvLess1=(TextView)v.findViewById(R.id.tv_less_1);
return v;
}
@Override
public void onResume() {
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
super.onResume();
}
@Override
public void onLocationChanged(Location location) {
Log.d("myLogs", "onChangeLocation");
//tvLess1.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
//Log.d("myLogs","Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
Log.d("myLogs","disable");
}
@Override
public void onProviderEnabled(String provider) {
Log.d("myLogs","enable");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("myLogs","status");
}
}
它为我获取坐标大约一分钟,为什么要花这么多时间?然后 onChangeLocation 一直在调用,但我只想在 onResume 调用时更新坐标?我该怎么做?
解决方案是使用下一个:
LocationManager service = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());