Java Code Examples for android.app.usage.UsageStatsManager#queryUsageStats()

The following examples show how to use android.app.usage.UsageStatsManager#queryUsageStats() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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 9
Source File: AppInfoEngine.java    From AppPlus with MIT License 5 votes vote down vote up
@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 10
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 11
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 12
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 13
Source File: CurrentAppResolver.java    From always-on-amoled with GNU General Public License v3.0 5 votes vote down vote up
@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();
}
 
Example 14
Source File: SettingsFragment.java    From ToDoList with Apache License 2.0 5 votes vote down vote up
/**
 * 判断“查看应用使用情况”是否开启
 * @return
 */
private boolean isNoSwitch() {
    long ts = System.currentTimeMillis();
    if(Build.VERSION.SDK_INT >=21){
        //noinspection ResourceType
        usageStatsManager = (UsageStatsManager)getActivity().getApplicationContext().getSystemService("usagestats");
        queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, 0, ts);
    }
    if (queryUsageStats == null || queryUsageStats.isEmpty()) {
        return false;
    }
    return true;
}
 
Example 15
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 16
Source File: Stats.java    From flutter-plugins with MIT License 5 votes vote down vote up
/** 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 17
Source File: MainActivity.java    From ToDoList with Apache License 2.0 5 votes vote down vote up
/**
 * 判断“查看应用使用情况”是否开启
 * @return
 */
private boolean isNoSwitch() {
    long ts = System.currentTimeMillis();
    if(Build.VERSION.SDK_INT >=21){
        //noinspection ResourceType
        usageStatsManager = (UsageStatsManager)this.getApplicationContext().getSystemService("usagestats");
        queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, 0, ts);
    }
    if (queryUsageStats == null || queryUsageStats.isEmpty()) {
        return false;
    }
    return true;
}
 
Example 18
Source File: ProcessUtils.java    From AndroidUtilCode with Apache License 2.0 4 votes vote down vote up
/**
 * Return the foreground process name.
 * <p>Target APIs greater than 21 must hold
 * {@code <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" />}</p>
 *
 * @return the foreground process name
 */
public static String getForegroundProcessName() {
    ActivityManager am =
            (ActivityManager) Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE);
    //noinspection ConstantConditions
    List<ActivityManager.RunningAppProcessInfo> pInfo = am.getRunningAppProcesses();
    if (pInfo != null && pInfo.size() > 0) {
        for (ActivityManager.RunningAppProcessInfo aInfo : pInfo) {
            if (aInfo.importance
                    == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return aInfo.processName;
            }
        }
    }
    if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
        PackageManager pm = Utils.getApp().getPackageManager();
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        List<ResolveInfo> list =
                pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        Log.i("ProcessUtils", list.toString());
        if (list.size() <= 0) {
            Log.i("ProcessUtils",
                    "getForegroundProcessName: noun of access to usage information.");
            return "";
        }
        try {// Access to usage information.
            ApplicationInfo info =
                    pm.getApplicationInfo(Utils.getApp().getPackageName(), 0);
            AppOpsManager aom =
                    (AppOpsManager) Utils.getApp().getSystemService(Context.APP_OPS_SERVICE);
            if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                    info.uid,
                    info.packageName) != AppOpsManager.MODE_ALLOWED) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Utils.getApp().startActivity(intent);
            }
            if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                    info.uid,
                    info.packageName) != AppOpsManager.MODE_ALLOWED) {
                Log.i("ProcessUtils",
                        "getForegroundProcessName: refuse to device usage stats.");
                return "";
            }
            UsageStatsManager usageStatsManager = (UsageStatsManager) Utils.getApp()
                    .getSystemService(Context.USAGE_STATS_SERVICE);
            List<UsageStats> usageStatsList = null;
            if (usageStatsManager != null) {
                long endTime = System.currentTimeMillis();
                long beginTime = endTime - 86400000 * 7;
                usageStatsList = usageStatsManager
                        .queryUsageStats(UsageStatsManager.INTERVAL_BEST,
                                beginTime, endTime);
            }
            if (usageStatsList == null || usageStatsList.isEmpty()) return "";
            UsageStats recentStats = null;
            for (UsageStats usageStats : usageStatsList) {
                if (recentStats == null
                        || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) {
                    recentStats = usageStats;
                }
            }
            return recentStats == null ? null : recentStats.getPackageName();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    return "";
}
 
