下面列出了怎么用android.app.usage.UsageStats的API类实例代码及写法,或者点击链接到github查看源代码。
/** Produces a map for each installed app package name,
* with the corresponding time in foreground in seconds for that application.
*/
@SuppressWarnings("ResourceType")
public static HashMap<String, Double> getUsageMap(Context context, long start, long end) {
UsageStatsManager manager = (UsageStatsManager) context.getSystemService("usagestats");
Map<String, UsageStats> usageStatsMap = manager.queryAndAggregateUsageStats(start, end);
HashMap<String, Double> usageMap = new HashMap<>();
for (String packageName : usageStatsMap.keySet()) {
UsageStats us = usageStatsMap.get(packageName);
try {
long timeMs = us.getTotalTimeInForeground();
Double timeSeconds = new Double(timeMs / 1000);
usageMap.put(packageName, timeSeconds);
} catch (Exception e) {
Log.d(TAG, "Getting timeInForeground resulted in an exception");
}
}
return usageMap;
}
private String currentPackage() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(),
usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
return mySortedMap.get(
mySortedMap.lastKey()).getPackageName();
}
}
}
return currentTask().topActivity.getPackageName();
}
@SuppressWarnings("WrongConstant")
public static String getForegroundAppPackageName(Context context) {
UsageStatsManager manager = (UsageStatsManager) context.getSystemService("usagestats");
long time = System.currentTimeMillis();
List<UsageStats> list = manager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,
time - 1000 * 1000, time);
if (list != null && !list.isEmpty()) {
SortedMap<Long, UsageStats> map = new TreeMap<>();
for (UsageStats stats : list) {
map.put(stats.getLastTimeUsed(), stats);
}
if (!map.isEmpty()) {
return map.get(map.lastKey()).getPackageName();
}
}
return null;
}
@SuppressWarnings("ResourceType")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static ArrayList<UsageStats> getUsageList(Context context, long startTime, long endTime) {
Log.i(TAG," EventUtils-getUsageList() Range start:" + startTime);
Log.i(TAG," EventUtils-getUsageList() Range end:" + endTime);
Log.i(TAG," EventUtils-getUsageList() Range start:" + dateFormat.format(startTime));
Log.i(TAG," EventUtils-getUsageList() Range end:" + dateFormat.format(endTime));
ArrayList<UsageStats> list = new ArrayList<>();
UsageStatsManager mUsmManager = (UsageStatsManager) context.getSystemService("usagestats");
Map<String, UsageStats> map = mUsmManager.queryAndAggregateUsageStats(startTime, endTime);
for (Map.Entry<String, UsageStats> entry : map.entrySet()) {
UsageStats stats = entry.getValue();
if(stats.getTotalTimeInForeground() > 0){
list.add(stats);
Log.i(TAG," EventUtils-getUsageList() stats:" + stats.getPackageName() + " TotalTimeInForeground = " + stats.getTotalTimeInForeground());
}
}
return list;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private List<AppEntry> getAppEntriesUsingUsageStats() {
UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
List<UsageStats> usageStatsList = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, searchInterval, System.currentTimeMillis());
List<AppEntry> entries = new ArrayList<>();
for(UsageStats usageStats : usageStatsList) {
AppEntry newEntry = new AppEntry(
usageStats.getPackageName(),
null,
null,
null,
false
);
newEntry.setTotalTimeInForeground(usageStats.getTotalTimeInForeground());
newEntry.setLastTimeUsed(usageStats.getLastTimeUsed());
entries.add(newEntry);
}
return entries;
}
@Override
public boolean isGoRunning() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
UsageStatsManager usm = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - REFRESH_INTERVAL * REFRESH_INTERVAL, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (!mySortedMap.isEmpty()) {
String currentAppName = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
return (currentAppName.equals("com.android.systemui") || currentAppName.equals("com.tomer.poke.notifier") || currentAppName.equals(getPackageName())) ? isGoOpen : currentAppName.equals(Constants.GOPackageName);
}
}
} else {
ActivityManager am = (ActivityManager) getBaseContext().getSystemService(ACTIVITY_SERVICE);
return am.getRunningTasks(1).get(0).topActivity.getPackageName().equals(Constants.GOPackageName);
}
return isGoOpen;
}
/**
* get current task top app package name
* @param context
* @param am
* @return the top app package name
*/
public static String getTaskTopAppPackageName(Context context, ActivityManager am) {
String packageName = "";
// if the sdk >= 21. It can only use getRunningAppProcesses to get task top package name
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usage = (UsageStatsManager)context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> stats = usage.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time);
if (stats != null) {
SortedMap<Long, UsageStats> runningTask = new TreeMap<Long,UsageStats>();
for (UsageStats usageStats : stats) {
runningTask.put(usageStats.getLastTimeUsed(), usageStats);
}
if (runningTask.isEmpty()) {
return null;
}
packageName = runningTask.get(runningTask.lastKey()).getPackageName();
}
} else {// if sdk <= 20, can use getRunningTasks
List<ActivityManager.RunningTaskInfo> infos = am.getRunningTasks(1);
packageName = infos.get(0).topActivity.getPackageName();
}
return packageName;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private String getTopActivityAfterLM() {
try {
UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
long milliSecs = 60 * 1000;
Date date = new Date();
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, date.getTime() - milliSecs, date.getTime());
if (queryUsageStats.size() > 0) {
return null;
}
long recentTime = 0;
String recentPkg = "";
for (int i = 0; i < queryUsageStats.size(); i++) {
UsageStats stats = queryUsageStats.get(i);
if (stats.getLastTimeStamp() > recentTime) {
recentTime = stats.getLastTimeStamp();
recentPkg = stats.getPackageName();
}
}
return recentPkg;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
@TargetApi(24)
public static Observable<List<AppEntity>>getAppList(final Context ctx){
return RxUtil.makeObservable(new Callable<List<AppEntity>>() {
@Override
public List<AppEntity> call() throws Exception {
List<UsageStats> listStats = UStats.getUsageStatsList(ctx);
List<AppEntity> list = new ArrayList<>();
for (UsageStats stats:listStats) {
stats.getPackageName();
String packageName = stats.getPackageName();
if(packageName.contains("android") || packageName.contains("google")){
continue;
}
if (isNotShowSelf(ctx, packageName)) continue;
AppEntity entity = DataHelper.getAppByPackageName(packageName);
if (entity == null) continue;
list.add(entity);
}
return list;
}
});
}
@Deprecated
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public List<AppEntity> getRecentAppInfo(){
List<UsageStats> usageStatsList = getUsageStatsList();
List<AppEntity> list = new ArrayList<>();
for (UsageStats u : usageStatsList){
String packageName = u.getPackageName();
ApplicationInfo applicationInfo = getAppInfo(packageName);
//system app will not appear recent list
//if(isSystemApp(packageName))continue;
if (isShowSelf(packageName)) continue;
AppEntity entity = DataHelper.getAppByPackageName(packageName);
if (entity == null)continue;
list.add (entity);
}
return list;
}
/**
* Returns the {@link #mRecyclerView} including the time span specified by the
* intervalType argument.
*
* @param intervalType The time interval by which the stats are aggregated.
* Corresponding to the value of {@link UsageStatsManager}.
* E.g. {@link UsageStatsManager#INTERVAL_DAILY}, {@link
* UsageStatsManager#INTERVAL_WEEKLY},
*
* @return A list of {@link android.app.usage.UsageStats}.
*/
public List<UsageStats> getUsageStatistics(int intervalType) {
// Get the app statistics since one year ago from the current time.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, -1);
List<UsageStats> queryUsageStats = mUsageStatsManager
.queryUsageStats(intervalType, cal.getTimeInMillis(),
System.currentTimeMillis());
if (queryUsageStats.size() == 0) {
Log.i(TAG, "The user may not allow the access to apps usage. ");
Toast.makeText(getActivity(),
getString(R.string.explanation_access_to_appusage_is_not_enabled),
Toast.LENGTH_LONG).show();
mOpenUsageSettingButton.setVisibility(View.VISIBLE);
mOpenUsageSettingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
}
});
}
return queryUsageStats;
}
/**
* Updates the {@link #mRecyclerView} with the list of {@link UsageStats} passed as an argument.
*
* @param usageStatsList A list of {@link UsageStats} from which update the
* {@link #mRecyclerView}.
*/
//VisibleForTesting
void updateAppsList(List<UsageStats> usageStatsList) {
List<CustomUsageStats> customUsageStatsList = new ArrayList<>();
for (int i = 0; i < usageStatsList.size(); i++) {
CustomUsageStats customUsageStats = new CustomUsageStats();
customUsageStats.usageStats = usageStatsList.get(i);
try {
Drawable appIcon = getActivity().getPackageManager()
.getApplicationIcon(customUsageStats.usageStats.getPackageName());
customUsageStats.appIcon = appIcon;
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, String.format("App Icon is not found for %s",
customUsageStats.usageStats.getPackageName()));
customUsageStats.appIcon = getActivity()
.getDrawable(R.drawable.ic_default_app_launcher);
}
customUsageStatsList.add(customUsageStats);
}
mUsageListAdapter.setCustomUsageStatsList(customUsageStatsList);
mUsageListAdapter.notifyDataSetChanged();
mRecyclerView.scrollToPosition(0);
}
@Override
protected void after(XParam param) throws Throwable {
switch (mMethod) {
case queryAndAggregateUsageStats:
if (isRestricted(param))
param.setResult(new HashMap<String, UsageStats>());
break;
case queryConfigurations:
case Srv_queryConfigurationStats:
if (isRestricted(param))
param.setResult(new ArrayList<ConfigurationStats>());
break;
case queryEvents:
case Srv_queryEvents:
// Do nothing
break;
case queryUsageStats:
case Srv_queryUsageStats:
if (isRestricted(param))
param.setResult(new ArrayList<UsageStats>());
break;
}
}
private boolean isUserActive(long startTime, long currentTime){
String TAG = "isUserActive";
if (currentNotification == 1){
startTime = startTime - notificationDelay * ONE_MINUTE_MILLIS;
}
//#TODO experiment with using a daily interval (make sure it works past midnight)
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_WEEKLY, startTime, currentTime);
UsageStats minUsageStat = null;
long min = Long.MAX_VALUE;
for (UsageStats usageStat : queryUsageStats){
if ((System.currentTimeMillis() - usageStat.getLastTimeStamp() < min) && (usageStat.getTotalTimeInForeground() > ONE_MINUTE_MILLIS) && !usageStat.getPackageName().equals("com.corvettecole.gotosleep")){ //make sure app has been in foreground for more than one minute to filter out background apps
minUsageStat = usageStat;
min = System.currentTimeMillis() - usageStat.getLastTimeStamp();
}
}
if (minUsageStat != null) {
Log.d(TAG, minUsageStat.getPackageName() + " last time used: " + minUsageStat.getLastTimeUsed() + " time in foreground: " + minUsageStat.getTotalTimeInForeground());
Log.d(TAG, "getLastTimeStamp: " + minUsageStat.getLastTimeStamp() + " getLastUsed: " + minUsageStat.getLastTimeUsed() + " current time: " + System.currentTimeMillis());
Log.d(TAG, (System.currentTimeMillis() - minUsageStat.getLastTimeUsed() <= userActiveMargin * ONE_MINUTE_MILLIS) + "");
return System.currentTimeMillis() - minUsageStat.getLastTimeStamp() <= userActiveMargin * ONE_MINUTE_MILLIS;
} else {
Log.e(TAG, "minUsageStat was null!");
Log.e(TAG, queryUsageStats.toString());
return false;
}
}
public boolean needToSet() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
long time = System.currentTimeMillis();
// We get usage stats for the last 10 seconds
List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 60, time);
return stats.size() == 0;
} else {
return false;
}
}
/** Check if permission for usage statistics is required,
* by fetching usage statistics since the beginning of time
*/
@SuppressWarnings("ResourceType")
public static boolean permissionRequired(Context context) {
UsageStatsManager usm = (UsageStatsManager) context.getSystemService("usagestats");
Calendar calendar = Calendar.getInstance();
long endTime = calendar.getTimeInMillis();
long startTime = 0;
List<UsageStats> stats = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
// If list is empty then permission ios required
return stats.isEmpty();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private long getTotalTimeFromUsage(String pkg){
UsageStats stats = mUseTimeDataManager.getUsageStats(pkg);
if(stats == null){
return 0;
}
return stats.getTotalTimeInForeground();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private ArrayList<UsageStats> getUsageList(int dayNumber) {
long endTime = 0,startTime = 0;
if(dayNumber == 0 ){
endTime = System.currentTimeMillis();
startTime = DateTransUtils.getZeroClockTimestamp(endTime);
}else {
endTime = DateTransUtils.getZeroClockTimestamp(System.currentTimeMillis() - (dayNumber-1) * DateTransUtils.DAY_IN_MILLIS )-1;
startTime = endTime - DateTransUtils.DAY_IN_MILLIS + 1;
}
return EventUtils.getUsageList(mContext,startTime,endTime);
}
private int getLaunchCount(UsageStats usageStats) throws IllegalAccessException {
Field field = null;
try {
field = usageStats.getClass().getDeclaredField("mLaunchCount");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return (int) field.get(usageStats);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public UsageStats getUsageStats(String pkg){
for(int i = 0 ; i < mStatsList.size() ; i++){
if(mStatsList.get(i).getPackageName().equals(pkg)){
return mStatsList.get(i);
}
}
return null;
}
public static String[] getCurrentPackageByManager(Context context) {
String pkg_name = null;
String act_name = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
if (usageStatsManager != null) {
long now = System.currentTimeMillis();
List<UsageStats> stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, now - 6000, now);
if (stats != null && !stats.isEmpty()) {
int top = 0;
for (int last = 0; last < stats.size(); last++) {
if (stats.get(last).getLastTimeUsed() > stats.get(top).getLastTimeUsed()) {
top = last;
}
}
pkg_name = stats.get(top).getPackageName();
}
}
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
@SuppressWarnings("deprecation")
List list = activityManager.getRunningTasks(1);
pkg_name = ((ActivityManager.RunningTaskInfo) list.get(0)).topActivity.getPackageName();
act_name = ((ActivityManager.RunningTaskInfo) list.get(0)).topActivity.getClassName();
}
if (pkg_name == null) {
pkg_name = "";
}
if (act_name == null) {
act_name = pkg_name;
}
if (act_name.contains("$")) {
act_name = act_name.replace("$", ".");
}
return new String[]{pkg_name, act_name};
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private String getActivePackages() {
UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 200 * 200, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
return mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
return context.getPackageName();
}
/**
* 方法4:通过使用UsageStatsManager获取,此方法是ndroid5.0A之后提供的API
* 必须:
* 1. 此方法只在android5.0以上有效
* 2. AndroidManifest中加入此权限<uses-permission xmlns:tools="http://schemas.android.com/tools" android:name="android.permission.PACKAGE_USAGE_STATS"
* tools:ignore="ProtectedPermissions" />
* 3. 打开手机设置,点击安全-高级,在有权查看使用情况的应用中,为这个App打上勾
*
* @param context 上下文参数
* @param packageName 需要检查是否位于栈顶的App的包名
* @return
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static boolean queryUsageStats(Context context, String packageName) {
class RecentUseComparator implements Comparator<UsageStats> {
@Override
public int compare(UsageStats lhs, UsageStats rhs) {
return (lhs.getLastTimeUsed() > rhs.getLastTimeUsed()) ? -1 : (lhs.getLastTimeUsed() == rhs.getLastTimeUsed()) ? 0 : 1;
}
}
RecentUseComparator mRecentComp = new RecentUseComparator();
long ts = System.currentTimeMillis();
UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService("usagestats");
List<UsageStats> usageStats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, ts - 1000 * 10, ts);
if (usageStats == null || usageStats.size() == 0) {
if (HavaPermissionForTest(context) == false) {
Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Toast.makeText(context, "权限不够\n请打开手机设置,点击安全-高级,在有权查看使用情况的应用中,为这个App打上勾", Toast.LENGTH_SHORT).show();
}
return false;
}
Collections.sort(usageStats, mRecentComp);
String currentTopPackage = usageStats.get(0).getPackageName();
if (currentTopPackage.equals(packageName)) {
return true;
} else {
return false;
}
}
/** Query the used packages during the given time span. (works on Android 6+ or Android 5.x with PACKAGE_USAGE_STATS permission granted manually) */
private static Collection<String> queryUsedPackagesDuring(final Context context, final long begin_time, final long end_time) {
if (! Permissions.ensure(context, Manifest.permission.PACKAGE_USAGE_STATS)) return Collections.emptySet();
@SuppressLint("InlinedApi") final UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE); /* hidden but accessible on API 21 */
if (usm == null) return Collections.emptySet();
final Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(begin_time, end_time);
if (stats == null) return Collections.emptySet();
return StreamSupport.stream(stats.values()).filter(usage -> usage.getLastTimeUsed() != 0).map(UsageStats::getPackageName)
.collect(Collectors.toList());
}
@TargetApi(21)
public static List<UsageStats> getUsageStatsList(final Context context) {
UsageStatsManager usm = getUsageStatsManager(context);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
long startTime = calendar.getTimeInMillis();
long endTime = System.currentTimeMillis();
return usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime);
}
public static List<UsageStats> getUsageStatsList(Context context){
UsageStatsManager usm = getUsageStatsManager(context);
Calendar calendar = Calendar.getInstance();
long endTime = calendar.getTimeInMillis();
long startTime = calendar.getTimeInMillis()-60*60*1000;
List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,endTime);
return usageStatsList;
}
public static void printUsageStats(List<UsageStats> usageStatsList){
for (UsageStats u : usageStatsList){
Log.d(TAG, "Pkg: " + u.getPackageName() + "\t" + "ForegroundTime: "
+ u.getTotalTimeInForeground()) ;
}
}
@Deprecated
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public List<UsageStats> getUsageStatsList(){
UsageStatsManager usm = getUsageStatsManager();
Calendar calendar = Calendar.getInstance();
long endTime = calendar.getTimeInMillis();
calendar.add(Calendar.MONTH, -1);
long startTime = calendar.getTimeInMillis();
List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,endTime);
return usageStatsList;
}
public void testGetUsageStatistics() {
List<UsageStats> usageStatsList = mTestFragment
.getUsageStatistics(UsageStatsManager.INTERVAL_DAILY);
// Whether the usageStatsList has any UsageStats depends on if the app is granted
// the access to App usage statistics.
// Only check non null here.
assertNotNull(usageStatsList);
}
@UiThreadTest
public void testUpdateAppsList() {
List<UsageStats> usageStatsList = mTestFragment
.getUsageStatistics(UsageStatsManager.INTERVAL_DAILY);
mTestFragment.updateAppsList(usageStatsList);
// The result depends on if the app is granted the access to App usage statistics.
if (usageStatsList.size() == 0) {
assertTrue(mTestFragment.mUsageListAdapter.getItemCount() == 0);
} else {
assertTrue(mTestFragment.mUsageListAdapter.getItemCount() > 0);
}
}