Android: how do I know if the main screen is in focus?

I have a service running on Android, and I need to know if there is any application in focus or if the “desktop” (main screen) is in focus. I do not know if this is suitable to indicate the main screen of the phone. How can I find out if this is in focus or some other application?

Inside the service, I have this code to perform the tasks that are performed:

ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;

How can I find out from componentInfo if this is the desktop or not? In the emulator, componentInfo.getPackageName () returns com.android.launcher , but in the galaxy s1 (I tested only on this phone), it returns something else.

Is there any other way to do this?

Thank.

+3
source share
3

, " ", .

0
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
ComponentName currentTask = taskInfo.get(0).topActivity;

final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_HOME);
mPackageManager = getPackageManager();

List<ResolveInfo> appList = mPackageManager.queryIntentActivities(mainIntent, 0);
for(int i = 0; i < appList.size(); i++) {
    ResolveInfo apl = appList.get(i);
    if(currentTask.getPackageName().equals(apl.activityInfo.packageName)) {
        Log.e(TAG, "ONHOMESCREEN");
    }
}

AndroidManifest.xml

<uses-permission android:name="android.permission.GET_TASKS"/>
+4

Try this feature,

    public boolean isUserIsOnHomeScreen()
{
    ActivityManager manager = 
            (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List<RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
    for (RunningAppProcessInfo process : processes)
    {
        if(process.pkgList[0].equalsIgnoreCase("com.android.launcher"))
        {
            return true;
        }
        else
        {
            return false;
        }

    }
    return false;

}
+1
source

All Articles