繁体   English   中英

在 Firebase 中更新用户位置而不生成新的唯一 ID

[英]Updating user location without generating new unique ID in Firebase

在此处输入图像描述

这是我的 Firebase 中的实时数据库在不使用唯一 ID 的情况下将用户当前位置发送给它时的样子。

但是,在代码中使用 push() 时,它会在每次刷新位置时不断生成新的 ID。

是否可以在不生成新的唯一 ID 的情况下不断更新用户的位置,或者完全删除位置的更新?

这是我将位置发送到数据库的活动。

private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2000;
private long FASTEST_INTERVAL = 2000;
private LocationManager locationManager;
private LatLng latLng;
private boolean isPermission;


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

    if(requestSinglePermission()){

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        checkLocation();




    }



}

private boolean checkLocation() {

    if(!isLocationEnabled()){
        showAlert();
    }
    return isLocationEnabled();

}

private void showAlert() {
    final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("Enable Location")
            .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
                    "use this app")
            .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                    Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(myIntent);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface paramDialogInterface, int paramInt) {

                }
            });
    dialog.show();
}

private boolean isLocationEnabled() {

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

private boolean requestSinglePermission() {

    Dexter.withActivity(this)
            .withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
            .withListener(new PermissionListener() {
                @Override
                public void onPermissionGranted(PermissionGrantedResponse response) {
                    isPermission = true;
                }

                @Override
                public void onPermissionDenied(PermissionDeniedResponse response) {
                    // check for permanent denial of permission
                    if (response.isPermanentlyDenied()) {
                        isPermission = false;
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(com.karumi.dexter.listener.PermissionRequest permission, PermissionToken token) {

                }


            }).check();

    return isPermission;
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    if(latLng!=null){

        mMap.addMarker(new MarkerOptions().position(latLng).title("Marker in Current Location"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,14F));

    }
}

@Override
public void onConnected(@Nullable Bundle bundle) {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED) {
        return;
    }
    startLocationUpdates();
    mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

    if (mLocation == null) {
        startLocationUpdates();
    }
    else {
        Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
    }
}

private void startLocationUpdates() {

    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(UPDATE_INTERVAL);


    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED) {
        return;
    }

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
            mLocationRequest, this);

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {

    String msg = "Updated Location: " +
            Double.toString(location.getLatitude()) + "," +
            Double.toString(location.getLongitude());
    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();


    LocationSend send = new LocationSend(
            location.getLongitude(),
            location.getLatitude()
    );
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
    reference.getKey();
    reference.child("User Location").setValue(send).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {

            if(task.isSuccessful()){
                Toast.makeText(MapsActivity.this, "Location Saved", Toast.LENGTH_SHORT).show();

            }
            else{
                Toast.makeText(MapsActivity.this, "Location Not Saved", Toast.LENGTH_SHORT).show();
            }
        }
    });




    latLng = new LatLng(location.getLatitude(), location.getLongitude());

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

}



@Override
protected void onStart() {
    super.onStart();

    if(mGoogleApiClient !=null){
        mGoogleApiClient.connect();
    }

}

@Override
protected void onStop() {
    super.onStop();


    if(mGoogleApiClient.isConnected()){
        mGoogleApiClient.disconnect();
    }

}

}

最合适的解决方案是实施Firebase 身份验证并使用存储纬度和经度,如下所示:

Firebase-root
  |
  --- users
       |
       --- $uid
             |
             --- location
                   |
                   --- latitude: 37.421795
                   |
                   --- longitude: -122.13792

这样,您将始终更新相同的位置。 这是所需的参考资料:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference locationRef = db.child("users").child(uid).child("location");

如果您不想生成新的 ID,那么 firebase 每次都会用新值替换旧的纬度和经度值(如果它们与现有值不同)。

当调用 push() function 时,会生成新的 ID。 如果您不想生成新的 ID,则可以使用时间戳来确定何时使用 System.currentTimeMilliS() 方法更新纬度和经度。

代码会像

LocationSend send = new LocationSend(
            location.getLongitude(),
            location.getLatitude(),
            System.currentTimeMillis()
    );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM