Android get UsageStatsManager in API level 21
Asked Answered
H

1

6

I need to get info about recent apps usage.

Before API 21 it was used getRunningTasks or getRecentTasks to get this info. These methods were deprecated in API 21 according docs.

There is UsageStatsManager class now, introduced in API level 21.
But! Context.getSystemService(UsageStatsService) was added only in API level 22!

The question is - how to get needed data in API 21?? According dashboards, there is 13% of users at this API level, I don't wanna lose them.

Hosier answered 5/10, 2016 at 19:39 Comment(0)
I
13

Well Context#getSystemService(...) was introduced in API level 1 but Contexts' USAGE_STATS_SERVICE String was introduced in API level 22. So the public static final String field Context.USAGE_STATS_SERVICE can only be accessed on devices with API level 22 and up. In order to get the needed data in API level 21 you simply need to pass to this method the resolved String "usagestats".

tl;dr
Use Context.getSystemService("usagestats")

Further notes:
#1 The USAGE_STATS_SERVICE field was already in API level 21 but was tagged with the @hide property which made in inaccessible. In API level 22 this was removed.

#2 You may want to turn of the attribution inspection for the given method via @SuppressWarnings("WrongConstant") otherwise Android Studio will complaint that it isn't a valid constant

Infliction answered 7/10, 2016 at 18:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.