Google地图获取当前位置并启用gps时出错

问题描述 投票:0回答:1

我尝试通过单击按钮来获取当前位置。我有一种方法可以获取用户的当前位置,如果gps被禁用,请要求用户启用它。我的问题是,如果用户第一次拒绝此请求并接受它在第二次尝试中,它将循环播放并且永不停止(callBackLocation),并通过每个循环将相机移动到当前位置,并在重复中显示相关的Toast Massege(“此处有一个循环”)。但是如果用户接受启用gps第一次很好用。

public class FragmentLocation extends Fragment implements OnMapReadyCallback, ShopDialog.OnDialogClickListener {
  private View rootView;
  private MapView mapView;
  private static final float DEFAULT_ZOOM = 15f;
  private static final String MAPVIEW_BUNDLE_KEY = "MapViewBundleKey";
  private static GoogleMap map;    
  ExtendedFloatingActionButton btn_gps;
  private static final int GPS_ENABLE_REQUEST_CODE = 555;
  LocationCallback locationCallback;
  Location deviceLocation;
  LocationRequest locationRequest;

  private FusedLocationProviderClient fusedLocationProviderClient;


  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_location, container, false);
    mapView = (MapView) rootView.findViewById(R.id.mapView);
    initGoogleMap(savedInstanceState);

    btn_gps = rootView.findViewById(R.id.btn_gps);      


    return rootView;
  }    

  @Override
  public void onMapReady(GoogleMap googleMap) {
    map = googleMap;
    map.setMyLocationEnabled(true);
    map.getUiSettings().setMyLocationButtonEnabled(false);
    btn_gps.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        getDeviceLocation();
      }
    });

  }

  ///get device location by code..
  //گرفتن لوکیشن دستگاه با کد
  private void getDeviceLocation() {
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
    try {
      Task myLocation = fusedLocationProviderClient.getLastLocation();
      myLocation.addOnCompleteListener(new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
          if (task.isSuccessful()) {
            Toast.makeText(getActivity(), " task.isSuccessful() ", Toast.LENGTH_SHORT).show();
            deviceLocation = (Location) task.getResult();
            //if deviceLocatrion is null then we will send a request to user to turn on the GPS
            //if deviceLocation is not null we will get user location
            if (deviceLocation != null) {
              Toast.makeText(getActivity(), "deviceLocation != null ", Toast.LENGTH_SHORT).show();
              moveCamera(new LatLng(deviceLocation.getLatitude(), deviceLocation.getLongitude()), DEFAULT_ZOOM);

            } else {
              Toast.makeText(getActivity(), " deviceLocation == null ", Toast.LENGTH_SHORT).show();
              isGPSon();
              locationCallback = new LocationCallback() {
                @Override
                public void onLocationResult(LocationResult locationResult) {
                  super.onLocationResult(locationResult);

                  if (locationResult == null) {
                    Toast.makeText(getActivity(), " return ", Toast.LENGTH_SHORT).show();

                    return;
                  } else {
                    Toast.makeText(getActivity(), " THERE IS A LOOP HERE ", Toast.LENGTH_SHORT).show();
                    deviceLocation = locationResult.getLastLocation();
                    moveCamera(new LatLng(deviceLocation.getLatitude(), deviceLocation.getLongitude()), DEFAULT_ZOOM);
                    fusedLocationProviderClient.removeLocationUpdates(locationCallback);


                  }
                }
              };

              fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, null);
            }
          } else {
            Toast.makeText(getActivity(), "device location | unable to get current location", Toast.LENGTH_SHORT).show();
          }
        }
      });
    } catch (SecurityException e) {
      Log.e("TAG", "Get Devise Location : SecurityException" + e.getMessage());
    }
  }

  //move camera method
  private void moveCamera(LatLng latLng, float zoom) {
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
  }

  //Check if the device gps is enabled or not ,if not ask user to enable it...
  //////////بررسی فعال بودن جی پی اس دستگاه و درخواست روشن کردن ان به یوزر
  private void isGPSon() {
    //درخواست گرفتن لوکیشن یوزر
    locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.addLocationRequest(locationRequest);

    SettingsClient settingsClient = LocationServices.getSettingsClient(getActivity());
    //این خط چک میکنه که جی پی اس روشنه یا نه و نتیجه در تسک ذخیره میشه
    Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());
    task.addOnSuccessListener(getActivity(), new OnSuccessListener<LocationSettingsResponse>() {
      @Override
      public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
        Toast.makeText(getActivity(), "onSuccess/; OONN", Toast.LENGTH_SHORT).show();

      }
    });
    //اگر غیرفعال بود در این قسمت درخواست فعال کردن انرا به یوزر میدهیم
    //برای اینکه بفهمیم یوزر چه پاسخی به این درخواست میدهد متد onActivityresult رو در اکتیویتی فراخوانی میکنیم
    task.addOnFailureListener(getActivity(), new OnFailureListener() {
      @Override
      public void onFailure(@NonNull Exception e) {
        if (e instanceof ResolvableApiException) {
          ResolvableApiException resolvableApiException = (ResolvableApiException) e;
          try {
            Toast.makeText(getActivity(), "GPS ooofff", Toast.LENGTH_SHORT).show();
            resolvableApiException.startResolutionForResult(getActivity(), GPS_ENABLE_REQUEST_CODE);
          } catch (IntentSender.SendIntentException ex) {
            ex.printStackTrace();
          }
        }

      }
    });
  }

  private void initGoogleMap(Bundle savedInstanceState) {
    // *** IMPORTANT ***
    // MapView requires that the Bundle you pass contain _ONLY_ MapView SDK
    // objects or sub-Bundles.
    Bundle mapViewBundle = null;
    if (savedInstanceState != null) {
      mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY);
    }
    mapView.onCreate(mapViewBundle);

    mapView.getMapAsync(this);
  }

  @Override
  public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY);
    if (mapViewBundle == null) {
      mapViewBundle = new Bundle();
      outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle);
    }

    mapView.onSaveInstanceState(mapViewBundle);
  }


  @Override
  public void onPause() {
    mapView.onPause();
    super.onPause();
  }

  @Override
  public void onDestroy() {
    mapView.onDestroy();
    super.onDestroy();
  }

  @Override
  public void onLowMemory() {
    super.onLowMemory();
    mapView.onLowMemory();
  }

  @Override
  public void onResume() {
    super.onResume();
    mapView.onResume();
  }

  @Override
  public void onStart() {
    super.onStart();
    mapView.onStart();
  }

  @Override
  public void onStop() {
    super.onStop();
    mapView.onStop();
  }


}

与此错误相关的两个方法是getCurrentLocation()和isGpsOn()

android dictionary gps location
1个回答
0
投票

[我尝试了许多方法后发现,如果我通过“ this”而不是“ locationCallback”

来自:

deviceLocation = locationResult.getLastLocation();
                    moveCamera(new LatLng(deviceLocation.getLatitude(), deviceLocation.getLongitude()), DEFAULT_ZOOM);
                    fusedLocationProviderClient.removeLocationUpdates(locationCallback);

至:

deviceLocation = locationResult.getLastLocation();
                        moveCamera(new LatLng(deviceLocation.getLatitude(), deviceLocation.getLongitude()), DEFAULT_ZOOM);
                        fusedLocationProviderClient.removeLocationUpdates(this);

这将是正确的...我不知道为什么,但是它能正常工作

热门问题
推荐问题
最新问题