Search code examples
androidandroid-appwidget

how can I know whether an android app widget is in background


I do not want to update UI of my app widget when it go to background(you can not see it), how can I know an app widget is in background?


Solution

  • You cannot detect whether or not your homescreen widget it currently visible. There is an open bug report requesting this here.

    At best, you could check to see if the homescreen (or any launcher in general) is visible:

    public boolean isHomeShowing(){
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        ArrayList<string> homeList = new ArrayList<string>();
        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;
    }