android.app.usage.UsageStats Java Examples
The following examples show how to use
android.app.usage.UsageStats.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AppLockService.java From lockit with Apache License 2.0 | 7 votes |
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(); }
Example #2
Source File: XUsageStatsManager.java From XPrivacy with GNU General Public License v3.0 | 6 votes |
@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; } }
Example #3
Source File: AppUsageStatisticsFragment.java From android-AppUsageStatistics with Apache License 2.0 | 6 votes |
/** * 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); }
Example #4
Source File: AppUsageStatisticsFragment.java From android-AppUsageStatistics with Apache License 2.0 | 6 votes |
/** * 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; }
Example #5
Source File: AppInfoEngine.java From AppPlus with MIT License | 6 votes |
@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; }
Example #6
Source File: DataHelper.java From AppPlus with MIT License | 6 votes |
@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; } }); }
Example #7
Source File: BackgroundDetectService.java From GrabQQPWD with Apache License 2.0 | 6 votes |
@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 ""; }
Example #8
Source File: ProcessManagerEngine.java From MobileGuard with MIT License | 6 votes |
/** * 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; }
Example #9
Source File: BackgroundUtil.java From AndroidProcess with Apache License 2.0 | 6 votes |
/** * 方法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; } }
Example #10
Source File: MainService.java From More-For-GO with GNU General Public License v3.0 | 6 votes |
@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; }
Example #11
Source File: TaskbarController.java From Taskbar with Apache License 2.0 | 6 votes |
@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; }
Example #12
Source File: EventUtils.java From UseTimeStatistic with MIT License | 6 votes |
@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; }
Example #13
Source File: PolicyUtils.java From Mount with GNU General Public License v3.0 | 6 votes |
@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; }
Example #14
Source File: Stats.java From flutter-plugins with MIT License | 6 votes |
/** 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; }
Example #15
Source File: UStats.java From AppPlus with MIT License | 5 votes |
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; }
Example #16
Source File: Tools.java From Hangar with GNU General Public License v3.0 | 5 votes |
@TargetApi(21) public static List<UsageStats> getUsageStats(Context context) { final UsageStatsManager usageStatsManager = (UsageStatsManager)context.getSystemService(USAGE_STATS_SERVICE_NAME); // Context.USAGE_STATS_SERVICE); long time = System.currentTimeMillis(); List<UsageStats> stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - USAGE_STATS_QUERY_TIMEFRAME, time); if (stats.size() > 1) { Collections.sort(stats, new Tools.UsageStatsComparator()); } return stats; }
Example #17
Source File: RunningTasksLollipop.java From AcDisplay with GNU General Public License v2.0 | 5 votes |
@Nullable private UsageStats getUsageStatsTop(@NonNull Context context) throws SecurityException { SortedMap<Long, UsageStats> statsSortedMap = getUsageStats(context); return statsSortedMap != null && !statsSortedMap.isEmpty() ? statsSortedMap.get(statsSortedMap.lastKey()) : null; }
Example #18
Source File: RunningTasksLollipop.java From AcDisplay with GNU General Public License v2.0 | 5 votes |
@SuppressWarnings("ResourceType") @Nullable private SortedMap<Long, UsageStats> getUsageStats(@NonNull Context context) throws SecurityException { UsageStatsManager usm = (UsageStatsManager) context.getSystemService(USAGE_STATS_MANAGER); // We get usage stats for the last 30 seconds final long timeEnd = System.currentTimeMillis(); final long timeBegin = timeEnd - 30 * 1000; // +30 sec. List<UsageStats> statsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, timeBegin, timeEnd); if (statsList != null) { // Sort the stats by the last time used SortedMap<Long, UsageStats> statsSortedMap = new TreeMap<>(); for (final UsageStats usageStats : statsList) { // Filter system decor apps if ("com.android.systemui".equals(usageStats.getPackageName())) { continue; } statsSortedMap.put(usageStats.getLastTimeUsed(), usageStats); } return statsSortedMap; } return null; }
Example #19
Source File: RunningTasksLollipop.java From AcDisplay with GNU General Public License v2.0 | 5 votes |
/** * {@inheritDoc} */ @Nullable public String getRunningTasksTop(@NonNull Context context) { try { UsageStats usageStats = getUsageStatsTop(context); return usageStats != null ? usageStats.getPackageName() : null; } catch (SecurityException e) { Log.e(TAG, "Failed to get usage stats! Permissions denied!"); e.printStackTrace(); } return null; }
Example #20
Source File: AppUsageStatisticsFragmentTests.java From android-AppUsageStatistics with Apache License 2.0 | 5 votes |
@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); } }
Example #21
Source File: AppUsageStatisticsFragmentTests.java From android-AppUsageStatistics with Apache License 2.0 | 5 votes |
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); }
Example #22
Source File: BedtimeNotificationReceiver.java From GotoSleep with GNU General Public License v3.0 | 5 votes |
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; } }
Example #23
Source File: Tools.java From Hangar with GNU General Public License v3.0 | 5 votes |
@TargetApi(21) public static LollipopTaskInfo parseUsageStats(List<UsageStats> stats, LollipopTaskInfo lollipopTaskInfo) { UsageStats aRunner = stats.get(0); UsageStats bRunner = null; if (lollipopTaskInfo == null) { // setup new lollipopTaskInfo object! lollipopTaskInfo = new Tools.LollipopTaskInfo(aRunner.getPackageName()); } else if (lollipopTaskInfo.packageName.equals(aRunner.getPackageName())) { // Tools.HangarLog("Last package same as current top, skipping! [" + lollipopTaskInfo.packageName + "]"); return lollipopTaskInfo; } // TODO change this to keep track of all usagestats and compare timeinFg deltas // Will need to refactor buildTasks to manage bulk time change to db as well as // new runningTask. for (UsageStats s : stats) { if (s.getPackageName().equals(lollipopTaskInfo.packageName)) { bRunner = s; } } lollipopTaskInfo.lastPackageName = lollipopTaskInfo.packageName; lollipopTaskInfo.packageName = aRunner.getPackageName(); if (bRunner == null) { Tools.HangarLog("Couldn't find previous task [" + lollipopTaskInfo.packageName + "]"); } else { lollipopTaskInfo.timeInFGDelta = (lollipopTaskInfo.timeInFG > 0) ? bRunner.getTotalTimeInForeground() - lollipopTaskInfo.timeInFG : 0; } lollipopTaskInfo.timeInFG = aRunner.getTotalTimeInForeground(); Tools.HangarLog("New [" + lollipopTaskInfo.packageName + "] old [" + lollipopTaskInfo.lastPackageName + "] old FG delta: " + lollipopTaskInfo.timeInFGDelta); return lollipopTaskInfo; }
Example #24
Source File: RunningTaskUtil.java From timecat with Apache License 2.0 | 5 votes |
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; } }
Example #25
Source File: AppInfoEngine.java From AppPlus with MIT License | 5 votes |
@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; }
Example #26
Source File: Stats.java From flutter-plugins with MIT License | 5 votes |
/** 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(); }
Example #27
Source File: UStats.java From AppPlus with MIT License | 5 votes |
public static void printUsageStats(List<UsageStats> usageStatsList){ for (UsageStats u : usageStatsList){ Log.d(TAG, "Pkg: " + u.getPackageName() + "\t" + "ForegroundTime: " + u.getTotalTimeInForeground()) ; } }
Example #28
Source File: UseTimeDataManager.java From UseTimeStatistic with MIT License | 5 votes |
@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); }
Example #29
Source File: UStats.java From batteryhub with Apache License 2.0 | 5 votes |
@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); }
Example #30
Source File: ClonedHiddenSystemApps.java From island with Apache License 2.0 | 5 votes |
/** 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()); }