android.app.usage.UsageStatsManager Java Examples

The following examples show how to use android.app.usage.UsageStatsManager. 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 vote down vote up
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: EventUtils.java    From UseTimeStatistic with MIT License 6 votes vote down vote up
@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 #3
Source File: LollipopDetector.java    From foregroundappchecker with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public String getForegroundApp(final Context context) {
    if(!Utils.hasUsageStatsPermission(context))
        return null;

    String foregroundApp = null;

    UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Service.USAGE_STATS_SERVICE);
    long time = System.currentTimeMillis();

    UsageEvents usageEvents = mUsageStatsManager.queryEvents(time - 1000 * 3600, time);
    UsageEvents.Event event = new UsageEvents.Event();
    while (usageEvents.hasNextEvent()) {
        usageEvents.getNextEvent(event);
        if(event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
            foregroundApp = event.getPackageName();
        }
    }

    return foregroundApp ;
}
 
Example #4
Source File: MainService.java    From More-For-GO with GNU General Public License v3.0 6 votes vote down vote up
@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 #5
Source File: BackgroundUtil.java    From AndroidProcess with Apache License 2.0 6 votes vote down vote up
/**
 * 方法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 #6
Source File: ProcessManagerEngine.java    From MobileGuard with MIT License 6 votes vote down vote up
/**
 * 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 #7
Source File: FreezeService.java    From Shelter with Do What The F*ck You Want To Public License 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    // Save usage statistics right now!
    // We need to use the statics at this moment
    // for "skipping foreground apps"
    // No app is foreground after the screen is locked.
    mScreenLockTime = new Date().getTime();
    if (SettingsManager.getInstance().getSkipForegroundEnabled() &&
            Utility.checkUsageStatsPermission(FreezeService.this)) {
        UsageStatsManager usm = getSystemService(UsageStatsManager.class);
        mUsageStats = usm.queryAndAggregateUsageStats(mScreenLockTime - APP_INACTIVE_TIMEOUT, mScreenLockTime);
    }

    // Delay the work so that it can be canceled if the screen
    // gets unlocked before the delay passes
    mHandler.postDelayed(mFreezeWork,
            ((long) SettingsManager.getInstance().getAutoFreezeDelay()) * 1000);
    registerReceiver(mUnlockReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
}
 
Example #8
Source File: BackgroundDetectService.java    From GrabQQPWD with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: UStats.java    From AppPlus with MIT License 6 votes vote down vote up
@SuppressWarnings("ResourceType")
public static void getStats(Context context){
    UsageStatsManager usm = (UsageStatsManager) context.getSystemService("usagestats");
    int interval = UsageStatsManager.INTERVAL_YEARLY;
    Calendar calendar = Calendar.getInstance();
    long endTime = calendar.getTimeInMillis();
    calendar.add(Calendar.YEAR, -1);
    long startTime = calendar.getTimeInMillis();

    Log.d(TAG, "Range start:" + dateFormat.format(startTime) );
    Log.d(TAG, "Range end:" + dateFormat.format(endTime));

    UsageEvents uEvents = usm.queryEvents(startTime,endTime);
    while (uEvents.hasNextEvent()){
        UsageEvents.Event e = new UsageEvents.Event();
        uEvents.getNextEvent(e);

        if (e != null){
            Log.d(TAG, "Event: " + e.getPackageName() + "\t" +  e.getTimeStamp());
        }
    }
}
 
Example #10
Source File: Stats.java    From flutter-plugins with MIT License 6 votes vote down vote up
/** 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 #11
Source File: TaskbarController.java    From Taskbar with Apache License 2.0 6 votes vote down vote up
@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: UsageStatsUtils.java    From FCM-for-Mojo with GNU General Public License v3.0 6 votes vote down vote up
public static String getForegroundPackage(UsageStatsManager usageStatsManager) {
    String packageName = null;

    final long INTERVAL = 1000 * 60;
    final long end = System.currentTimeMillis();
    final long begin = end - INTERVAL;
    final UsageEvents usageEvents = usageStatsManager.queryEvents(begin, end);
    while (usageEvents.hasNextEvent()) {
        UsageEvents.Event event = new UsageEvents.Event();
        usageEvents.getNextEvent(event);
        switch (event.getEventType()) {
            case UsageEvents.Event.MOVE_TO_FOREGROUND:
                packageName = event.getPackageName();
                break;
            case UsageEvents.Event.MOVE_TO_BACKGROUND:
                if (event.getPackageName().equals(packageName)) {
                    packageName = null;
                }
        }
    }

    return packageName;
}
 
Example #13
Source File: ActivityManagerShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private int bucketNameToBucketValue(String name) {
    String lower = name.toLowerCase();
    if (lower.startsWith("ac")) {
        return UsageStatsManager.STANDBY_BUCKET_ACTIVE;
    } else if (lower.startsWith("wo")) {
        return UsageStatsManager.STANDBY_BUCKET_WORKING_SET;
    } else if (lower.startsWith("fr")) {
        return UsageStatsManager.STANDBY_BUCKET_FREQUENT;
    } else if (lower.startsWith("ra")) {
        return UsageStatsManager.STANDBY_BUCKET_RARE;
    } else if (lower.startsWith("ne")) {
        return UsageStatsManager.STANDBY_BUCKET_NEVER;
    } else {
        try {
            int bucket = Integer.parseInt(lower);
            return bucket;
        } catch (NumberFormatException nfe) {
            getErrPrintWriter().println("Error: Unknown bucket: " + name);
        }
    }
    return -1;
}
 
Example #14
Source File: AlarmManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Return the minimum time that should elapse before an app in the specified bucket
 * can receive alarms again
 */
