Last active
September 27, 2018 11:11
-
-
Save mstoic/f8de9c2896df278cfffaf7d1cd11e0d1 to your computer and use it in GitHub Desktop.
Crashes on devices before Lolipop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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