Showing posts with label launcher. Show all posts
Showing posts with label launcher. Show all posts

Tuesday, December 21, 2010

Detecting is home(launcher) screen showing

While developing widgets for android, especially the clock widget which should updates each second, determining whether the home screen is on top is important to save for batteries and CPU power. After quite some time of research, following is the method I could find to do this:

 public boolean HomeIsShowing(){
  Intent intent = new Intent(Intent.ACTION_MAIN);
  intent.addCategory(Intent.CATEGORY_HOME);
  ArrayList homeList = new ArrayList();
  for(ResolveInfo info : this.getPackageManager().queryIntentActivities(intent, 0)){
   homeList.add(info.activityInfo.packageName);
  }
  
  ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningTaskInfo t : am.getRunningTasks(1)) {
            if (t != null && t.numRunning > 0) {
                ComponentName cn = t.baseActivity;
                if (cn == null)
                 continue;
                else
                 if (homeList.contains(cn.getPackageName())) return true;
            }
        }
        return false;
 }

Tested on my HTC Desire, it tooks about 5000ms to run 1000 iteration of the above query: that's about 5ms each time, it's quite heavy since it is querying all the applications installed (maybe?) so you probably won't use this too often.