Android background service to determine foreground application

我是研究僧i 提交于 2019-12-05 20:03:54

Below code works for me. The first task in the list is what I need to determine the foreground application name.

ActivityManager activityManager = (ActivityManager) getSystemService(UpdateService.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> appProcesses = activityManager.getRunningTasks(1);

Log.i("MyApp", "Foreground Package: " + appProcesses.get(0).topActivity.getPackageName());

found the answer, heres how I did it. I am just calling getForegroundApp() from a background service.

   public String getForegroundApp() throws NameNotFoundException{ 

        RunningTaskInfo info = null;
        ActivityManager am;
        am = (ActivityManager)mContext.getSystemService(ACTIVITY_SERVICE);
        List<RunningTaskInfo> l = am.getRunningTasks(1000);
        System.out.println(l);
        Iterator <RunningTaskInfo> i = l.iterator();


        String packName = new String();
        String appName = new String();
        ApplicationInfo appInfo = new ApplicationInfo();

        while(i.hasNext()){
            info = i.next();
            packName = info.topActivity.getPackageName();
            if(!packName.equals("com.htc.launcher") && !packName.equals("com.android.launcher")){ //this could be what is causing the problem. not sure.
                packName = info.topActivity.getPackageName();
                break;
            }
            info = i.next();
            packName= info.topActivity.getPackageName();
            break;          
            }
        return packName;
        }

I know this isn't the best method, especially how I am determining that the launcher is not open since there are more launchers out there than just the two I have listed. But this works for my use case so I thought I would share.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!