Reputation:
I found this method to get the foreground activity:
public String getRecentActivity(Context context) { //I cut out the pre API 22 part of the method
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
UsageEvents usageEvents = mUsageStatsManager.queryEvents(time - 1000 * 30, System.currentTimeMillis() + (10 * 1000));
UsageEvents.Event event = new UsageEvents.Event();
while (usageEvents.hasNextEvent()) {
usageEvents.getNextEvent(event);
}
if (!TextUtils.isEmpty(event.getPackageName()) && event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
return event.getPackageName();
}
}
return " ";
}
Here's the problem: When there's a foreground service running this method returns an empty package name instead of the package name of foreground activity (i.e. return " ";
). How can I have it return the foreground activity? Is there a way to filter out services from usageEvents?
Upvotes: 0
Views: 230
Reputation: 153
Hope it will fix if use queryUsageStates
instead of quertEvent
public String getRecentActivity(){
String mpackageName = "";
UsageStatsManager usage = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> stats = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 30, time);
if (stats != null) {
SortedMap<Long, UsageStats> runningTask = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : stats) {
runningTask.put(usageStats.getLastTimeUsed(), usageStats);
}
if (runningTask.isEmpty()) {
mpackageName = "";
} else {
mpackageName = runningTask.get(runningTask.lastKey()).getPackageName();
}
}
return mpackageName;
}
Upvotes: 0