Getting current running application

99封情书 提交于 2019-12-09 19:39:50

问题


How may I get the current running application?

I want to check if the application is running or not in service. I used the following code for that.

       ActivityManager activityManager =
       (ActivityManager)
       this.getSystemService(ACTIVITY_SERVICE );

   PackageManager pm =getPackageManager();
   procInfos = activityManager.getRunningAppProcesses();

But it is returning me list of several applications, even if I pressed back button on their home screen. The running app list is still showing them in the list. But I want that list to show only the apps in foreground.

So, how to differentiate between foreground and background running apps?

Or in other words, how to detect current foreground running applications, or which are not destroyed. I don't want to get background running apps.


回答1:


You can try this code it gives the package of the currently active screen:

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;
if(!componentInfo.getPackageName().equals("your.package.name"))
{
    //Do your stuff
}

You might need the permission

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


来源:https://stackoverflow.com/questions/11246703/getting-current-running-application

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