private long getMinDelayForBucketLocked(int bucket) {
    // UsageStats bucket values are treated as floors of their behavioral range.
    // In other words, a bucket value between WORKING and ACTIVE is treated as
    // WORKING, not as ACTIVE.  The ACTIVE and NEVER bucket apply only at specific
    // values.
    final int index;

    if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
    else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
    else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
    else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
    else index = ACTIVE_INDEX;

    return mConstants.APP_STANDBY_MIN_DELAYS[index];
}
 
Example #15
Source File: AppStateTracker.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void onAppIdleStateChanged(String packageName, int userId, boolean idle,
        int bucket, int reason) {
    if (DEBUG) {
        Slog.d(TAG,"onAppIdleStateChanged: " + packageName + " u" + userId
                + (idle ? " idle" : " active") + " " + bucket);
    }
    final boolean changed;
    if (bucket == UsageStatsManager.STANDBY_BUCKET_EXEMPTED) {
        changed = mExemptedPackages.add(userId, packageName);
    } else {
        changed = mExemptedPackages.remove(userId, packageName);
    }
    if (changed) {
        mHandler.notifyExemptChanged();
    }
}
 
Example #16
Source File: PolicyUtils.java    From Mount with GNU General Public License v3.0 6 votes vote down vote up
@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 #17
Source File: EventUtils.java    From UseTimeStatistic with MIT License 6 votes vote down vote up
@SuppressWarnings("ResourceType")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static ArrayList<UsageEvents.Event> getEventList(Context context, long startTime, long endTime){
    ArrayList<UsageEvents.Event> mEventList = new ArrayList<>();

    Log.i(TAG," EventUtils-getEventList()   Range start:" + startTime);
    Log.i(TAG," EventUtils-getEventList()   Range end:" +endTime);
    Log.i(TAG," EventUtils-getEventList()   Range start:" + dateFormat.format(startTime));
    Log.i(TAG," EventUtils-getEventList()   Range end:" + dateFormat.format(endTime));

    UsageStatsManager mUsmManager = (UsageStatsManager) context.getSystemService("usagestats");
    UsageEvents events = mUsmManager.queryEvents(startTime, endTime);

    while (events.hasNextEvent()) {
        UsageEvents.Event e = new UsageEvents.Event();
        events.getNextEvent(e);
        if (e != null && (e.getEventType() == 1 || e.getEventType() == 2)) {
            Log.i(TAG," EventUtils-getEventList()  "+e.getTimeStamp()+"   event:" + e.getClassName() + "   type = " + e.getEventType());
            mEventList.add(e);
        }
    }

    return mEventList;
}
 
