0

I use following code in service to get the current foreground of running app in android but when i open any app it shows the name of the app in which I made this service

ActivityManager am = (ActivityManager)MyService.this.getSystemService(ACTIVITY_SERVICE);
                    // The first in the list of RunningTasks is always the foreground task.
                    ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
                    String foregroundTaskPackageName = foregroundTaskInfo .topActivity.getPackageName();
                    PackageManager pm = MyService.this.getPackageManager();
                    PackageInfo foregroundAppPackageInfo = null;
                    try {
                        foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    String packageName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();
Gordon Bell
  • 13,337
  • 3
  • 45
  • 64

2 Answers2

0

try this code:

 ActivityManager mActivityManager =(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);

if(Build.VERSION.SDK_INT > 20){
String mPackageName = mActivityManager.getRunningAppProcesses().get(0).processName;
}
else{
  String mpackageName = mActivityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}

it returns the the application base package name..

rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
0

The short answer is that you can't do this and you shouldn't try. Google has been trying to prevent this since 5.0, and every workaround that people discover has been disabled in a subsequent Android version. It's likely that any new method that you discover will soon be closed. If you write an app that requires this ability, the best case scenario is that it will be a perpetual maintenance nightmare. The worst case scenario is that Google will close all the loopholes, and your app will become useless.

The latest dirty hack is implemented by the open source AndroidProcesses library. But as the readme says, it already doesn't work in 7.0+.

Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82