[英]How to copy a record from a location to another in Firebase realtime database?
[英]How to periodically update the location to Firebase Realtime database?
我正在使用 Android Studio 和 Firebase 创建一个实时公共交通跟踪系统。 我创建了一个用户切换的切换按钮,位置将开始跟踪。 我遇到的问题是位置数据只发送一次到数据库。 但是对于应用程序,位置正在正常跟踪。
我需要的是每次位置更新都必须更新到数据库中。 这是我的代码中的错误或错误吗?
这是位置回调函数:
//Location Callback
locationCallback = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
if(locationResult == null) {
return;
}
Location driverLocation = locationResult.getLastLocation();
Toast.makeText(DriverDetail.this, driverLocation.getLatitude()+", "+driverLocation.getLongitude()
, Toast.LENGTH_SHORT).show();
Log.d("Location Update: ", "onLocationResult: Location is: "
+driverLocation.getLatitude()+", "+driverLocation.getLongitude());
}
};
这是切换按钮的代码
locate_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View button) {
if (locate_btn.isChecked()) {
// The toggle is enabled
Toast.makeText(DriverDetail.this, "Start tracking location", Toast.LENGTH_SHORT).show();
final String value_lat = String.valueOf(driverLocation.getLatitude());
final String value_lng = String.valueOf(driverLocation.getLongitude());
getLocationUpdates();
ref.child(firebaseUser.getUid()).child("Latitude").setValue(value_lat);
ref.child(firebaseUser.getUid()).child("Longitude").setValue(value_lng);
}
else {
// The toggle is disabled
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
Toast.makeText(DriverDetail.this, "Stop tracking location", Toast.LENGTH_SHORT).show();
}
}
});
这是我设置的位置请求。
//Update Location
private void getLocationUpdates(){
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(3000);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
}
当用户切换按钮时,您的代码现在正在将位置数据写入 Firebase。
您想要的是在切换按钮后连续写入位置。 这意味着写入应该在onLocationResult
内部发生(或被触发):
locationCallback = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
if(locationResult == null) {
return;
}
Location driverLocation = locationResult.getLastLocation();
if (true) { // TODO: check if button is toggled
final String value_lat = String.valueOf(driverLocation.getLatitude());
final String value_lng = String.valueOf(driverLocation.getLongitude());
ref.child(firebaseUser.getUid()).child("Latitude").setValue(value_lat);
ref.child(firebaseUser.getUid()).child("Longitude").setValue(value_lng);
}
}
};
在if (true)
语句中,您可能想要检查按钮是否已切换。 但由于我注意到您仅在用户切换按钮时注册位置更新,因此甚至可能不需要该检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.