Example #18
Source File: UStats.java    From batteryhub with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: Tools.java    From Hangar with GNU General Public License v3.0 5 votes vote down vote up
@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 #20
Source File: UStats.java    From AppPlus with MIT License 5 votes vote down vote up
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 #21
Source File: AppUsageStatisticsFragment.java    From android-AppUsageStatistics with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mUsageStatsManager = (UsageStatsManager) getActivity()
            .getSystemService("usagestats"); //Context.USAGE_STATS_SERVICE
}
 
Example #22
Source File: AppUsageStatisticsFragmentTests.java    From android-AppUsageStatistics with Apache License 2.0 5 votes vote down vote up
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 #23
Source File: AppUsageStatisticsFragmentTests.java    From android-AppUsageStatistics with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: RunningTasksLollipop.java    From AcDisplay with GNU General Public License v2.0 5 votes vote down vote up
@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 #25
Source File: LogSectionPower.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public @NonNull CharSequence getContent(@NonNull Context context) {
  final UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);

  if (usageStatsManager == null) {
    return "UsageStatsManager not available";
  }

  BucketInfo info = BucketInfo.getInfo(usageStatsManager, TimeUnit.DAYS.toMillis(3));

  return new StringBuilder().append("Current bucket: ").append(BucketInfo.bucketToString(info.getCurrentBucket())).append('\n')
                            .append("Highest bucket: ").append(BucketInfo.bucketToString(info.getBestBucket())).append('\n')
                            .append("Lowest bucket : ").append(BucketInfo.bucketToString(info.getWorstBucket())).append("\n\n")
                            .append(info.getHistory());
}
 
Example #26
Source File: AppChangeDetectionService.java    From ScreenShift with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    startThread();
    mOnForegroundAppChangedListener = new OnForegroundAppChangedListenerImpl(this);
    mActivityManager = (ActivityManager) getBaseContext().getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        mUsageStatsManager = (UsageStatsManager) this.getSystemService(Context.USAGE_STATS_SERVICE);
    }
    super.onCreate();
}
 
Example #27
Source File: ClonedHiddenSystemApps.java    From island with Apache License 2.0 5 votes vote down vote up
/** 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());
}
 
Example #28
Source File: BaseMethod.java    From KeyBlocker with GNU General Public License v3.0 5 votes vote down vote up
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};
}
 
Example #29
Source File: AccessibilityUtil.java    From RelaxFinger with GNU General Public License v2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static boolean isUsageAccess() {
    long ts = System.currentTimeMillis();
    UsageStatsManager usageStatsManager = (UsageStatsManager)
            context.getSystemService(USAGE_STATS_SERVICE);
    List queryUsageStats = usageStatsManager.queryUsageStats(
            UsageStatsManager.INTERVAL_BEST, 0, ts);
    if (queryUsageStats == null || queryUsageStats.isEmpty()) {
        return false;
    }
    return true;
}
 
Example #30
Source File: TaskbarController.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
void filterForegroundApp(Context context,
                         SharedPreferences pref,
                         long searchInterval,
                         List<String> applicationIdsToRemove) {
    if (pref.getBoolean(PREF_HIDE_FOREGROUND, false)) {
        UsageStatsManager mUsageStatsManager =
                (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        UsageEvents events =
                mUsageStatsManager.queryEvents(searchInterval, System.currentTimeMillis());
        UsageEvents.Event eventCache = new UsageEvents.Event();
        String currentForegroundApp = null;

        while (events.hasNextEvent()) {
            events.getNextEvent(eventCache);

            if (eventCache.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                if (!(eventCache.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID)
                        && !eventCache.getClassName().equals(MainActivity.class.getCanonicalName())
                        && !eventCache.getClassName().equals(HomeActivity.class.getCanonicalName())
                        && !eventCache.getClassName().equals(HomeActivityDelegate.class.getCanonicalName())
                        && !eventCache.getClassName().equals(SecondaryHomeActivity.class.getCanonicalName())
                        && !eventCache.getClassName().equals(InvisibleActivityFreeform.class.getCanonicalName()))) {
                    currentForegroundApp = eventCache.getPackageName();
                }
            }
        }

        if (!applicationIdsToRemove.contains(currentForegroundApp)) {
            applicationIdsToRemove.add(currentForegroundApp);
        }
    }
}