Example 19
Source File: ProcessUtils.java    From Android-UtilCode with Apache License 2.0 4 votes vote down vote up
/**
 * 获取前台线程包名
 * <p>当不是查看当前App,且SDK大于21时,
 * 需添加权限 {@code <uses-permission android:name="android.permission.PACKAGE_USAGE_STATS"/>}</p>
 *
 * @return 前台应用包名
 */
public static String getForegroundProcessName() {
    ActivityManager manager = (ActivityManager) Utils.getContext().getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> pInfo = manager.getRunningAppProcesses();
    if (pInfo != null && pInfo.size() != 0) {
        for (ActivityManager.RunningAppProcessInfo aInfo : pInfo) {
            if (aInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return aInfo.processName;
            }
        }
    }
    if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
        PackageManager packageManager = Utils.getContext().getPackageManager();
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        System.out.println(list);
        if (list.size() > 0) {// 有"有权查看使用权限的应用"选项
            try {
                ApplicationInfo info = packageManager.getApplicationInfo(Utils.getContext().getPackageName(), 0);
                AppOpsManager aom = (AppOpsManager) Utils.getContext().getSystemService(Context.APP_OPS_SERVICE);
                if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
                    Utils.getContext().startActivity(intent);
                }
                if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
                    LogUtils.d("getForegroundApp", "没有打开\"有权查看使用权限的应用\"选项");
                    return null;
                }
                UsageStatsManager usageStatsManager = (UsageStatsManager) Utils.getContext().getSystemService(Context.USAGE_STATS_SERVICE);
                long endTime = System.currentTimeMillis();
                long beginTime = endTime - 86400000 * 7;
                List<UsageStats> usageStatses = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, beginTime, endTime);
                if (usageStatses == null || usageStatses.isEmpty()) return null;
                UsageStats recentStats = null;
                for (UsageStats usageStats : usageStatses) {
                    if (recentStats == null || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) {
                        recentStats = usageStats;
                    }
                }
                return recentStats == null ? null : recentStats.getPackageName();
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            LogUtils.d("getForegroundApp", "无\"有权查看使用权限的应用\"选项");
        }
    }
    return null;
}
 
Example 20
Source File: AppUtils.java    From Common with Apache License 2.0 4 votes vote down vote up
private static String getForegroundProcessName(final Context context) {
    ActivityManager am =
            (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> pInfo = am.getRunningAppProcesses();
    if (pInfo != null && pInfo.size() > 0) {
        for (ActivityManager.RunningAppProcessInfo aInfo : pInfo) {
            if (aInfo.importance
                    == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return aInfo.processName;
            }
        }
    }
    if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
        PackageManager pm = context.getPackageManager();
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        List<ResolveInfo> list =
                pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        Log.i("ProcessUtils", list.toString());
        if (list.size() <= 0) {
            Log.i("ProcessUtils", "getForegroundProcessName: noun of access to usage information.");
            return "";
        }
        try {
            // Access to usage information.
            ApplicationInfo info = pm.getApplicationInfo(context.getPackageName(), 0);
            AppOpsManager aom = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid,
                    info.packageName) != AppOpsManager.MODE_ALLOWED) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
            if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                    info.uid,
                    info.packageName) != AppOpsManager.MODE_ALLOWED) {
                Log.i("ProcessUtils", "getForegroundProcessName: refuse to device usage stats.");
                return "";
            }
            UsageStatsManager usageStatsManager = (UsageStatsManager) context
                    .getSystemService(Context.USAGE_STATS_SERVICE);
            List<UsageStats> usageStatsList = null;
            if (usageStatsManager != null) {
                long endTime = System.currentTimeMillis();
                long beginTime = endTime - 86400000 * 7;
                usageStatsList = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,
                        beginTime, endTime);
            }
            if (usageStatsList == null || usageStatsList.isEmpty()) return null;
            UsageStats recentStats = null;
            for (UsageStats usageStats : usageStatsList) {
                if (recentStats == null
                        || usageStats.getLastTimeUsed() > recentStats.getLastTimeUsed()) {
                    recentStats = usageStats;
                }
            }
            return recentStats == null ? null : recentStats.getPackageName();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }
    return "";
}