Java Code Examples for android.app.usage.UsageStats#getPackageName()

The following examples show how to use android.app.usage.UsageStats#getPackageName() . 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: 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 2
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 3
Source File: AppInfoEngine.java    From AppPlus with MIT License 6 votes vote down vote up
@Deprecated
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public List<AppEntity> getRecentAppInfo(){
    List<UsageStats> usageStatsList = getUsageStatsList();
    List<AppEntity> list = new ArrayList<>();
    for (UsageStats u : usageStatsList){
        String packageName = u.getPackageName();
        ApplicationInfo applicationInfo = getAppInfo(packageName);
        //system app will not appear recent list
        //if(isSystemApp(packageName))continue;
        if (isShowSelf(packageName)) continue;
        AppEntity entity = DataHelper.getAppByPackageName(packageName);
        if (entity == null)continue;
        list.add (entity);
    }
    return list;
}
 
Example 4
Source File: RunningTasksLollipop.java    From AcDisplay with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Nullable
public String getRunningTasksTop(@NonNull Context context) {
    try {
        UsageStats usageStats = getUsageStatsTop(context);
        return usageStats != null ? usageStats.getPackageName() : null;
    } catch (SecurityException e) {
        Log.e(TAG, "Failed to get usage stats! Permissions denied!");
        e.printStackTrace();
    }
    return null;
}
 
Example 5
Source File: Tools.java    From Hangar with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
    public static LollipopTaskInfo parseUsageStats(List<UsageStats> stats, LollipopTaskInfo lollipopTaskInfo) {
        UsageStats aRunner = stats.get(0);
        UsageStats bRunner = null;

        if (lollipopTaskInfo == null) {
            // setup new lollipopTaskInfo object!

            lollipopTaskInfo = new Tools.LollipopTaskInfo(aRunner.getPackageName());
        } else if (lollipopTaskInfo.packageName.equals(aRunner.getPackageName())) {
//            Tools.HangarLog("Last package same as current top, skipping! [" + lollipopTaskInfo.packageName + "]");
            return lollipopTaskInfo;
        }

        // TODO change this to keep track of all usagestats and compare timeinFg deltas
        // Will need to refactor buildTasks to manage bulk time change to db as well as
        // new runningTask.

        for (UsageStats s : stats) {
            if (s.getPackageName().equals(lollipopTaskInfo.packageName)) {
                bRunner = s;
            }
        }

        lollipopTaskInfo.lastPackageName = lollipopTaskInfo.packageName;
        lollipopTaskInfo.packageName = aRunner.getPackageName();
        if (bRunner == null) {
            Tools.HangarLog("Couldn't find previous task [" + lollipopTaskInfo.packageName + "]");
        } else {
            lollipopTaskInfo.timeInFGDelta = (lollipopTaskInfo.timeInFG > 0) ? bRunner.getTotalTimeInForeground() - lollipopTaskInfo.timeInFG : 0;
        }
        lollipopTaskInfo.timeInFG = aRunner.getTotalTimeInForeground();

        Tools.HangarLog("New [" + lollipopTaskInfo.packageName + "] old [" + lollipopTaskInfo.lastPackageName + "] old FG delta: " + lollipopTaskInfo.timeInFGDelta);

        return lollipopTaskInfo;
    }
 
Example 6
Source File: WatchfulService.java    From Hangar with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
protected void buildLBaseTasks() {
    Context context = getApplicationContext();
    List<UsageStats> stats = Tools.getUsageStats(context);

    for (UsageStats task : stats) {
        String taskPackage = task.getPackageName();
        String taskClass = getClassName(context, taskPackage);
        Tools.HangarLog("buildLBaseTask: package: " + taskPackage + " class: " + taskClass);
        buildTaskInfo(taskClass, taskPackage);
    }
}
 
Example 7
Source File: CacheQuotaStrategy.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a list of CacheQuotaHints which do not have their quotas filled out for apps
 * which have been used in the last year.
 */
private List<CacheQuotaHint> getUnfulfilledRequests() {
    long timeNow = System.currentTimeMillis();
    long oneYearAgo = timeNow - DateUtils.YEAR_IN_MILLIS;

    List<CacheQuotaHint> requests = new ArrayList<>();
    UserManager um = mContext.getSystemService(UserManager.class);
    final List<UserInfo> users = um.getUsers();
    final int userCount = users.size();
    final PackageManager packageManager = mContext.getPackageManager();
    for (int i = 0; i < userCount; i++) {
        UserInfo info = users.get(i);
        List<UsageStats> stats =
                mUsageStats.queryUsageStatsForUser(info.id, UsageStatsManager.INTERVAL_BEST,
                        oneYearAgo, timeNow, /*obfuscateInstantApps=*/ false);
        if (stats == null) {
            continue;
        }

        for (UsageStats stat : stats) {
            String packageName = stat.getPackageName();
            try {
                // We need the app info to determine the uid and the uuid of the volume
                // where the app is installed.
                ApplicationInfo appInfo = packageManager.getApplicationInfoAsUser(
                        packageName, 0, info.id);
                requests.add(
                        new CacheQuotaHint.Builder()
                                .setVolumeUuid(appInfo.volumeUuid)
                                .setUid(appInfo.uid)
                                .setUsageStats(stat)
                                .setQuota(CacheQuotaHint.QUOTA_NOT_SET)
                                .build());
            } catch (PackageManager.NameNotFoundException e) {
                // This may happen if an app has a recorded usage, but has been uninstalled.
                continue;
            }
        }
    }
    return requests;
}
 
Example 8
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 "";
}
 
Example 9
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 10
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 11
Source File: TaskController.java    From batteryhub with Apache License 2.0 4 votes vote down vote up
@TargetApi(21)
private List<Task> getRunningTasksNougat() {
    final List<Task> tasks = new ArrayList<>();

    AppOpsManager appOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
    int mode = appOps.checkOpNoThrow(
            "android:get_usage_stats",
            Process.myUid(), mContext.getPackageName()
    );
    boolean granted = mode == AppOpsManager.MODE_ALLOWED;

    if (!granted) return tasks;

    final List<UsageStats> list = UStats.getUsageStatsList(mContext);

    for (UsageStats stats : list) {
        String packageName = stats.getPackageName();
        /* Exclude the app itself from the list */
        if (packageName.equals(BuildConfig.APPLICATION_ID)) continue;

        PackageInfo packageInfo = getPackageInfo(packageName, 0);

        if (packageInfo == null) continue;

        /** Remove system apps if necessary */
        if (isSystemApp(packageInfo) && SettingsUtils.isSystemAppsHidden(mContext)) {
            continue;
        }

        /** Remove apps without label */
        String appLabel = packageInfo.applicationInfo.loadLabel(mPackageManager).toString();
        if (appLabel.isEmpty()) continue;

        int uid = packageInfo.applicationInfo.uid;
        Task task = getTaskByUid(tasks, uid);

        if (task == null) {
            task = new Task(uid, packageInfo.applicationInfo.processName);
            task.setPackageInfo(packageInfo);
            task.setLabel(appLabel);
            task.setIsAutoStart(isAutoStartApp(packageName));
            task.setHasBackgroundService(hasBackgroundServices(packageName));
            tasks.add(task);
        }
    }

    // Dirty quick sorting
    Collections.sort(tasks, new Comparator<Task>() {
        @Override
        public int compare(Task t1, Task t2) {
            return t1.getLabel().compareTo(t2.getLabel());
        }
    });

    return tasks;
}