It seems Google finally closed all doors for getting the current foreground application package.
After the Lollipop update, which killed getRunningTasks(int maxNum)
and thanks to this answer, I used this code to get the foreground application package since Lollipop:
final int PROCESS_STATE_TOP = 2; RunningAppProcessInfo currentInfo = null; Field field = null; try { field = RunningAppProcessInfo.class.getDeclaredField("processState"); } catch (Exception ignored) { } ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); List<RunningAppProcessInfo> appList = am.getRunningAppProcesses(); for (RunningAppProcessInfo app : appList) { if (app.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && app.importanceReasonCode == 0 ) { Integer state = null; try { state = field.getInt( app ); } catch (Exception ignored) { } if (state != null && state == PROCESS_STATE_TOP) { currentInfo = app; break; } } } return currentInfo;
Android 5.1.1 and above (6.0 Marshmallow), it seems, killed getRunningAppProcesses()
as well. It now returns a list of your own application package.
UsageStatsManager
We can use the new UsageStatsManager
API as described here but it doesn't work for all applications. Some system applications will return the same package
com.google.android.googlequicksearchbox
AccessibilityService (December 2017: Going to be banned for use by Google)
Some applications use AccessibilityService
(as seen here) but it has some disadvantages.
Is there another way of getting the current running application package?
Android 5.1.1 and above (6.0 Marshmallow), it seems, killed getRunningAppProcesses () as well. It now returns a list of your own application package. We can use the new UsageStatsManager API as described here but it doesn't work for all applications. Some system applications will return the same package
To get a list of running processes on Android Nougat you will need to use UsageStatsManager or have root access. Click the edit history for previous alternative solutions. Use this method for getting foreground task.
It seems Google finally closed all doors for getting the current foreground application package. After the Lollipop update, which killed getRunningTasks (int maxNum) and thanks to this answer, I used this code to get the foreground application package since Lollipop:
To get a list of running processes on Android 1.6 - Android 6.0 you can use this library I wrote: https://github.com/jaredrummler/AndroidProcesses The library reads /proc to get process info.
Google has significantly restricted access to /proc in Android Nougat. To get a list of running processes on Android Nougat you will need to use UsageStatsManager or have root access.
Click the edit history for previous alternative solutions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With