gpt4 book ai didi

java - 删除位置管理器不起作用的更新

转载 作者:行者123 更新时间:2023-12-01 09:00:53 26 4
gpt4 key购买 nike

我有一张 map ,我想在上面显示用户的当前位置,并且在获取用户的位置后调用 api 来获取附近的商家。

我正在获取用户的当前位置,所有商家也都通过 map 上的标记来获取位置。

但是我在LocationListener的onLocationChanged()方法中调用了setMap方法。该方法会被连续调用。

我想获取一次位置并显示在标记上,当下次用户访问此 fragment 时,我只想获取更新的位置。

但现在它会连续循环调用 onLocation 方法,因此会调用 accessMerchants。

为了阻止这个问题,我尝试从位置管理器中删除更新,我还尝试设置一个 boolean 变量,如果它第一次进入 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?谢谢..

最佳答案

您注册了 2 个提供商的更新,您是否从这两个提供商处注销了注册?

此外,要使 boolean 标志起作用,您需要进行更改 - 在函数末尾将其设置为 true,并将 if 更改为 if(!receivedLocation) 这将使其生效只运行一次。事实上,它永远不会运行。

关于java - 删除位置管理器不起作用的更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41678531/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com