Search in sources :

Example 76 with UsageStats

use of android.app.usage.UsageStats in project android_packages_apps_Settings by crdroidandroid.

the class RecentAppsPreferenceControllerTest method display_hasRecentButNoneDisplayable_showAppInfo.

@Test
public void display_hasRecentButNoneDisplayable_showAppInfo() {
    when(mMockContext.getResources().getBoolean(R.bool.config_display_recent_apps)).thenReturn(true);
    final List<UsageStats> stats = new ArrayList<>();
    final UsageStats stat1 = new UsageStats();
    final UsageStats stat2 = new UsageStats();
    stat1.mLastTimeUsed = System.currentTimeMillis();
    stat1.mPackageName = "com.android.phone";
    stats.add(stat1);
    stat2.mLastTimeUsed = System.currentTimeMillis();
    stat2.mPackageName = "com.android.settings";
    stats.add(stat2);
    // stat1, stat2 are not displayable
    when(mAppState.getEntry(stat1.mPackageName, UserHandle.myUserId())).thenReturn(mock(ApplicationsState.AppEntry.class));
    when(mAppState.getEntry(stat2.mPackageName, UserHandle.myUserId())).thenReturn(mock(ApplicationsState.AppEntry.class));
    when(mMockContext.getPackageManager().resolveActivity(any(Intent.class), anyInt())).thenReturn(new ResolveInfo());
    when(mUsageStatsManager.queryUsageStats(anyInt(), anyLong(), anyLong())).thenReturn(stats);
    mController = new RecentAppsPreferenceController(mMockContext, mAppState, null);
    mController.displayPreference(mScreen);
    verify(mCategory, never()).addPreference(any(Preference.class));
    verify(mCategory).setTitle(null);
    verify(mSeeAllPref).setTitle(R.string.applications_settings);
    verify(mSeeAllPref).setIcon(null);
}
Also used : ResolveInfo(android.content.pm.ResolveInfo) Preference(android.support.v7.preference.Preference) ArrayList(java.util.ArrayList) Intent(android.content.Intent) UsageStats(android.app.usage.UsageStats) Test(org.junit.Test)

Example 77 with UsageStats

use of android.app.usage.UsageStats in project AndroidUtilLib by SiberiaDante.

