views:

503

answers:

2

I'm going to create widget which needs to update its content every minute (it shows time-related data).

However, there is no need to update widget if it is currently invisible, which means:

  • screen is turned off
  • another app is running
  • widget is placed on another (invisible) home screen tab

What is the best way to update only visible widget every minute - without waking up device nor doing unnecessary computations? After widget becomes visible, small lag before update is acceptable.

+2  A: 

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

mbaird
I starred, at least this I can do, you answered so many questions of mine, and probably will do so in the future. Thanks.
Pentium10
Starred, too bad it won't be available in millions of hadsets that are currently in use...
tomash
+3  A: 

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.

xandy