Android - how update widget often but only when it is visible? Android - how update widget often but only when it is visible? android android

Android - how update widget often but only when it is visible?


To keep from updating when the screen is off, use the AlarmManager to schedule a recurring alarm that doesn't wakeup the phone.

The other two bullet points you have in your question aren't possible. There is no way to detect if your widget is on a home screen that isn't currently visible, and there is no way to determine if an app is running that is hiding the home screen. I have filed a ticket on http://b.android.com requesting this functionality be added to Android. If you feel like starring it, it will help it gain priority: http://code.google.com/p/android/issues/detail?id=5529&q=reporter:mark.r.baird&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars


  1. You can ask the PowerManager about isScreenOn()
  2. You can register for Intent ACTION_SCREEN_OFF/ACTION_SCREEN_ON and turn you timer on/off accordingly.

Allthough the answer above concerning the AlarmManager is correct it may not be sufficient since I observed many phones also delivering alarms even if they are not of type *_WAKEUP. This may happen if there are other applications installed that are waking up the device. And if it is once awake, it delivers all pending alarms.


I found this under a project named 24clock in goole code. It try Not update the widget while user is away from home:

    ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);    List<RunningTaskInfo> runningTasks = am.getRunningTasks(2);    for (RunningTaskInfo t : runningTasks) {        if (t != null && t.numRunning > 0) {            ComponentName cn = t.baseActivity;            if (cn == null) continue;            String clz = cn.getClassName();            String pkg = cn.getPackageName();            // TODO make this configurable            if (pkg != null && pkg.startsWith("com.android.launcher")) {                return true;            }            return false;        }    }

It might be an answer for you requirement #2. Although it might not work under other 3rd party launchers.

== Update ==

A few months later, I suddenly have an idea in my mind about how to detect whether home screen is showing. I put it in my blog, and I ran test on my Desire and it works fine. The method is to query the Android for all installed packages, which one of it contains the "Launcher" ability, and then check whether it is on the top of running stack. If anyone have tested please let me know the result as well, since I have no access to other Android devices.