Skip to content

Instantly share code, notes, and snippets.

@mstoic
Last active September 27, 2018 11:11
Show Gist options
  • Save mstoic/f8de9c2896df278cfffaf7d1cd11e0d1 to your computer and use it in GitHub Desktop.
Save mstoic/f8de9c2896df278cfffaf7d1cd11e0d1 to your computer and use it in GitHub Desktop.
Crashes on devices before Lolipop
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public String getForegroundApp(Context context) {
String currentApp = "NULL";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
try {
Class.forName( "android.app.usage.UsageStatsManager" );
UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
} catch( ClassNotFoundException e ) {
//my class isn't there!
Log.i (TAG, "Class not found: android.app.usage.UsageStatsManager");
}
} else {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
Log.i("Foreground App", "getForegroundApp: " + currentApp);
return currentApp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment