android – Error while accessing TSensorManager.Current inside a POSIX timer event


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,

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:

  1. Create a filter for the 'ACTION_LOCATION_CHANGE' action for the LocalBroadcastManager and register the LocalBroadcastReceiver;
  2. In the timer event I send the sendBroadcast action 'ACTION_LOCATION_CHANGE';
  3. In the LocalBroadcastReceiver handler, I switch the TLocationSensor activity.

Spied a solution here , a very good example.

Scroll to Top