无法在 firebase 数据库中上传 GeoFire 位置

问题描述

我只想使用 GeoFire 将我的位置上传到 firebase 数据库中。

    DatabaseReference onlineRef,CurrentUserRef,DriverLocationRef;
    GeoFire geoFire;
    ValueEventListener onlineValueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists())
                CurrentUserRef.ondisconnect().removeValue();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Toast.makeText(HomeActivity.this,error.getMessage(),Toast.LENGTH_SHORT).show();

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        onlineRef = FirebaseDatabase.getInstance().getReference().child(".info/connected");
        DriverLocationRef = FirebaseDatabase.getInstance().getReference(Common.Drivers_Location_Reference);
        CurrentUserRef = FirebaseDatabase.getInstance().getReference(Common.Drivers_Location_Reference).child(FirebaseAuth.getInstance().getCurrentUser().getUid());
        geoFire = new GeoFire(DriverLocationRef);
        registerOnlinesystem();
        getDeviceLocation();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerOnlinesystem();
    }

    private void registerOnlinesystem() {
        onlineRef.addValueEventListener(onlineValueEventListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        geoFire.removeLocation(FirebaseAuth.getInstance().getCurrentUser().getUid());
        mFusedLocationProviderClient.removeLocationUpdates(locationCallback);
        onlineRef.removeEventListener(onlineValueEventListener);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);

        // Get the location at the center of the map each time the camera moves
        mMap.setonCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
            @Override
            public void onCameraIdle() {
                latLng = mMap.getCameraPosition().target;
            }
        });

        //reposition default GPS button on map
        if (mapView != null && mapView.findViewById(Integer.parseInt("1")) != null) {
            View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
            layoutParams.width = 100;
            layoutParams.height = 100;
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP,0);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BottOM,RelativeLayout.TRUE);
            layoutParams.setMargins(0,40,40);
        }

        //check if GPS is enabled or not and then request user to enable it.
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setInterval(10000);
        locationRequest.setFastestInterval(5000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        //Handles location settings turned on/off
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);

        SettingsClient settingsClient = LocationServices.getSettingsClient(HomeActivity.this);
        Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());

        task.addOnSuccessListener(HomeActivity.this,locationSettingsResponse -> getDeviceLocation());

        task.addOnFailureListener(HomeActivity.this,new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                if (e instanceof ResolvableApiException) {
                    ResolvableApiException resolvable = (ResolvableApiException) e;
                    try {
                        resolvable.startResolutionForResult(HomeActivity.this,51);
                    } catch (IntentSender.SendIntentException ex) {
                        ex.printstacktrace();
                    }
                }
            }
        });
    }
    private void getDeviceLocation() {
        mFusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if (task.isSuccessful()) {
                    mLastKNownLocation = task.getResult();
                    if (mLastKNownLocation != null) {
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKNownLocation.getLatitude(),mLastKNownLocation.getLongitude()),DEFAULT_ZOOM));
                    } else {
                        locationRequest = new LocationRequest();
                        locationRequest.setInterval(10000);
                        locationRequest.setFastestInterval(5000);
                        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                        locationCallback = new LocationCallback() {
                            @Override
                            public void onLocationResult(LocationResult locationResult) {
                                super.onLocationResult(locationResult);
                                LatLng newPosition = new LatLng(locationResult.getLastLocation().getLatitude(),locationResult.getLastLocation().getLongitude());
                                mLastKNownLocation = locationResult.getLastLocation();
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newPosition,DEFAULT_ZOOM));
                                //mFusedLocationProviderClient.removeLocationUpdates(locationCallback);

                                geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(),new GeoLocation(locationResult.getLastLocation().getLatitude(),locationResult.getLastLocation().getLongitude()),(key,error) -> {
                                            if (error != null){
                                                Toast.makeText(HomeActivity.this,Toast.LENGTH_SHORT).show();
                                            }
                                            else {
                                                Toast.makeText(HomeActivity.this,"You are online",Toast.LENGTH_SHORT).show();
                                            }
                                        });
                            }
                        };
                        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(HomeActivity.this);
                        mFusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback,Looper.myLooper());
                    }
                } else {
                    Toast.makeText(HomeActivity.this,"Unable to get location",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

但 firebase 数据库中没有显示任何内容

firebase 数据库规则:

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    ".read": "auth!=null",".write": "auth!=null"
  }
}

地图显示正常,但是当我打开活动时,我的当前位置没有上传。我想在打开活动时上传我的当前位置。当活动被销毁时,当前用户数据库中的位置将被删除。>

解决方法

我解决了这个问题。当 if 条件中 lastKnownLocation 不等于 null 时,我们必须在 geofire 中设置位置。

private void getDeviceLocation() {
        mFusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if (task.isSuccessful()) {
                    mLastKnownLocation = task.getResult();
                    if (mLastKnownLocation != null) {
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLastKnownLocation.getLatitude(),mLastKnownLocation.getLongitude()),DEFAULT_ZOOM));
                        geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(),new GeoLocation(mLastKnownLocation.getLatitude(),(key,error) -> {
                                    if (error != null){
                                        Toast.makeText(HomeActivity.this,error.getMessage(),Toast.LENGTH_SHORT).show();
                                    }
                                    else {
                                        Toast.makeText(HomeActivity.this,"You are online",Toast.LENGTH_SHORT).show();
                                    }
                                });
                    } else {
                        locationRequest = new LocationRequest();
                        locationRequest.setInterval(10000);
                        locationRequest.setFastestInterval(5000);
                        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                        locationCallback = new LocationCallback() {
                            @Override
                            public void onLocationResult(LocationResult locationResult) {
                                super.onLocationResult(locationResult);
                                LatLng newPosition = new LatLng(locationResult.getLastLocation().getLatitude(),locationResult.getLastLocation().getLongitude());
                                mLastKnownLocation = locationResult.getLastLocation();
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newPosition,DEFAULT_ZOOM));
                                //mFusedLocationProviderClient.removeLocationUpdates(locationCallback);

                                geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(),new GeoLocation(locationResult.getLastLocation().getLatitude(),locationResult.getLastLocation().getLongitude()),error) -> {
                                            if (error != null){
                                                Toast.makeText(HomeActivity.this,Toast.LENGTH_SHORT).show();
                                            }
                                            else {
                                                Toast.makeText(HomeActivity.this,Toast.LENGTH_SHORT).show();
                                            }
                                        });
                            }
                        };
                        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(HomeActivity.this);
                        mFusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback,Looper.myLooper());
                    }
                } else {
                    Toast.makeText(HomeActivity.this,"Unable to get location",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }