获取App使用记录

使用获取app运行记录
出现在 5.0 API21之后,5.0之前是没有这个类的
// 获取app的UsageStatspublic static List getUsageStatsList(Context context) {UsageStatsManager usm = (UsageStatsManager) context.getSystemService("usagestats");Calendar calendar = Calendar.getInstance();long endTime = calendar.getTimeInMillis();calendar.add(Calendar.YEAR, -1);long startTime = calendar.getTimeInMillis();List usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);return usageStatsList;}// 读取UsageStats里数据public static void printUsageStats(List usageStatsList)throws IllegalAccessException, IllegalArgumentException,NoSuchFieldException {for (UsageStats u : usageStatsList) {String pkgName = u.getPackageName();// 包名Long foregroundtime = u.getTotalTimeInForeground();// 运行时长:int launcherCount = u.getClass().getDeclaredField("mLaunchCount").getInt(u);// 运行次数,不能直接访问,反射获取}}
通常情况下默认是拿不到数据的,需要给予权限,并打开相应开关,部分手机开关页是隐藏的,需要代码跳转 。
//需要的权限,再manifest注册后,则可以在“查看使用情况权限”控制页控制本app//跳转的方法public static void statrtUsageAccessActivity(Context context) {Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);context.startActivity(intent);}
/data//
-rw------- systemsystem12992 2016-07-23 08:31 usage-20160722-rw------- systemsystem6532 2016-07-24 01:11 usage-20160723-rw------- systemsystem976 2016-07-25 08:18 usage-20160724-rw------- systemsystem9848 2016-07-26 05:25 usage-20160725-rw------- systemsystem7308 2016-07-26 17:57 usage-20160726-rw------- systemsystem50802 2016-07-26 05:25 usage-history.xml
其中usage-.xml如下
【获取App使用记录】...............
-----------------------分割线---------------------------------
4.4.4之前
com...app.
.4.4_r14.4.3_r14.4.2_r14.4.1_r14.4_r14.3.1_r14.3_r2.14.3_r1
4.2.2_r14.2.1_r1.24.2_r14.1.2_r14.1.1_r1、4.0.4_r2.14.0.4_r1.22.0_r1...
应该是可以通过这个类获取相关信息
需要系统级app才可以

获取App使用记录

文章插图
参考链接:////
// use reflect// have to root and push into system/appprivate void getPkgUsageStats(){try {Class cServiceManager = Class.forName("android.os.ServiceManager");Method mGetService = cServiceManager.getMethod("getService",java.lang.String.class);Object oRemoteService = mGetService.invoke(null, "usagestats");// IUsageStats oIUsageStats =// IUsageStats.Stub.asInterface(oRemoteService)Class