//get usagestats service
IUsageStats mUsageStatsService = IUsageStats.Stub
.asInterface(ServiceManager.getService(“usagestats”));
try {
//get PkgUsageStats
PkgUsageStats aStats = mUsageStatsService
.getPkgUsageStats(aName);
PkgUsageStats bStats = mUsageStatsService
.getPkgUsageStats(bName);
if(aStats!=null && bStats!=null) {
if ((aStats.launchCount > bStats.launchCount)
|| ((aStats.launchCount == bStats.launchCount) && (aStats.usageTime > bStats.usageTime)))
result = -1;
else if ((aStats.launchCount < bStats.launchCount)
|| ((aStats.launchCount == bStats.launchCount) && (aStats.usageTime < bStats.usageTime)))
result = 1;
else {
result = 0;
}
}else if(aStats!=null && bStats ==null) {
result = -1;
} else if(aStats==null && bStats !=null) {
result = 1;
}
} catch (RemoteException e) {
Log.i(“TAG”, “get package usage stats fail”);
}
return result;
}
那么如果想在sdk中使用这个 类要如果作呢–可以使用反射 的方法,代码如下:
public final int compare(ApplicationInfo a, Ap
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
plicationInfo b) {
ComponentName aName = a.intent.getComponent();
ComponentName bName = b.intent.getComponent();
int aLaunchCount,bLaunchCount;
long aUseTime,bUseTime;
int result = 0;
try {
//获得ServiceManager类
Class<?> ServiceManager = Class
.forName(“android.os.ServiceManager”);
//获得ServiceManager的getService方法
Method getService = ServiceManager.getMethod(“getService”, java.lang.String.class);
//调用getService获取RemoteService
Object oRemoteService = getService.invoke(null, “usagestats”);
//获得IUsageStats.Stub类
Class<?> cStub = Class
.forName(“com.android.internal.app.IUsageStats$Stub”);
//获得asInterface方法
Method asInterface = cStub.getMethod(“asInterface”, android.os.IBinder.class);
//调用asInterface方法获取IUsageStats对象
Object oIUsageStats = asInterface.invoke(null, oRemoteService);
//获得getPkgUsageStats(ComponentName)方法
Method getPkgUsageStats = oIUsageStats.getClass().getMethod(“getPkgUsageStats”, ComponentName.class);
//调用getPkgUsageStats 获取PkgUsageStats对象
Object aStats = getPkgUsageStats.invoke(oIUsageStats, aName);
Object bStats = getPkgUsageStats.invoke(oIUsageStats, bName);
//获得PkgUsageStats类
Class<?> PkgUsageStats = Class.forName(“com.android.internal.os.PkgUsageStats”);
aLaunchCount = PkgUsageStats.getDeclaredField(“launchCount”).getInt(aStats);
bLaunchCount = PkgUsageStats.getDeclaredField(“launchCount”).getInt(bStats);
aUseTime = PkgUsageStats.getDeclaredField(“usageTime”).getLong(aStats);
bUseTime = PkgUsageStats.getDeclaredField(“usageTime”).getLong(bStats);