こんにちは、フラグメントを開始するときに現在の座標を取得する必要があります (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");
}
}
座標を取得するのに約 1 分かかりますが、なぜそんなに時間がかかるのですか? そして、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());