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

项目: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));
        }
    }
}
项目:AppPlus    文件:UStats.java   
@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());
        }
    }
}
项目:FCM-for-Mojo    文件:UsageStatsUtils.java   
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;
}
项目: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;
}
项目:foregroundappchecker    文件:LollipopDetector.java   
@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 ;
}
项目: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 "";
}
项目: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;
}
项目:App-Monitor    文件:UStats.java   
@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());
        }
    }
}
项目:UsageStatsSample    文件:UStats.java   
@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());
        }
    }
}
项目:LollipopExplorer    文件:UsageEventsViewerActivity.java   
@Override
protected List<UsageEventsItem> doInBackground(Void... params) {
    //noinspection ResourceType
    UsageStatsManager usageStatsMgr = (UsageStatsManager) getSystemService("usagestats");
    UsageEvents events = usageStatsMgr.queryEvents(mStartTime, mEndTime);
    List<UsageEventsItem> results = new ArrayList<>();
    UsageEvents.Event event = new UsageEvents.Event();
    PackageManager pm = getPackageManager();
    while (events.getNextEvent(event)) {
        UsageEventsItem item = new UsageEventsItem();
        item.pkgName = event.getPackageName();
        item.className = event.getClassName();
        item.type = event.getEventType();
        item.timeStamp = event.getTimeStamp();
        item.appName = item.pkgName;
        try {
            item.appName = pm.getApplicationInfo(item.pkgName, 0).loadLabel(pm).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        results.add(item);
    }
    Collections.sort(results, new UsageEventsItem.AppNameComparator());
    return results;
}
项目: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;
        }
    }
项目: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 "";
    }
项目:Night-Light    文件:NotificationService.java   
private void updateRecentApps() {
    Blacklist blacklist = Blacklist.getInstance(this);
    String currentForegroundApp = null;

    if(!U.isNightModeOn(this))
        stopSelf();
    else if(Settings.Secure.getInt(getContentResolver(), "accessibility_display_inversion_enabled", 0) == 1)
        U.setTint(this, false);
    else {
        if(blacklist.getBlockedApps().size() > 0) {
            UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
            UsageEvents events = mUsageStatsManager.queryEvents(
                    System.currentTimeMillis() - AlarmManager.INTERVAL_DAY,
                    System.currentTimeMillis());

            UsageEvents.Event eventCache = new UsageEvents.Event();

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

                if(eventCache.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND)
                    currentForegroundApp = eventCache.getPackageName();
            }
        }


        U.setTint(this, !blacklist.isBlocked(currentForegroundApp));
    }
}
项目: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);
}
项目:AppUsageWatcher    文件:WatchUtil.java   
@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
private static String getTopPackageNameAfterLollipop(Context context) {
    PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
    UsageStatsManager usageStatsManager = (UsageStatsManager)context.getSystemService(USAGE_STATS);
    if (!powerManager.isInteractive()) {
        sForegroundMap.clear();
        return null;
    }
    long time = System.currentTimeMillis();
    UsageEvents usageEvents = usageStatsManager.queryEvents(time-5000, time);
    if (null == usageEvents) {
        return null;
    }
    String packageName = null;
    while (usageEvents.hasNextEvent()) {
        UsageEvents.Event event = new UsageEvents.Event();
        usageEvents.getNextEvent(event);
        packageName = event.getPackageName();
        switch (event.getEventType()) {
        case UsageEvents.Event.MOVE_TO_FOREGROUND:
            sForegroundMap.put(packageName, Long.valueOf(event.getTimeStamp()));
            break;
        case UsageEvents.Event.MOVE_TO_BACKGROUND:
            sForegroundMap.remove(packageName);
            break;
        }
    }
    long latest = 0;
    for (Map.Entry<String, Long> entry : sForegroundMap.entrySet()) {
        long timestamp = entry.getValue().longValue();
        if (latest < timestamp) {
            packageName = entry.getKey();
            latest = timestamp;
        }
    }
    return packageName;
}
项目: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    文件: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;
}
项目: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    文件:CallerPackageExtractor.java   
/**
 * Returns recently used apps for the last 10 seconds
 */
@Nullable
private static List<UsageStats> recentUsageStats(UsageStatsManager mUsm) {
    try {
        long time = System.currentTimeMillis();
        return mUsm.queryUsageStats(
                UsageStatsManager.INTERVAL_DAILY,
                time - 10 * DateUtils.SECOND_IN_MILLIS,
                time
        );
    } catch (Exception ignored) {
    }
    return null; // queryUsageStats also returns null
}
项目:UsageStatsSample    文件: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;
}
项目:ScreenShift    文件:AppChangeDetectionService.java   
@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();
}
项目:AcDisplay    文件:RunningTasksLollipop.java   
@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;
}
项目:Hangar    文件:Tools.java   
@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;

}
项目:LollipopExplorer    文件:AppsUsageViewerActivity.java   
@Override
protected List<AppsUsageItem> doInBackground(Void... params) {
    //noinspection ResourceType
    UsageStatsManager usageStatsMgr = (UsageStatsManager) getSystemService("usagestats");
    Map<String, UsageStats> usagesList = usageStatsMgr.queryAndAggregateUsageStats(
            mStartTime, mEndTime);
    AppLogger.i(TAG, "usages stat list size: " + usagesList.size());
    List<AppsUsageItem> results = new ArrayList<AppsUsageItem>();
    PackageManager pm = getPackageManager();
    for (UsageStats usage : usagesList.values()) {
        AppsUsageItem item = new AppsUsageItem();
        item.pkgName = usage.getPackageName();
        item.lastStartup = usage.getLastTimeUsed();
        item.lastStartupStr = getString(R.string.apps_usage_last_startup,
                DateTimeUtils.generateFileName(item.lastStartup));
        item.fgTime = usage.getTotalTimeInForeground();
        item.fgTimeStr = getString(R.string.apps_usage_fg_time_used,
                DateTimeUtils.getReadableTimeUsage(item.fgTime));
        item.appName = item.pkgName;
        try {
            item.appName = pm.getApplicationInfo(item.pkgName, 0).loadLabel(pm).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        results.add(item);
    }
    Collections.sort(results, new AppsUsageItem.AppNameComparator());
    return results;
}