0

How do I get information about the app that is currently on the foreground?

E.g. When I open an app I want to see the app name flashing under the screen like the following screenshot:

App name flasing under screen (Instagram)

I want this to happen for every app I open, not just the first, or the first 3, for every app I open. Then when I have that information, I want to do a few things if the app package name (Or name, but preferably the package name) is equal to the one I want.

Thanks

WoJo
  • 470
  • 1
  • 3
  • 16
  • Like when you open facebook then toast Facebook should be print if yes then i am just curious to know why you want to do this? – haresh Jan 12 '20 at 16:19
  • @haresh Yes, thats what I want to achieve. I want to achieve this so that when a certain app is opened, I can modify the volume. – WoJo Jan 12 '20 at 16:20

1 Answers1

0

Try this out :

 ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
 List l = am.getRecentTasks(1, ActivityManager.RECENT_WITH_EXCLUDED);
 Iterator i = l.iterator();
 PackageManager pm = this.getPackageManager();
 while (i.hasNext()) {
 ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) 
(i.next());
 try {
    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(
    info.processName, PackageManager.GET_META_DATA));
    Log.w("LABEL", c.toString()); // here you will get app name
} catch (Exception e) {
    // Name Not FOund Exception
}
}
haresh
  • 1,344
  • 2
  • 11
  • 17
  • When I paste this into my code (at the OnStart()) it gives me 14 errors so I'm not sure whats wrong. Errors: ActivityManager could not be found, CharSequence could not be found, Iterator could not be found, List could not be found, PackageManager could not be found, Log does not exist in the current context. Are you sure this is C#? Also, when I try to run it in Java, it also gives me lots of errors so I don't understand. – WoJo Jan 12 '20 at 17:42
  • Actually, in Java it only gives me **2** errors: `Cannot resolve method 'getSystemService(java.lang.String)'` and `Cannot resolve method 'getPackageManager()'` – WoJo Jan 12 '20 at 17:45
  • this is the java code which i used but in xamarin you can use activity manager.Try this answer https://stackoverflow.com/questions/11411395/how-to-get-current-foreground-activity-context-in-android. – haresh Jan 12 '20 at 17:49
  • Doesn't that say it's deprecated? – WoJo Jan 12 '20 at 18:54
  • alternative look for this :https://stackoverflow.com/questions/49743206/android-usagestatsmanager-get-a-list-of-currently-running-apps-on-phone – haresh Jan 12 '20 at 19:03
  • Yes, I came across that but that would mean I need to run that code in a loop, which would not be ideal. I need the code to run immediately on launch of the app. – WoJo Jan 12 '20 at 19:06