在我的代码中,我使用FusedLocationProviderClient获取用户的位置。在回调中,我将用户的纬度和经度保存在Firebase真实的数据库中。即使用户从一个地方移动到另一个地方,一切都工作正常,唯一的问题是,每次在Firebase上保存坐标时,Activity都会刷新,我如何停止这种自动刷新?
我只发布onCreate方法和回调方法,如果需要更多的代码,我会提供它。
除了每次在Firebase上保存新坐标时活动都会刷新之外,我的代码中的一切都工作正常。
注意:我的程式码位于片段中
private static final String TAG = "DriverMapFragment";
int LOCATION_REQUEST_CODE = 10001;
FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
double latitude,longitude;
DatabaseReference databaseReference;
String schoolName, driverPhone, vehicleNumberPlate;
TextView newLat,newLng;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_driver_map, container, false);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
locationRequest = LocationRequest.create();
locationRequest.setInterval(4000);
locationRequest.setFastestInterval(2000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
databaseReference = FirebaseDatabase.getInstance().getReference();
Intent intent = getActivity().getIntent();
schoolName = intent.getStringExtra("SchoolName");
driverPhone = intent.getStringExtra("DriverPhone");
vehicleNumberPlate = intent.getStringExtra("VehicleNumberPlate");
newLat = view.findViewById(R.id.newLat);
newLng = view.findViewById(R.id.newLng);
return view;
}
LocationCallback locationCallback = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null){
return;
}
for (Location location : locationResult.getLocations()){
Log.d(TAG,"onLocationResult: " + location.toString());
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("Lat",String.valueOf(latitude));
Log.i("Lng",String.valueOf(longitude));
LocationHelper helper = new LocationHelper(
location.getLongitude(),
location.getLatitude()
);
FirebaseDatabase.getInstance().getReference().child("Schools")
.child(schoolName)
.child("drivers")
.child(vehicleNumberPlate)
.child("driverLocation")
.setValue(helper).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.i("Success","Location Saved");
}
else{
Log.i("Failure","Location Not Saved");
}
}
});
}
}
};
1条答案
按热度按时间hm2xizp91#
请确保使用
addListenerForSingleValueEvent
而不是addValueEventListener
,否则在将数据更新到Firebase时,将再次调用addValueEventListener
,并运行您在中调用的“活动”。