-2

I Am Developing an App where I need to recognise the current running app on top, so I have tried with below code

 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
    }

But it's not working on Android Lollipop(5.0) and above os version, It's not returning the current running app informations.

please help if any one have any idea to do so on android lollipop(5.0) and above os versions.

Aniruddh Parihar
  • 3,072
  • 3
  • 21
  • 39

1 Answers1

0

You have to use UsageStatsManager class to achieve this. It requires android.permission.PACKAGE_USAGE_STATS. But it is mentioned as below in the developer guide.

NOTE: This API requires the permission android.permission.PACKAGE_USAGE_STATS, which is a system-level permission and will not be granted to third-party apps. However, declaring the permission implies intention to use the API and the user of the device can grant permission through the Settings application.

This means the user must also enable access for this app through Settings > Security > Apps with usage access.

Refer here for more details.