Class<?> cServiceManager = Class
.forName("android.os.ServiceManager");
Method mGetService = cServiceManager.getMethod("getService",
java.lang.String.class);
Object oRemoteService = mGetService.invoke(null, "usagestats");
Class<?> cStub = Class
.forName("com.android.internal.app.IUsageStats$Stub");
Method mUsageStatsService = cStub.getMethod("asInterface",
android.os.IBinder.class);
Object oIUsageStats = mUsageStatsService.invoke(null,
oRemoteService);
Class<?> cIUsageStatus = Class
.forName("com.android.internal.app.IUsageStats");
Method mGetAllPkgUsageStats = cIUsageStatus.getMethod(
"getAllPkgUsageStats", (Class[]) null);
Object[] oPkgUsageStatsArray = (Object[]) mGetAllPkgUsageStats
.invoke(oIUsageStats, (Object[]) null);
System.out.println(oPkgUsageStatsArray);
Class<?> cPkgUsageStats = Class
.forName("com.android.internal.os.PkgUsageStats");
for (Object pkgUsageStats : oPkgUsageStatsArray) {
String packageName = (String) cPkgUsageStats.getDeclaredField(
"packageName").get(pkgUsageStats);
int launchCount = cPkgUsageStats
.getDeclaredField("launchCount").getInt(pkgUsageStats);
long usageTime = cPkgUsageStats.getDeclaredField("usageTime")
.getLong(pkgUsageStats);
System.out.println(packageName + ":" + launchCount + ":"
+ usageTime);
注意加权限:
<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>