사용자의 현재 위치를 표시하려는지도가 있으며 인근 상점에 도착하기 위해 사용자의 위치를 얻은 후 API를 호출하고 있습니다.위치 관리자 업데이트가 작동하지 않습니다.
나는 사용자의 현재 위치를 얻고 있으며, 모든 상인은지도의 마커로 음모를 꾸미고 있습니다.
하지만 LocationListener의 onLocationChanged() 메서드에서 setMap 메서드를 호출했습니다. 이 메소드는 계속 호출됩니다.
다음 번에 사용자가이 조각을 가져 오면 업데이트 된 위치를 가져오고 싶을 때 위치를 한 번 가져와 마커에 표시하고 싶습니다.
하지만 이제 루프에서 계속 onLocation 메서드가 호출되어 accessMerchants가 호출됩니다.
위치 관리자에서 업데이트를 제거하려고했는데, 처음으로 onLocationChanged() 메소드가 실행되면 부울 변수를 설정하려고 시도했지만 false가되지만 다시 루프에 들어갑니다.
업데이트 제거 또한 작동하지 않습니다. 업데이트 제거가 작동하면 onLocationChanged 메소드가 다시 호출되지 않아야합니다.
public class SearchMerchantFragment extends Fragment implements GetSearchedMerchantsAsyncTask.GetSearchedMerchantsCallBack, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search_merchant, container, false);
setUpUI(view);
return view;
}
public void setUpUI(View view) {
initializeLocationManager();
requestLocation();
setUpMapIfNeeded();
mLocationsList = new ArrayList<>();
markers = new ArrayList<>();
edtSearch = (EditText) view.findViewById(R.id.edtSearch);
rv_fetch_merchants = (RecyclerView) view.findViewById(R.id.rv_fetch_merchants);
merchantsList = new ArrayList<Merchants>();
merchantsAdapter = new SearchedMerchantsAdapter(this.getContext(), merchantsList);
rv_fetch_merchants.setLayoutManager(new LinearLayoutManager(getActivity()));
rv_fetch_merchants.setAdapter(merchantsAdapter);
rv_fetch_merchants.setHasFixedSize(true);
rv_fetch_merchants.setItemViewCacheSize(30);
rv_fetch_merchants.setDrawingCacheEnabled(true);
rv_fetch_merchants.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
}
//get searched merchants
public void accessMerchants() {
if (CommonUtils.isConnectedToInternet(getContext())) {
new GetSearchedMerchantsAsyncTask(getActivity(), SearchMerchantFragment.this).execute(access_token, sessionUserId, String.valueOf(mLastLocation.getLatitude()), String.valueOf(mLastLocation.getLongitude()));
} else {
showAlert(String.valueOf(R.string.check_network));
}
}
@Override
public void doPostExecute(ArrayList<Merchants> merchantsArrayList) {
merchantsList.clear();
merchantsList.addAll(merchantsArrayList);
merchantsAdapter.notifyDataSetChanged();
for (Merchants merchants : merchantsList) {
LatLng latLng = new LatLng(merchants.getLatitude(), merchants.getLongitude());
MarkerOptions marker = new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).title(merchants.getKirana_name());
Marker m = mGoogleMap.addMarker(marker);
markers.add(m);
}
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
// getLocation();
}
}
//setup map
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
buildGoogleApiClient();
mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
// Toast.makeText(getActivity(),"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onConnected(Bundle bundle) {
// Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionSuspended(int i) {
// Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
private void removeMarkers() {
if (mGoogleMap != null) {
for (Marker marker : markers) {
marker.remove();
}
mGoogleMap.clear();
markers.clear();
}
}
@Override
public void onDetach() {
super.onDetach();
mapConnected = false;
}
return true;
}
public void setMap() {
try {
int locationPermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
int coarseLocation = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_COARSE_LOCATION);
if(locationPermission == PackageManager.PERMISSION_GRANTED && coarseLocation == PackageManager.PERMISSION_GRANTED && GPSTracker.isGPSEnabled) {
if(receivedLocation) {
receivedLocation = false;
mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
accessMerchants();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mLatLang);
markerOptions.title(getString(R.string.position));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mMarker = mGoogleMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(mLatLang).zoom(14).build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
// mLocationRequest = new LocationRequest();
// mLocationRequest.setInterval(5000); //5 seconds
// mLocationRequest.setFastestInterval(3000); //3 seconds
// mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
LocationListener locationListener = new LocationListener();
mLocationManager.removeUpdates(locationListener);
}
}
else {
showAlert(getString(R.string.locationAlert));
}
} catch (SecurityException e) {
}
}
private void initializeLocationManager() {
// Log.e(Application.TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
}
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
showAlert(getString(R.string.locationAlert));
}
}
public class LocationListener implements android.location.LocationListener {
public LocationListener() {
}
public LocationListener(String provider) {
Log.e(Application.TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
@Override
public void onLocationChanged(Location location) {
Log.e(Application.TAG, "onLocationChanged: " + location);
receivedLocation = true;
mLastLocation.set(location);
if (receivedLocation) {
setMap();
}
}
@Override
public void onProviderDisabled(String provider) {
Log.e(Application.TAG, "onProviderDisabled: " + provider);
}
@Override
public void onProviderEnabled(String provider) {
Log.e(Application.TAG, "onProviderEnabled: " + provider);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(Application.TAG, "onStatusChanged: " + provider);
}
}
public void requestLocation() {
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(Application.TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(Application.TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(Application.TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(Application.TAG, "gps provider does not exist " + ex.getMessage());
}
}
}
무슨 일입니까? 제발 도와주세요. 어디에서 removeUpdates를 호출해야합니까 ?? 고맙습니다 ...
두 공급자 모두의 등록 취소 방법은 무엇입니까? – Sid
removeUpdates를 각 공급자마다 한 번씩 두 번 호출하십시오. 또한 코드를 살펴보고 내가 어떻게 작동하는지 이해하고 시도해보십시오. 분명히 붙여 넣기 한 혼합 기술로 인해 잘 작동하지 않을 수 있습니다. –
고맙습니다. – Sid