Uses AndroidApi.Timer, System.Sensors;
I do not want the GPS sensor to drain the battery, so in my Android service I use a POSIX timer (AndroidTimerCreate) to turn the LocationSensor on and off from time to time in its event. It is acceptable for me to collect device coordinates every 5 minutes.
When I access the TSensorManager.Current property,
TSensorManager.Current.Activate; FSensors := SensorManager.Current.GetSensorsByCategory(TSensorCategory.Location);
I get an error
Сan't start sensor: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare ()
If I execute this code on the main thread, for example on AndroidServiceStartCommand or AndroidServiceCreate events, then the SensorManager gets activated fine.
To test the problem, I transferred the code from the service to the Multi-Device Appplication – the problem remains.
Please help me figure out how to turn the LocationSensor on and off on a timer event (well, or just once every 5 minutes)?
Found this solution:
- Create a filter for the 'ACTION_LOCATION_CHANGE' action for the LocalBroadcastManager and register the LocalBroadcastReceiver;
- In the timer event I send the sendBroadcast action 'ACTION_LOCATION_CHANGE';
- In the LocalBroadcastReceiver handler, I switch the TLocationSensor activity.
Spied a solution here , a very good example.