Domanda

I have a BroadcastReceiver that is listening for the screen to turn off.

For reasons that I won't go into, I need my Activity to finish() when it pauses.

However, the Broadcast takes so long to arrive that by the time it does the onDestroy method (which is the last place I can put it) has already unregistered the receiver so my Activity never gets the notification that the screen has fallen asleep.

In what is the ugliest kluge ever, I have found that if I set a delay of about 500ms and call finish() from a delayed Runnable in onPause, everything works as expected. However, this is brutally ugly and I'm wondering if there's anything else I can do to get around this. It seems that this is *only an issue in the screen timeout broadcast because the action of the screen going off calls onPause for me (which calls finish()). Other broadcasts arrive in the daylight (so to speak) so they don't produce the same problem as they're dealt with a split second later.

È stato utile?

Soluzione

It sounds like it does some non-UI related stuff in which case it might make sense to put that in a Service instead of an Activity if you want to it work even when the UI is not active.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top