Search code examples
androidbroadcastreceiveralarmmanagerandroid-sensors

Implementing SensorEventListener in a BroadcastReceiver... is it possible?


Why can't I have a class extending BroadcastReceiver and implementing SensorEventListener? This class receives alarm intents set in my application.

I have a class instance variable that is set inside the implemented onSensorChanged method. In the onReceive method I register the listener, have a while loop that runs until the class instance variable is set. After the loop I unregister the listener. But the variable is never set and the loop keeps running.

According to the answer here I should never register a listener inside a broadcast receiver:

BroadcastReceiver with a Listener drains battery when not in use

In AlarmManager docs there are all these warnings about the device sleeping but in my case it never sleeps.


Solution

  • According to this post:

    AlarmManager and BroadcastReceiver instead of Service - is that bad ? (Timeout)

    the onReceive method is run on the main application thread and cannot do a lot work or it times out. I can just fix my issue by moving the workload to an IntentService.