Search in sources :

Example 21 with UsageStats

use of android.app.usage.UsageStats in project AndroidUtilCode by Blankj.

the class ProcessUtils method getForegroundProcessName.

/**
     * 获取前台线程包名
     * <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> infos = manager.getRunningAppProcesses();
    if (infos != null && infos.size() != 0) {
        for (ActivityManager.RunningAppProcessInfo info : infos) {
            if (info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return info.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;
}
Also used : ApplicationInfo(android.content.pm.ApplicationInfo) Intent(android.content.Intent) UsageStats(android.app.usage.UsageStats) ActivityManager(android.app.ActivityManager) ResolveInfo(android.content.pm.ResolveInfo) AppOpsManager(android.app.AppOpsManager) PackageManager(android.content.pm.PackageManager) UsageStatsManager(android.app.usage.UsageStatsManager)

Example 22 with UsageStats

use of android.app.usage.UsageStats in project android_frameworks_base by AOSPA.

the class ResolverComparator method compute.

public void compute(List<ResolvedComponentInfo> targets) {
    mScoredTargets.clear();
    final long recentSinceTime = mCurrentTime - RECENCY_TIME_PERIOD;
    long mostRecentlyUsedTime = recentSinceTime + 1;
    long mostTimeSpent = 1;
    int mostLaunched = 1;
    for (ResolvedComponentInfo target : targets) {
        final ScoredTarget scoredTarget = new ScoredTarget(target.getResolveInfoAt(0).activityInfo);
        mScoredTargets.put(target.name, scoredTarget);
        final UsageStats pkStats = mStats.get(target.name.getPackageName());
        if (pkStats != null) {
            // Persistent processes muck this up, so omit them too.
            if (!target.name.getPackageName().equals(mReferrerPackage) && !isPersistentProcess(target)) {
                final long lastTimeUsed = pkStats.getLastTimeUsed();
                scoredTarget.lastTimeUsed = lastTimeUsed;
                if (lastTimeUsed > mostRecentlyUsedTime) {
                    mostRecentlyUsedTime = lastTimeUsed;
                }
            }
            final long timeSpent = pkStats.getTotalTimeInForeground();
            scoredTarget.timeSpent = timeSpent;
            if (timeSpent > mostTimeSpent) {
                mostTimeSpent = timeSpent;
            }
            final int launched = pkStats.mLaunchCount;
            scoredTarget.launchCount = launched;
            if (launched > mostLaunched) {
                mostLaunched = launched;
            }
        }
    }
    if (DEBUG) {
        Log.d(TAG, "compute - mostRecentlyUsedTime: " + mostRecentlyUsedTime + " mostTimeSpent: " + mostTimeSpent + " recentSinceTime: " + recentSinceTime + " mostLaunched: " + mostLaunched);
    }
    for (ScoredTarget target : mScoredTargets.values()) {
        final float recency = (float) Math.max(target.lastTimeUsed - recentSinceTime, 0) / (mostRecentlyUsedTime - recentSinceTime);
        final float recencyScore = recency * recency * RECENCY_MULTIPLIER;
        final float usageTimeScore = (float) target.timeSpent / mostTimeSpent;
        final float launchCountScore = (float) target.launchCount / mostLaunched;
        target.score = recencyScore + usageTimeScore + launchCountScore;
        if (DEBUG) {
            Log.d(TAG, "Scores: recencyScore: " + recencyScore + " usageTimeScore: " + usageTimeScore + " launchCountScore: " + launchCountScore + " - " + target);
        }
    }
}
Also used : UsageStats(android.app.usage.UsageStats) ResolvedComponentInfo(com.android.internal.app.ResolverActivity.ResolvedComponentInfo)

Example 23 with UsageStats

use of android.app.usage.UsageStats in project android_frameworks_base by ResurrectionRemix.

the class ResolverComparator method compute.

public void compute(List<ResolvedComponentInfo> targets) {
    mScoredTargets.clear();
    final long recentSinceTime = mCurrentTime - RECENCY_TIME_PERIOD;
    long mostRecentlyUsedTime = recentSinceTime + 1;
    long mostTimeSpent = 1;
    int mostLaunched = 1;
    for (ResolvedComponentInfo target : targets) {
        final ScoredTarget scoredTarget = new ScoredTarget(target.getResolveInfoAt(0).activityInfo);
        mScoredTargets.put(target.name, scoredTarget);
        final UsageStats pkStats = mStats.get(target.name.getPackageName());
        if (pkStats != null) {
            // Persistent processes muck this up, so omit them too.
            if (!target.name.getPackageName().equals(mReferrerPackage) && !isPersistentProcess(target)) {
                final long lastTimeUsed = pkStats.getLastTimeUsed();
                scoredTarget.lastTimeUsed = lastTimeUsed;
                if (lastTimeUsed > mostRecentlyUsedTime) {
                    mostRecentlyUsedTime = lastTimeUsed;
                }
            }
            final long timeSpent = pkStats.getTotalTimeInForeground();
            scoredTarget.timeSpent = timeSpent;
            if (timeSpent > mostTimeSpent) {
                mostTimeSpent = timeSpent;
            }
            final int launched = pkStats.mLaunchCount;
            scoredTarget.launchCount = launched;
            if (launched > mostLaunched) {
                mostLaunched = launched;
            }
        }
    }
    if (DEBUG) {
        Log.d(TAG, "compute - mostRecentlyUsedTime: " + mostRecentlyUsedTime + " mostTimeSpent: " + mostTimeSpent + " recentSinceTime: " + recentSinceTime + " mostLaunched: " + mostLaunched);
    }
    for (ScoredTarget target : mScoredTargets.values()) {
        final float recency = (float) Math.max(target.lastTimeUsed - recentSinceTime, 0) / (mostRecentlyUsedTime - recentSinceTime);
        final float recencyScore = recency * recency * RECENCY_MULTIPLIER;
        final float usageTimeScore = (float) target.timeSpent / mostTimeSpent;
        final float launchCountScore = (float) target.launchCount / mostLaunched;
        target.score = recencyScore + usageTimeScore + launchCountScore;
        if (DEBUG) {
            Log.d(TAG, "Scores: recencyScore: " + recencyScore + " usageTimeScore: " + usageTimeScore + " launchCountScore: " + launchCountScore + " - " + target);
        }
    }
}
Also used : UsageStats(android.app.usage.UsageStats) ResolvedComponentInfo(com.android.internal.app.ResolverActivity.ResolvedComponentInfo)

Example 24 with UsageStats

use of android.app.usage.UsageStats in project android_frameworks_base by ResurrectionRemix.

the class IntervalStats method update.

void update(String packageName, long timeStamp, int eventType) {
    UsageStats usageStats = getOrCreateUsageStats(packageName);
    // like double MOVE_TO_BACKGROUND, etc.
    if (eventType == UsageEvents.Event.MOVE_TO_BACKGROUND || eventType == UsageEvents.Event.END_OF_DAY) {
        if (usageStats.mLastEvent == UsageEvents.Event.MOVE_TO_FOREGROUND || usageStats.mLastEvent == UsageEvents.Event.CONTINUE_PREVIOUS_DAY) {
            usageStats.mTotalTimeInForeground += timeStamp - usageStats.mLastTimeUsed;
        }
    }
    if (isStatefulEvent(eventType)) {
        usageStats.mLastEvent = eventType;
    }
    if (eventType != UsageEvents.Event.SYSTEM_INTERACTION) {
        usageStats.mLastTimeUsed = timeStamp;
    }
    usageStats.mEndTimeStamp = timeStamp;
    if (eventType == UsageEvents.Event.MOVE_TO_FOREGROUND) {
        usageStats.mLaunchCount += 1;
    }
    endTime = timeStamp;
}
Also used : UsageStats(android.app.usage.UsageStats)

Example 25 with UsageStats

use of android.app.usage.UsageStats in project android_frameworks_base by ResurrectionRemix.

the class UserUsageStatsService method init.

void init(final long currentTimeMillis) {
    mDatabase.init(currentTimeMillis);
    int nullCount = 0;
    for (int i = 0; i < mCurrentStats.length; i++) {
        mCurrentStats[i] = mDatabase.getLatestUsageStats(i);
        if (mCurrentStats[i] == null) {
            // Find out how many intervals we don't have data for.
            // Ideally it should be all or none.
            nullCount++;
        }
    }
    if (nullCount > 0) {
        if (nullCount != mCurrentStats.length) {
            // This is weird, but we shouldn't fail if something like this
            // happens.
            Slog.w(TAG, mLogPrefix + "Some stats have no latest available");
        } else {
        // This must be first boot.
        }
        // By calling loadActiveStats, we will
        // generate new stats for each bucket.
        loadActiveStats(currentTimeMillis);
    } else {
        // Set up the expiry date to be one day from the latest daily stat.
        // This may actually be today and we will rollover on the first event
        // that is reported.
        updateRolloverDeadline();
    }
    // Now close off any events that were open at the time this was saved.
    for (IntervalStats stat : mCurrentStats) {
        final int pkgCount = stat.packageStats.size();
        for (int i = 0; i < pkgCount; i++) {
            UsageStats pkgStats = stat.packageStats.valueAt(i);
            if (pkgStats.mLastEvent == UsageEvents.Event.MOVE_TO_FOREGROUND || pkgStats.mLastEvent == UsageEvents.Event.CONTINUE_PREVIOUS_DAY) {
                stat.update(pkgStats.mPackageName, stat.lastTimeSaved, UsageEvents.Event.END_OF_DAY);
                notifyStatsChanged();
            }
        }
        stat.updateConfigurationStats(null, stat.lastTimeSaved);
    }
    if (mDatabase.isNewUpdate()) {
        notifyNewUpdate();
    }
}
Also used : UsageStats(android.app.usage.UsageStats)

Aggregations

UsageStats (android.app.usage.UsageStats)31 Configuration (android.content.res.Configuration)8 ResolvedComponentInfo (com.android.internal.app.ResolverActivity.ResolvedComponentInfo)5 ConfigurationStats (android.app.usage.ConfigurationStats)4 UsageEvents (android.app.usage.UsageEvents)4 Event (android.app.usage.UsageEvents.Event)4 ArraySet (android.util.ArraySet)4 ProtocolException (java.net.ProtocolException)4 UsageStatsManager (android.app.usage.UsageStatsManager)2 Intent (android.content.Intent)2 TargetApi (android.annotation.TargetApi)1 ActivityManager (android.app.ActivityManager)1 AppOpsManager (android.app.AppOpsManager)1 ApplicationInfo (android.content.pm.ApplicationInfo)1 PackageManager (android.content.pm.PackageManager)1 ResolveInfo (android.content.pm.ResolveInfo)1 Comparator (java.util.Comparator)1