long time = System.currentTimeMillis();
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*30, time);
发现 stats.size()==0
这种情况一般是缺少权限
1:判断当前应用是否被授权为有权查看使用情况的应用
public boolean checkMonitorAppPermission() {
try {
Object object = getSystemService(Context.APP_OPS_SERVICE);
if (object == null) {
return false;
}
Class localClass = object.getClass();
Class[] arrayOfClass = new Class[3];
arrayOfClass[0] = Integer.TYPE;
arrayOfClass[1] = Integer.TYPE;
arrayOfClass[2] = String.class;
Method method = localClass.getMethod("checkOp", arrayOfClass);
if (method == null) {
return false;
}
Object[] arrayOfObject1 = new Object[3];
arrayOfObject1[0] = 43;
arrayOfObject1[1] = Integer.valueOf(Binder.getCallingUid());
arrayOfObject1[2] = getPackageName();
int result = ((Integer) method.invoke(object, arrayOfObject1)).intValue();
Log.e("result", "========");
Log.e("result1", String.valueOf(result));
if (result == 0) {
return true;
} else {
return false;
}
} catch (Exception ex) {
}
return false;
}
2:如果没授权则跳转授权
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
startActivity(intent);
授权后就可以得到最近活跃的应用信息了,问题解决!
网友评论