首页  编辑  

通过反射方法获得usagestats服务

Tags: /Android/   Date Created:
http://www.voidcn.com/article/p-wxzriqoc-wp.html
//通过反射方法获得usagestats服务        
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<?> cStub = Class  
                .forName("com.android.internal.app.IUsageStats$Stub");  
        Method mUsageStatsService = cStub.getMethod("asInterface",  
                android.os.IBinder.class);  
        Object oIUsageStats = mUsageStatsService.invoke(null,  
                oRemoteService);  
  
        // PkgUsageStats[] oPkgUsageStatsArray =  
        // mUsageStatsService.getAllPkgUsageStats();  
        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) {  
            // get pkgUsageStats.packageName, pkgUsageStats.launchCount,  
            // pkgUsageStats.usageTime  
            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"/>