The accepted answer from mbaird hits the nail on the head. The proposed onVisivilityChange()
method, if implemented, should cover all the cases above.
In the meantime this is still a real problem for some types of widget. jom introduced the possibility of registering to receive ACTION_SCREEN_OFF/ACTION_SCREEN_ON intents. This is useful because relying on a non-wakeup recurring alarm is not sufficient as other services make cause wakeups. It is difficult because such actions cannot be subscribed to via AndroidManifest.xml and an AppWidgetProvider is not permitted to call context.registerReceiver()
. These issues are discussed in several other StackOverflow questions including Listening for ACTION_SCREEN_OFF, android.intent.action.SCREEN_ON doesn't work as a receiver intent filter and Android - how to receive broadcast intents ACTION_SCREEN_ON/OFF?.
I have succeeded in subscribing to ACTION_SCREEN_OFF/ACTION_SCREEN_ON intents in a widget by creating a subsidiary BroascastReceiver
instance and using context.getApplicationContext().registerReceiver()
to register it. This could well be cheating and, at least in some subsequent Android release, may fail at the registration stage or perhaps the events will simply not be delivered. I have coded to handle these cases but for now it works. Unfortunately, of course, this will fail if and when the application is ever killed.
Another possibility is to use an isHomeScreenShowing()
sort of method, as described here, referenced by xandy's answer. The ideas there could probably be optimized by caching the generated list of installed CATEGORY_HOME
applications and listening to ACTION_PACKAGE_ADDED/CHANGED/REMOVED broadcasts to update it.
My strategy is:
- Try to avoid being called (via a repeating alarm) when not visible.
- When called, check screen state and other visibility indicators before doing anything expensive.
- Only then invoke an
IntentService
to handle relatively expensive work, which includes a persistent network connection. This is necessary to monitor the state of a remote service in near real time.