我有一張地圖,我想在其上顯示用戶的當前位置,並在獲取用戶位置以獲取附近商家後調用api。刪除位置管理器不工作的更新
我得到用戶的當前位置,並且所有商家都通過地圖上的標記獲取圖形。
但我在LocationListener的onLocationChanged()方法中調用了setMap方法。這個方法被連續調用。
我想獲取位置一次並在標記上顯示,當下一次用戶來到這個片段時,再次只有我想獲得更新的位置。
但是現在它會持續進行一次循環,onLocation方法被調用,所以accessMerchants被調用。
爲了解決這個問題,我試圖從位置管理器中刪除更新,如果它第一次進入onLocationChanged()方法,我試圖設置一個布爾變量,它將是假的,但它也是在循環中。
刪除更新也無法正常工作,如果刪除更新工作,然後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