Java 类android.app.usage.UsageStats 实例源码

项目:Brevent    文件:BreventActivity.java   
private void retrieveStats() {
    UsageStatsManager manager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
    List<UsageStats> stats = manager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,
            BEGIN, System.currentTimeMillis());
    if (stats == null) {
        UILog.i("no stats");
        return;
    }
    for (UsageStats stat : stats) {
        String packageName = stat.getPackageName();
        int key = mStats.indexOfKey(packageName);
        if (key >= 0) {
            mStats.valueAt(key).add(stat);
        } else {
            mStats.put(packageName, new UsageStats(stat));
        }
    }
}
项目:Brevent    文件:AppsItemAdapter.java   
static void updateDescription(BreventActivity activity, AppsItemViewHolder viewHolder) {
    String description = activity.getDescription(viewHolder.packageName);
    if (description != null) {
        viewHolder.descriptionView.setText(description);
    } else if (activity.hasStats()) {
        UsageStats stats = activity.getStats(viewHolder.packageName);
        if (stats == null) {
            viewHolder.descriptionView.setText(R.string.process_no_stats);
        } else {
            viewHolder.descriptionView.setText(activity.getString(R.string.process_stats,
                    DateUtils.formatSameDayTime(stats.getLastTimeUsed(),
                            System.currentTimeMillis(), DateFormat.SHORT, DateFormat.SHORT),
                    DateUtils.formatElapsedTime(stats.getTotalTimeInForeground() / 1000)));
        }
    } else {
        viewHolder.descriptionView.setText(R.string.process_not_running);
    }
}
项目:XPrivacy    文件:XUsageStatsManager.java   
@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;
    }
}
项目:smarper    文件:XUsageStatsManager.java   
@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;
    }
}
项目:Enhancer-For-GO    文件:MainService.java   
@Override
public boolean isGoRunning() {
    if (android.os.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;
}
项目:Taskbar    文件:TaskbarService.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private List<AppEntry> getAppEntriesUsingUsageStats() {
    UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
    List<UsageStats> usageStatsList = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_YEARLY, 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;
}
项目:More-For-GO    文件:MainService.java   
@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;
}
项目:FingerTrans    文件:AppUtils.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static String queryUsageStats() {
    String packageName=null;
    UsageStatsManager usm = (UsageStatsManager) FingerApp.get().getSystemService(Context.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.isEmpty()) {
             packageName = mySortedMap.get(
                    mySortedMap.lastKey()).getPackageName();
        }
    }
    return packageName;
}
项目:MobileGuard    文件:ProcessManagerEngine.java   
/**
 * 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;
}
项目:GrabQQPWD    文件:BackgroundDetectService.java   
@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 "";
}
项目:xprivacy-mod    文件:XUsageStatsManager.java   
@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;
    }
}
项目:AndroidProject    文件:BaseActivity.java   
/**
 *
 * 通过UsageStatsManager来判断
 *
 * @return
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean isRunningForeground5() {
    if(Build.VERSION.SDK_INT >= 21){
        long ts = System.currentTimeMillis();
        UsageStatsManager usageStatsManager = (UsageStatsManager)
                getApplicationContext().getSystemService(Context.USAGE_STATS_SERVICE);
        List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(
                UsageStatsManager.INTERVAL_BEST, ts - 2000, ts);
        if (queryUsageStats == null || queryUsageStats.isEmpty()) {
            return false;
        }
        UsageStats recentStats = null;
        for (UsageStats usageStats : queryUsageStats) {
            if (recentStats == null ||
                    recentStats.getLastTimeUsed() < usageStats.getLastTimeUsed())
            {
                recentStats = usageStats;
            }
        }
        if(getPackageName().equals(recentStats.getPackageName())){
            return true;
        }
    }
    return false;
}
项目:AppPlus    文件:DataHelper.java   
@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;
        }
    });
}
项目:AppPlus    文件:AppInfoEngine.java   
@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;
}
项目:Android_AutoSignInTool    文件:Utils.java   
public static String getTopApp(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // 5.0及之后的方法
        UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        if (usm != null) {
            long now = System.currentTimeMillis();
            // 获取40秒之内的应用程序使用状态
            List<UsageStats> stats = usm.queryUsageStats(UsageStatsManager.INTERVAL_BEST, now - 40 * 1000, now);
            String topActivity = "";
            // 获取最新运行的程序
            if ((stats != null) && (!stats.isEmpty())) {
                int j = 0;
                for (int i = 0; i < stats.size(); i++) {
                    if (stats.get(i).getLastTimeUsed() > stats.get(j).getLastTimeUsed()) {
                        j = i;
                    }
                }
                topActivity = stats.get(j).getPackageName();
                return topActivity;
            }
        }
    } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){ // 5.0之前的方法
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = activityManager.getRunningTasks(1).get(0).topActivity;
        return cn.getPackageName();
    }
    return "Not found!";
}
项目:lockit    文件:AppLockService.java   
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();
}
项目:screenfilter    文件:CurrentAppMonitoringThread.java   
@Nullable
public static String getCurrentAppUsingUsageStats(Context context) {
    try {
        if (Build.VERSION.SDK_INT >= 21) {
            // Although the UsageStatsManager was added in API 21, the
            // constant to specify it wasn't added until API 22.
            // So we use the value of that constant on API 21.
            String usageStatsServiceString;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                usageStatsServiceString = (atLeastAPI(22)) ? Context.USAGE_STATS_SERVICE : "usagestats";
            } else {
                usageStatsServiceString = "usagestats";
            }
            @SuppressWarnings("WrongConstant")
            UsageStatsManager usm = (UsageStatsManager) context.getSystemService(usageStatsServiceString);
            long time = System.currentTimeMillis();
            List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);

            if (appList != null && appList.size() > 0) {
                TreeMap<Long, UsageStats> mySortedMap = new TreeMap<>();
                for (UsageStats usageStats : appList) {
                    mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
                }
                if (!mySortedMap.isEmpty()) {
                    return mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                }
            }
        }
    } catch (Exception e) {
        // Ignore exceptions to allow the user to determine if it
        // works him/herself
    }

    return null;
}
项目:RecentTask    文件:RunningTaskUtil.java   
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);
        if (stats.size()==0){
            return true;
        }else {
            return false;
        }
    }else {
        return false;
    }
}
项目:Mount    文件:PolicyUtils.java   
@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;
}
项目:Bigbang    文件:RunningTaskUtil.java   
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);
        if (stats.size()==0){
            return true;
        }else {
            return false;
        }
    }else {
        return false;
    }
}
项目:Accessibility    文件:PackageUsageHelper.java   
/**
     * 获取系统中所有应用的使用数据,不一定能读全
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static List<UsageStats> getPackageUsageStats(Context context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            long endt = calendar.getTimeInMillis();//结束时间
            calendar.add(Calendar.DAY_OF_YEAR, -2);//时间间隔为两年
            long statt = calendar.getTimeInMillis();//开始时间
            UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
            List<UsageStats> queryUsageStats = null;
            try {
                queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_YEARLY, statt, endt);
            } catch (Throwable e) {
//                360 1509-A00 6.0.1(23)、QiKU 8676-A01 5.1(22)、360 1505-A02 6.0.1(23)
//                java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.os.IBinder.transact(int, android.os.Parcel, android.os.Parcel, int)' on a null object reference
//                at android.content.pm.ParceledListSlice.(ParceledListSlice.java:97)
//                at android.content.pm.ParceledListSlice.(ParceledListSlice.java:41)
//                at android.content.pm.ParceledListSlice$2.createFromParcel(ParceledListSlice.java:200)
//                at android.content.pm.ParceledListSlice$2.createFromParcel(ParceledListSlice.java:198)
//                at android.app.usage.IUsageStatsManager$Stub$Proxy.queryUsageStats(IUsageStatsManager.java:184)
//                at android.app.usage.UsageStatsManager.queryUsageStats(UsageStatsManager.java:133)
//                at com.qihoo.utils.PackageUsageHelper.getPackageUsageStats(AppStore:161)
//                at com.qihoo.utils.PackageUsageHelper.getPackageUsageTime(AppStore:188)
//                at com.qihoo.express.mini.support.ApkWatcherData.getApkShowTimes(AppStore:87)
//                at com.qihoo.appstore.localapkinfo.LocalApkInfoDb.initLocalApkSimpleInfo(AppStore:268)
//                at com.qihoo.appstore.localapkinfo.LocalApkInfoDb.LoadAllSimpleApkInfo(AppStore:314)
//                at com.qihoo.appstore.localapkinfo.LocalApkInfoDb.loadAllApkInfo(AppStore:100)
//                at com.qihoo.appstore.localapkinfo.LocalApkMgr$5.run(AppStore:442)
//                at com.qihoo.utils.thread.LooperThread.run(AppStore:38)
                if (LogUtils.isDebug()) {
                    LogUtils.e(PackageUsageHelper.class.getName(), "getPackageUsageStats", e);
                }
            }
            return queryUsageStats;
        }else{
            return null;
        }
    }
项目:Accessibility    文件:PackageUsageHelper.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static long getPackageStartTime(Context context,String packageName){
    long cTime = System.currentTimeMillis();
    List<UsageStats> result = getPackageUsageStats(context);
    if (result != null) {
        for (UsageStats stat : result) {
            if (packageName.equalsIgnoreCase(stat.getPackageName())) {
                if (cTime - stat.getLastTimeUsed() < 5) {
                    return stat.getLastTimeUsed();
                }
            }
        }
    }
    return 0;
}
项目:content-farm-blocker-android    文件:C.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Nullable
private static String getRunningApp(Context mContext) {
    String topPackageName = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        //noinspection WrongConstant
        UsageStatsManager mUsageStatsManager = (UsageStatsManager) mContext.getSystemService("usagestats");
        long time = System.currentTimeMillis();
        // We get usage stats for the last 10 seconds
        List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 10, time);
        // Sort the stats by the last time used
        if (stats != null) {
            SortedMap<Long, String> mySortedMap = new TreeMap<>();
            for (UsageStats usageStats : stats) {
                mySortedMap.put(usageStats.getLastTimeUsed(), usageStats.getPackageName());
            }
            if (!mySortedMap.isEmpty()) {
                do {
                    topPackageName = mySortedMap.get(mySortedMap.lastKey());
                    if (mContext.getPackageName().equals(topPackageName) || "android".equals(topPackageName)) {
                        mySortedMap.remove(mySortedMap.lastKey());

                        if (mySortedMap.isEmpty())
                            break;
                    } else {
                        break;
                    }
                } while (true);
            }
        }
    }
    return topPackageName;
}
项目:AlwaysOnDisplayAmoled    文件:CurrentAppResolver.java   
@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();
}
项目:AndroidProcess    文件:BackgroundUtil.java   
/**
 * 方法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;
    }
}
项目:AndroidTcpdumpGui    文件:CaptureManager.java   
public String getForegroundAppName(Context context) {

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

            if(needPermissionForBlocking(context)) {
                Toast.makeText(context, "Turn on Settings->Security->[Apps with usage access]", Toast.LENGTH_SHORT).show();
            }

            // intentionally using string value as Context.USAGE_STATS_SERVICE was
            // strangely only added in API 22 (LOLLIPOP_MR1)
            @SuppressWarnings("WrongConstant")
            UsageStatsManager usm = (UsageStatsManager) context.getSystemService("usagestats");
            long now = System.currentTimeMillis();
            List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, now - 1000 * 1000, now);
            if (usageStatsList != null && usageStatsList.size() > 0) {
                long time = 0;
                String name = "";
                for(UsageStats usageStats : usageStatsList) {
                    if(usageStats.getLastTimeUsed() > time) {
                        time = usageStats.getLastTimeUsed();
                        name = usageStats.getPackageName();
                    }
                }
                return name;
            }
        } else {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            try {
                ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
                return foregroundTaskInfo.topActivity.getPackageName();
            } catch (Exception e) {
                Log.e(TAG, "can not get foreground app: " + e.getMessage(), e);
            }
        }
        return "";
    }
项目:kill-you-power-consumer    文件:KillerAction.java   
public List<UsageStats> usageEnabled() {
    long ts = System.currentTimeMillis();
    UsageStatsManager usageStatsManager = (UsageStatsManager) mContext
            .getApplicationContext().getSystemService("usagestats");
    List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(
            UsageStatsManager.INTERVAL_BEST, 0, ts);

    return queryUsageStats;
}
项目:batteryhub    文件:UStats.java   
@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);
}
项目:AppPlus    文件:UStats.java   
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;
}
项目:AppPlus    文件:UStats.java   
public static void printUsageStats(List<UsageStats> usageStatsList){
    for (UsageStats u : usageStatsList){
        Log.d(TAG, "Pkg: " + u.getPackageName() +  "\t" + "ForegroundTime: "
                + u.getTotalTimeInForeground()) ;
    }

}
项目:AppPlus    文件:AppInfoEngine.java   
@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;
}
项目:EasyLock    文件:EasyLockService.java   
private String getForegroundAppPackage(){
    String foregroundTaskPackageName = "";
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        long time = System.currentTimeMillis();
        List<UsageStats> appList = mUsageStatsManager
                .queryUsageStats(UsageStatsManager.INTERVAL_DAILY,  time - 1000*100, 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()) {
                foregroundTaskPackageName = mySortedMap
                        .get(mySortedMap.lastKey()).getPackageName();
            }
        }
    } else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        List<ActivityManager.RunningAppProcessInfo> tasks =
                mActivityManager.getRunningAppProcesses();
        foregroundTaskPackageName = tasks.get(0).processName;
    } else {
        @SuppressWarnings("deprecation")
        ActivityManager.RunningTaskInfo foregroundTaskInfo = mActivityManager.getRunningTasks(1).get(0);
        foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
    }
    return foregroundTaskPackageName;
}
项目:App-Monitor    文件:UStats.java   
public static List<UsageStats> getUsageStatsList(Context context){
    UsageStatsManager usm = getUsageStatsManager(context);
    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));

    List<UsageStats> usageStatsList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,startTime,endTime);
    return usageStatsList;
}
项目:App-Monitor    文件:UStats.java   
public static void printUsageStats(List<UsageStats> usageStatsList){
    for (UsageStats u : usageStatsList){
        Log.d(TAG, "Pkg: " + u.getPackageName() +  "\t" + "ForegroundTime: "
                + u.getTotalTimeInForeground()) ;
    }

}
项目:App-Monitor    文件:AppNameComparator.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public final int compare(UsageStats a, UsageStats b) {
    String alabel = mAppLabelList.get(a.getPackageName());
    String blabel = mAppLabelList.get(b.getPackageName());
    return alabel.compareTo(blabel);
}
项目:App-Monitor    文件:Sorting.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    AppViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.list_item_icon_duration, null);

        holder = new AppViewHolder();
        holder.pkgName = (TextView) convertView.findViewById(R.id.text);
        //holder.lastTimeUsed = (TextView) convertView.findViewById(R.id.last_time_used);
        holder.usageTime = (TextView) convertView.findViewById(R.id.duration);
        holder.imgViAppIcon = (ImageView) convertView.findViewById(R.id.icon);
        convertView.setTag(holder);
    } else {

        holder = (AppViewHolder) convertView.getTag();
    }

    UsageStats pkgStats = mPackageStats.get(position);
    if (pkgStats != null) {
        String label = mAppLabelMap.get(pkgStats.getPackageName());
        holder.pkgName.setText(label);
        try {
            Drawable icon = mPm.getApplicationIcon(pkgStats.getPackageName());
            holder.imgViAppIcon.setImageDrawable(icon);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        holder.usageTime.setText(
                DateUtils.formatElapsedTime(pkgStats.getTotalTimeInForeground() / 1000));
    } else {
        Log.w(TAG, "No usage stats info for package:" + position);
    }
    return convertView;
}
项目:OpenLinkWith    文件:ResolverModule.java   
private static Map<String, UsageStats> usageStatsFrom(Context context) {
    if (SDK_INT >= LOLLIPOP_MR1) {
        UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);

        final long sinceTime = System.currentTimeMillis() - USAGE_STATS_PERIOD;
        return usageStatsManager.queryAndAggregateUsageStats(sinceTime, System.currentTimeMillis());
    } else {
        return null;
    }
}
项目:OpenLinkWith    文件:ResolverComparator.java   
ResolverComparator(PackageManager packageManager,
                   ChooserHistory history,
                   Map<String, UsageStats> usageStatsMap,
                   Map<String, Integer> priorityPackages,
                   Intent sourceIntent) {
    this.packageManager = packageManager;
    this.history = history;
    this.usageStatsMap = usageStatsMap;
    this.priorityPackages = priorityPackages;
    this.collator = Collator.getInstance(Locale.getDefault());
    this.isHttp = Intents.isHttp(sourceIntent);
}
项目:OpenLinkWith    文件:ResolverComparator.java   
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private long getPackageTimeSpent(String packageName) {
    if (usageStatsMap != null) {
        final UsageStats stats = usageStatsMap.get(packageName);
        if (stats != null) {
            return stats.getTotalTimeInForeground();
        }

    }
    return 0;
}
项目:OpenLinkWith    文件:CallerPackageExtractor.java   
@Override
@Nullable
public String extract() {
    List<UsageStats> stats = recentUsageStats(usageStatsManager);
    if (stats == null) {
        return null;
    }

    return mostRecentPackage(stats);
}