How to run the onLocationChanged method when the application is closed (using the onStop method)… here is a solution to the problem.
How to run the onLocationChanged method when the application is closed (using the onStop method)
I have this method and it manages my position :
@Override
public void onLocationChanged(final Location location) {
if(inRun){
Clocation myLocation = new Clocation(location, this.useMetricUnits());
this.updateSpeed(myLocation);
this.updateDistance(myLocation);
this.updateAverageSpeed(this.distance, this.chronometer);
if (activity.getText().toString() != ActivityRecongnizedService.getActivity()) {
activity.setText(ActivityRecongnizedService.getActivity());
activityTimer.start();
}
switch (activity.getText().toString()) {
case "STILL": still = true; break;
case "IN VEHICLE": inVehicle = true; break;
case "ON BICYCLE": onBicycle = true; break;
case "ON FOOT": onFoot = true; break;
case "RUNNING": running = true; break;
case "WALKING": walking = true; break;
case "TILTING": tilting = true; break;
}
setTimeActivity();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String[] key;
key = user.getEmail().split("@");
reference.child("Position").child(key[0]).child("latlng").setValue(new LatLng(location.getLatitude(),location.getLongitude()));
}
}
But I want this method to run when MainActivity is closed. I read about this, there are two ways to do this: use the service or use the onStop method.
I
prefer the second way, with the onStop method, but I don’t know how to call onLocationChanged in the onStop method.
Solution
Hope this helps.
In Android, there is the Location Manager, which provides access to the system’s location services.
You can use this class to trigger the onLocationChanged
event.
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Get the best provider for the criteria
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String bestprovider = locationManager.getBestProvider(criteria,false);
locationManager.requestLocationUpdates(bestprovider,0, 0, this);
If you insert some code into the onStop
method, the onLocationChanged
event fires.