the class SDProcessUtil 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) SDAndroidLib.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 = SDAndroidLib.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(SDAndroidLib.getContext().getPackageName(), 0);
                AppOpsManager aom = (AppOpsManager) SDAndroidLib.getContext().getSystemService(Context.APP_OPS_SERVICE);
                if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
                    SDAndroidLib.getContext().startActivity(intent);
                }
                if (aom.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, info.uid, info.packageName) != AppOpsManager.MODE_ALLOWED) {
                    SDToastUtil.toast("getForegroundApp---没有打开\"有权查看使用权限的应用\"选项");
                    return null;
                }
                UsageStatsManager usageStatsManager = (UsageStatsManager) SDAndroidLib.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 {
            SDToastUtil.toast("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 78 with UsageStats

use of android.app.usage.UsageStats in project robolectric by robolectric.

the class ShadowUsageStatsManagerTest method queryUsageStats_multipleIntervalTypes.

@Test
public void queryUsageStats_multipleIntervalTypes() {
    // Weekly data.
    UsageStats usageStats1 = newUsageStats(TEST_PACKAGE_NAME1, 1000, 2000);
    UsageStats usageStats2 = newUsageStats(TEST_PACKAGE_NAME1, 2001, 3000);
    shadowOf(usageStatsManager).addUsageStats(INTERVAL_WEEKLY, usageStats1);
    shadowOf(usageStatsManager).addUsageStats(INTERVAL_WEEKLY, usageStats2);
    // Daily data.
    UsageStats usageStats3 = newUsageStats(TEST_PACKAGE_NAME1, 2001, 3000);
    shadowOf(usageStatsManager).addUsageStats(INTERVAL_DAILY, usageStats3);
    List<UsageStats> results = usageStatsManager.queryUsageStats(INTERVAL_WEEKLY, 0, 3000);
    assertThat(results).containsExactly(usageStats1, usageStats2);
    results = usageStatsManager.queryUsageStats(INTERVAL_DAILY, 0, 3000);
    assertThat(results).containsExactly(usageStats3);
}
Also used : UsageStats(android.app.usage.UsageStats) Test(org.junit.Test)

Example 79 with UsageStats

use of android.app.usage.UsageStats in project robolectric by robolectric.

the class ShadowUsageStatsManager method queryUsageStats.

/**
 * Returns aggregated UsageStats added by calling {@link #addUsageStats}.
 *
 * <p>The real implementation creates these aggregated objects from individual {@link Event}. This
 * aggregation logic is nontrivial, so the shadow implementation just returns the aggregate data
 * added using {@link #addUsageStats}.
 */
@Implementation
protected List<UsageStats> queryUsageStats(int intervalType, long beginTime, long endTime) {
    List<UsageStats> results = new ArrayList<>();
    Range<Long> queryRange = Range.closed(beginTime, endTime);
    for (UsageStats stats : usageStatsByIntervalType.get(intervalType)) {
        Range<Long> statsRange = Range.closed(stats.getFirstTimeStamp(), stats.getLastTimeStamp());
        if (queryRange.isConnected(statsRange)) {
            results.add(stats);
        }
    }
    return results;
}
Also used : ArrayList(java.util.ArrayList) UsageStats(android.app.usage.UsageStats) Implementation(org.robolectric.annotation.Implementation)

Example 80 with UsageStats

use of android.app.usage.UsageStats in project Saiy-PS by brandall76.

the class UtilsApplication method getForegroundPackage21.

/**
 * Get the package name of the current foreground application
 *
 * @param ctx the application context
 * @return the package name or null
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private static String getForegroundPackage21(@NonNull final Context ctx, final long history) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "getForegroundPackage21");
    }
    try {
        @SuppressWarnings("WrongConstant") final UsageStatsManager mUsageStatsManager = (UsageStatsManager) ctx.getSystemService(USAGE_STATS_SERVICE);
        final long currentTime = System.currentTimeMillis();
        final List<UsageStats> statsList = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, currentTime - history, currentTime);
        if (UtilsList.notNaked(statsList)) {
            final SortedMap<Long, UsageStats> sortedMap = new TreeMap<>();
            for (final UsageStats usageStats : statsList) {
                sortedMap.put(usageStats.getLastTimeUsed(), usageStats);
            }
            if (!sortedMap.isEmpty()) {
                final String packageName = sortedMap.get(sortedMap.lastKey()).getPackageName();
                if (DEBUG) {
                    MyLog.i(CLS_NAME, "getForegroundPackage21: packageName: " + packageName);
                }
                return packageName;
            }
        }
    } catch (final NullPointerException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "getForegroundPackage21 NullPointerException");
            e.printStackTrace();
        }
    } catch (final IndexOutOfBoundsException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "getForegroundPackage21 IndexOutOfBoundsException");
            e.printStackTrace();
        }
    } catch (final SecurityException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "getForegroundPackage21 SecurityException");
            e.printStackTrace();
        }
    } catch (final Exception e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "getForegroundPackage21 Exception");
            e.printStackTrace();
        }
    }
    return null;
}
Also used : UsageStats(android.app.usage.UsageStats) TreeMap(java.util.TreeMap) UsageStatsManager(android.app.usage.UsageStatsManager) RequiresApi(android.support.annotation.RequiresApi)

Aggregations

UsageStats (android.app.usage.UsageStats)98 ArrayList (java.util.ArrayList)45 Test (org.junit.Test)38 Intent (android.content.Intent)35 ResolveInfo (android.content.pm.ResolveInfo)33 Configuration (android.content.res.Configuration)20 ApplicationsState (com.android.settingslib.applications.ApplicationsState)19 Preference (android.support.v7.preference.Preference)18 ArrayMap (android.util.ArrayMap)16 UsageStatsManager (android.app.usage.UsageStatsManager)13 ApplicationInfo (android.content.pm.ApplicationInfo)7 PackageManager (android.content.pm.PackageManager)6 ActivityManager (android.app.ActivityManager)5 AppOpsManager (android.app.AppOpsManager)5 ResolvedComponentInfo (com.android.internal.app.ResolverActivity.ResolvedComponentInfo)5 TargetApi (android.annotation.TargetApi)4 ConfigurationStats (android.app.usage.ConfigurationStats)4 UsageEvents (android.app.usage.UsageEvents)4 Event (android.app.usage.UsageEvents.Event)4 ArraySet (android.util.ArraySet)4