1.客户要求需要对所有安装的应用根据使用频率进行排序,如下图:
最初想到方法1,通过反射获取系统管理PkgUsageStats变量launchCount,在listview里面点击确实刷新排序。
但是此方法重启后失效了,又重新来了。
/**
*
* 对象比较器 用于程序启动次数排序
*
*
*/
private static class AppUseFrequncyComparator implements Comparator<AppInfo> {
@Override
public int compare(AppInfo front_app, AppInfo behind_app) {
long front = front_app.getLaunchCount();
long behind = behind_app.getLaunchCount();
if (front > behind) {
return -1;
}
if (front < behind) {
return 1;
}
return 0;
}
}
/**
*
* 获取应用使用次数
*
* @param context
* @param packageName
* @return
*/
public static int getAppLaunchCount(String packageName) {
int aLaunchCount = 0;
// PackageManager pm = context.getPackageManager();
try {
Intent i = mPackageManager.getLaunchIntentForPackage(packageName);
log.d("getAppLaunchCount==" + packageName);
if (i == null)
return 0;
ComponentName aName = i.getComponent();
log.d("getAppLaunchCount==" + packageName);
// 隐藏引用
// 获得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);
log.d("getAppLaunchCount==" + packageName);
if (aStats == null)
return 0;
// 获得PkgUsageStats类
Class<?> PkgUsageStats = Class.forName("com.android.internal.os.PkgUsageStats");
log.d("getAppLaunchCount==" + packageName);
aLaunchCount = PkgUsageStats.getDeclaredField("launchCount").getInt(aStats);
} catch (Exception e) {
e.printStackTrace();
}
return aLaunchCount;
}
方法2:通过SharedPreferences进行计数,在onitemClick里面进行统计点击次数(缺点:其他地方点击的不统计)
但总得来说达到用户要求(方便查看常用应用)了