Я хочу показывать местоположение пользователя на карте при каждом нажатии кнопки переключения.Я написал код, как показано ниже, и он работает только для отображения карты, но не для местоположения пользователя, и иногда выдает ошибку вроде:
java.lang.IllegalStateException: GoogleApiClient is not connected yet.
в этой строке: LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, this);
Яможет получить местоположение в logcat, но не может показать на карте.Вот фрагмент кода:
public class HomeFragment extends BaseFragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private static final String TAG = HomeFragment.class.getSimpleName();
private Toolbar toolbar;
private TextView driverStatusTV;
public static MaterialAnimatedSwitch statusSwitch;
public static GoogleApiClient apiClient;
public static Location mLastLocation;
public static LocationRequest locationRequest;
public GoogleMap mGmap;
public static Marker currentMarker;
public static double latitude = 0f, longitude = 0f;
public static final int UPDATE_INTERVAL = 15000;
public static final int FASTEST_INTERVAL = 8000;
public static final int DISPLACEMENT = 10;
public static final int PLAY_SERVICES_REQ_CODE = 9009;
public static final int PLAY_SERVICES_RESOLUTION_REQ_CODE = 9090;
private SupportMapFragment mapFragment;
public HomeFragment() {
// Required empty public constructor
}
private void initViews(View view) {
toolbar = view.findViewById(R.id.toolbar);
driverStatusTV = view.findViewById(R.id.driverStatusTV);
statusSwitch = view.findViewById(R.id.statusSwitch);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
initViews(view);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
setUpLocation();
statusSwitch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(boolean b) {
if (b){
Snackbar.make(getActivity().findViewById(android.R.id.content), "You are Now Online", Snackbar.LENGTH_LONG).show();
startLocationListener();
displayLocation();
driverStatusTV.setText("ONLINE");
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "You are Now Offline", Snackbar.LENGTH_LONG).show();
stopLocationListener();
driverStatusTV.setText("OFFLINE");
//currentMarker.remove();
}
}
});
return view;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case AppConstants.LOC_PERM_CODE:
for (int gr : grantResults) {
if (gr == PackageManager.PERMISSION_GRANTED) {
if (checkPlayServices()) {
makeLocationRequest();
initAPIClient();
if (statusSwitch.isChecked()) {
displayLocation();
}
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Google Play Services Not Supported on Your Device", Snackbar.LENGTH_LONG).show();
}
} else {
getActivity().finish();
getActivity().moveTaskToBack(true);
}
}
break;
}
}
public void startLocationListener() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, AppConstants.LOC_PERM_CODE);
} else {
initAPIClient();
apiClient.connect();
LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, this);
}
}
public void setUpLocation() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
if (checkPlayServices()) {
if (statusSwitch.isChecked()) {
initAPIClient();
makeLocationRequest();
displayLocation();
}
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Google Play Services Not Supported on Your Device", Snackbar.LENGTH_LONG).show();
}
}
}
private void makeLocationRequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setSmallestDisplacement(DISPLACEMENT);
}
public boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(), AppConstants.PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Play Services NOT Supported on Your Device", Snackbar.LENGTH_LONG).show();
getActivity().finish();
getActivity().moveTaskToBack(true);
}
return false;
}
return true;
}
private void initAPIClient() {
apiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage(getActivity(), 0, this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
apiClient.connect();
}
public void stopLocationListener() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
LocationServices.FusedLocationApi.removeLocationUpdates(apiClient, this);
}
}
public void displayLocation() {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, AppConstants.LOC_PERM_CODE);
} else {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(apiClient);
if (mLastLocation != null) {
if (statusSwitch.isChecked()) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Log.d(TAG, "Locn:\t" + "lat:\t" + latitude + "and long:\t" + longitude);
geoFire.setLocation("saj9oPN15VZODBbB87JXU26Rqa53", new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
@Override
public void onComplete(String key, DatabaseError error) {
if (currentMarker != null) {
currentMarker.remove();
currentMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.car));
currentMarker = mGmap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)));
LatLng latLng = new LatLng(latitude, longitude);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17f);
mGmap.animateCamera(cameraUpdate);
//draw rotate marker animation
//rotateMarker(currentMarker, -360, mGmap);
}
}
});
}
}
}
}
private void rotateMarker(final Marker currentMarker, final float i, GoogleMap mGmap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = currentMarker.getRotation();
final int duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.postDelayed(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.elapsedRealtime() - start;
float t = interpolator.getInterpolation(elapsed / duration);
float rot = t * i + (1 - t) * startRotation;
currentMarker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
handler.postDelayed(this, 16);
}
}
}, duration);
}
@Override
public void onConnected(@Nullable Bundle bundle) {
startLocationListener();
displayLocation();
}
@Override
public void onConnectionSuspended(int i) {
apiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
if (apiClient != null) {
apiClient = null;
initAPIClient();
}
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
displayLocation();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mGmap = googleMap;
}
}
Может кто-нибудь помочь мне понять, почему он не работает.