Search in sources :

Example 1 with UsageEvents

use of android.app.usage.UsageEvents in project android_frameworks_base by DirtyUnicorns.

the class UsageLogActivity method run.

@Override
public void run() {
    long now = System.currentTimeMillis();
    UsageEvents events = mUsageStatsManager.queryEvents(mLastTime, now);
    long lastEventTime = mAdapter.update(events);
    if (lastEventTime >= 0) {
        mLastTime = lastEventTime + 1;
    }
    mHandler.postDelayed(this, 1000 * 5);
}
Also used : UsageEvents(android.app.usage.UsageEvents)

Example 2 with UsageEvents

use of android.app.usage.UsageEvents in project android_frameworks_base by crdroidandroid.

the class UsageLogActivity method run.

@Override
public void run() {
    long now = System.currentTimeMillis();
    UsageEvents events = mUsageStatsManager.queryEvents(mLastTime, now);
    long lastEventTime = mAdapter.update(events);
    if (lastEventTime >= 0) {
        mLastTime = lastEventTime + 1;
    }
    mHandler.postDelayed(this, 1000 * 5);
}
Also used : UsageEvents(android.app.usage.UsageEvents)

Example 3 with UsageEvents

use of android.app.usage.UsageEvents in project Taskbar by farmerbb.

the class TaskbarService method updateRecentApps.

@SuppressWarnings("Convert2streamapi")
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private void updateRecentApps(final boolean firstRefresh) {
    if (isScreenOff())
        return;
    SharedPreferences pref = U.getSharedPreferences(this);
    final PackageManager pm = getPackageManager();
    final List<AppEntry> entries = new ArrayList<>();
    List<LauncherActivityInfo> launcherAppCache = new ArrayList<>();
    int maxNumOfEntries = U.getMaxNumOfEntries(this);
    int realNumOfPinnedApps = 0;
    boolean fullLength = pref.getBoolean("full_length", false);
    PinnedBlockedApps pba = PinnedBlockedApps.getInstance(this);
    List<AppEntry> pinnedApps = pba.getPinnedApps();
    List<AppEntry> blockedApps = pba.getBlockedApps();
    List<String> applicationIdsToRemove = new ArrayList<>();
    // Filter out anything on the pinned/blocked apps lists
    if (pinnedApps.size() > 0) {
        UserManager userManager = (UserManager) getSystemService(USER_SERVICE);
        LauncherApps launcherApps = (LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE);
        for (AppEntry entry : pinnedApps) {
            boolean packageEnabled = launcherApps.isPackageEnabled(entry.getPackageName(), userManager.getUserForSerialNumber(entry.getUserId(this)));
            if (packageEnabled)
                entries.add(entry);
            else
                realNumOfPinnedApps--;
            applicationIdsToRemove.add(entry.getPackageName());
        }
        realNumOfPinnedApps = realNumOfPinnedApps + pinnedApps.size();
    }
    if (blockedApps.size() > 0) {
        for (AppEntry entry : blockedApps) {
            applicationIdsToRemove.add(entry.getPackageName());
        }
    }
    // Get list of all recently used apps
    List<AppEntry> usageStatsList = realNumOfPinnedApps < maxNumOfEntries ? getAppEntries() : new ArrayList<>();
    if (usageStatsList.size() > 0 || realNumOfPinnedApps > 0 || fullLength) {
        if (realNumOfPinnedApps < maxNumOfEntries) {
            List<AppEntry> usageStatsList2 = new ArrayList<>();
            List<AppEntry> usageStatsList3 = new ArrayList<>();
            List<AppEntry> usageStatsList4 = new ArrayList<>();
            List<AppEntry> usageStatsList5 = new ArrayList<>();
            List<AppEntry> usageStatsList6;
            Intent homeIntent = new Intent(Intent.ACTION_MAIN);
            homeIntent.addCategory(Intent.CATEGORY_HOME);
            ResolveInfo defaultLauncher = pm.resolveActivity(homeIntent, PackageManager.MATCH_DEFAULT_ONLY);
            // Also filter out the current launcher, and Taskbar itself
            for (AppEntry packageInfo : usageStatsList) {
                if (hasLauncherIntent(packageInfo.getPackageName()) && !packageInfo.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID) && !packageInfo.getPackageName().equals(defaultLauncher.activityInfo.packageName))
                    usageStatsList2.add(packageInfo);
            }
            // Filter out apps that don't fall within our current search interval
            for (AppEntry stats : usageStatsList2) {
                if (stats.getLastTimeUsed() > searchInterval || runningAppsOnly)
                    usageStatsList3.add(stats);
            }
            // Sort apps by either most recently used, or most time used
            if (!runningAppsOnly && sortOrder.contains("most_used")) {
                Collections.sort(usageStatsList3, (us1, us2) -> Long.compare(us2.getTotalTimeInForeground(), us1.getTotalTimeInForeground()));
            } else {
                Collections.sort(usageStatsList3, (us1, us2) -> Long.compare(us2.getLastTimeUsed(), us1.getLastTimeUsed()));
            }
            // Filter out any duplicate entries
            List<String> applicationIds = new ArrayList<>();
            for (AppEntry stats : usageStatsList3) {
                if (!applicationIds.contains(stats.getPackageName())) {
                    usageStatsList4.add(stats);
                    applicationIds.add(stats.getPackageName());
                }
            }
            // Filter out the currently running foreground app, if requested by the user
            if (pref.getBoolean("hide_foreground", false)) {
                UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(USAGE_STATS_SERVICE);
                UsageEvents events = mUsageStatsManager.queryEvents(searchInterval, System.currentTimeMillis());
                UsageEvents.Event eventCache = new UsageEvents.Event();
                String currentForegroundApp = null;
                while (events.hasNextEvent()) {
                    events.getNextEvent(eventCache);
                    if (eventCache.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                        if (!(eventCache.getPackageName().contains(BuildConfig.BASE_APPLICATION_ID) && !eventCache.getClassName().equals(MainActivity.class.getCanonicalName()) && !eventCache.getClassName().equals(HomeActivity.class.getCanonicalName()) && !eventCache.getClassName().equals(InvisibleActivityFreeform.class.getCanonicalName())))
                            currentForegroundApp = eventCache.getPackageName();
                    }
                }
                if (!applicationIdsToRemove.contains(currentForegroundApp))
                    applicationIdsToRemove.add(currentForegroundApp);
            }
            for (AppEntry stats : usageStatsList4) {
                if (!applicationIdsToRemove.contains(stats.getPackageName())) {
                    usageStatsList5.add(stats);
                }
            }
            // Truncate list to a maximum length
            if (usageStatsList5.size() > maxNumOfEntries)
                usageStatsList6 = usageStatsList5.subList(0, maxNumOfEntries);
            else
                usageStatsList6 = usageStatsList5;
            // Determine if we need to reverse the order
            boolean needToReverseOrder;
            switch(U.getTaskbarPosition(this)) {
                case "bottom_right":
                case "top_right":
                    needToReverseOrder = sortOrder.contains("false");
                    break;
                default:
                    needToReverseOrder = sortOrder.contains("true");
                    break;
            }
            if (needToReverseOrder) {
                Collections.reverse(usageStatsList6);
            }
            // Generate the AppEntries for TaskbarAdapter
            int number = usageStatsList6.size() == maxNumOfEntries ? usageStatsList6.size() - realNumOfPinnedApps : usageStatsList6.size();
            UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE);
            LauncherApps launcherApps = (LauncherApps) getSystemService(Context.LAUNCHER_APPS_SERVICE);
            final List<UserHandle> userHandles = userManager.getUserProfiles();
            for (int i = 0; i < number; i++) {
                for (UserHandle handle : userHandles) {
                    String packageName = usageStatsList6.get(i).getPackageName();
                    List<LauncherActivityInfo> list = launcherApps.getActivityList(packageName, handle);
                    if (!list.isEmpty()) {
                        // Google App workaround
                        if (!packageName.equals("com.google.android.googlequicksearchbox"))
                            launcherAppCache.add(list.get(0));
                        else {
                            boolean added = false;
                            for (LauncherActivityInfo info : list) {
                                if (info.getName().equals("com.google.android.googlequicksearchbox.SearchActivity")) {
                                    launcherAppCache.add(info);
                                    added = true;
                                }
                            }
                            if (!added)
                                launcherAppCache.add(list.get(0));
                        }
                        AppEntry newEntry = new AppEntry(packageName, null, null, null, false);
                        newEntry.setUserId(userManager.getSerialNumberForUser(handle));
                        entries.add(newEntry);
                        break;
                    }
                }
            }
        }
        while (entries.size() > maxNumOfEntries) {
            try {
                entries.remove(entries.size() - 1);
                launcherAppCache.remove(launcherAppCache.size() - 1);
            } catch (ArrayIndexOutOfBoundsException e) {
            /* Gracefully fail */
            }
        }
        // Determine if we need to reverse the order again
        if (U.getTaskbarPosition(this).contains("vertical")) {
            Collections.reverse(entries);
            Collections.reverse(launcherAppCache);
        }
        // Now that we've generated the list of apps,
        // we need to determine if we need to redraw the Taskbar or not
        boolean shouldRedrawTaskbar = firstRefresh;
        List<String> finalApplicationIds = new ArrayList<>();
        for (AppEntry entry : entries) {
            finalApplicationIds.add(entry.getPackageName());
        }
        if (finalApplicationIds.size() != currentTaskbarIds.size() || numOfPinnedApps != realNumOfPinnedApps)
            shouldRedrawTaskbar = true;
        else {
            for (int i = 0; i < finalApplicationIds.size(); i++) {
                if (!finalApplicationIds.get(i).equals(currentTaskbarIds.get(i))) {
                    shouldRedrawTaskbar = true;
                    break;
                }
            }
        }
        if (shouldRedrawTaskbar) {
            currentTaskbarIds = finalApplicationIds;
            numOfPinnedApps = realNumOfPinnedApps;
            UserManager userManager = (UserManager) getSystemService(USER_SERVICE);
            int launcherAppCachePos = -1;
            for (int i = 0; i < entries.size(); i++) {
                if (entries.get(i).getComponentName() == null) {
                    launcherAppCachePos++;
                    LauncherActivityInfo appInfo = launcherAppCache.get(launcherAppCachePos);
                    String packageName = entries.get(i).getPackageName();
                    entries.remove(i);
                    AppEntry newEntry = new AppEntry(packageName, appInfo.getComponentName().flattenToString(), appInfo.getLabel().toString(), IconCache.getInstance(TaskbarService.this).getIcon(TaskbarService.this, pm, appInfo), false);
                    newEntry.setUserId(userManager.getSerialNumberForUser(appInfo.getUser()));
                    entries.add(i, newEntry);
                }
            }
            final int numOfEntries = Math.min(entries.size(), maxNumOfEntries);
            handler.post(() -> {
                if (numOfEntries > 0 || fullLength) {
                    ViewGroup.LayoutParams params = scrollView.getLayoutParams();
                    DisplayMetrics metrics = U.getRealDisplayMetrics(this);
                    int recentsSize = getResources().getDimensionPixelSize(R.dimen.icon_size) * numOfEntries;
                    float maxRecentsSize = fullLength ? Float.MAX_VALUE : recentsSize;
                    if (U.getTaskbarPosition(TaskbarService.this).contains("vertical")) {
                        int maxScreenSize = metrics.heightPixels - U.getStatusBarHeight(TaskbarService.this) - U.getBaseTaskbarSize(TaskbarService.this);
                        params.height = (int) Math.min(maxRecentsSize, maxScreenSize) + getResources().getDimensionPixelSize(R.dimen.divider_size);
                        if (fullLength && U.getTaskbarPosition(this).contains("bottom")) {
                            try {
                                Space whitespace = U.findViewById(layout, R.id.whitespace);
                                ViewGroup.LayoutParams params2 = whitespace.getLayoutParams();
                                params2.height = maxScreenSize - recentsSize;
                                whitespace.setLayoutParams(params2);
                            } catch (NullPointerException e) {
                            /* Gracefully fail */
                            }
                        }
                    } else {
                        int maxScreenSize = metrics.widthPixels - U.getBaseTaskbarSize(TaskbarService.this);
                        params.width = (int) Math.min(maxRecentsSize, maxScreenSize) + getResources().getDimensionPixelSize(R.dimen.divider_size);
                        if (fullLength && U.getTaskbarPosition(this).contains("right")) {
                            try {
                                Space whitespace = U.findViewById(layout, R.id.whitespace);
                                ViewGroup.LayoutParams params2 = whitespace.getLayoutParams();
                                params2.width = maxScreenSize - recentsSize;
                                whitespace.setLayoutParams(params2);
                            } catch (NullPointerException e) {
                            /* Gracefully fail */
                            }
                        }
                    }
                    scrollView.setLayoutParams(params);
                    taskbar.removeAllViews();
                    for (int i = 0; i < entries.size(); i++) {
                        taskbar.addView(getView(entries, i));
                    }
                    isShowingRecents = true;
                    if (shouldRefreshRecents && scrollView.getVisibility() != View.VISIBLE) {
                        if (firstRefresh)
                            scrollView.setVisibility(View.INVISIBLE);
                        else
                            scrollView.setVisibility(View.VISIBLE);
                    }
                    if (firstRefresh && scrollView.getVisibility() != View.VISIBLE)
                        new Handler().post(() -> {
                            switch(U.getTaskbarPosition(TaskbarService.this)) {
                                case "bottom_left":
                                case "bottom_right":
                                case "top_left":
                                case "top_right":
                                    if (sortOrder.contains("false"))
                                        scrollView.scrollTo(0, 0);
                                    else if (sortOrder.contains("true"))
                                        scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight());
                                    break;
                                case "bottom_vertical_left":
                                case "bottom_vertical_right":
                                case "top_vertical_left":
                                case "top_vertical_right":
                                    if (sortOrder.contains("false"))
                                        scrollView.scrollTo(taskbar.getWidth(), taskbar.getHeight());
                                    else if (sortOrder.contains("true"))
                                        scrollView.scrollTo(0, 0);
                                    break;
                            }
                            if (shouldRefreshRecents) {
                                scrollView.setVisibility(View.VISIBLE);
                            }
                        });
                } else {
                    isShowingRecents = false;
                    scrollView.setVisibility(View.GONE);
                }
            });
        }
    } else if (firstRefresh || currentTaskbarIds.size() > 0) {
        currentTaskbarIds.clear();
        handler.post(() -> {
            isShowingRecents = false;
            scrollView.setVisibility(View.GONE);
        });
    }
}
Also used : ArrayList(java.util.ArrayList) MainActivity(com.farmerbb.taskbar.MainActivity) UsageEvents(android.app.usage.UsageEvents) DisplayMetrics(android.util.DisplayMetrics) ResolveInfo(android.content.pm.ResolveInfo) PackageManager(android.content.pm.PackageManager) UserHandle(android.os.UserHandle) UsageStatsManager(android.app.usage.UsageStatsManager) PinnedBlockedApps(com.farmerbb.taskbar.util.PinnedBlockedApps) Space(android.widget.Space) SharedPreferences(android.content.SharedPreferences) InvisibleActivityFreeform(com.farmerbb.taskbar.activity.InvisibleActivityFreeform) ViewGroup(android.view.ViewGroup) Handler(android.os.Handler) LauncherApps(android.content.pm.LauncherApps) Intent(android.content.Intent) RecognizerIntent(android.speech.RecognizerIntent) SuppressLint(android.annotation.SuppressLint) Point(android.graphics.Point) AppEntry(com.farmerbb.taskbar.util.AppEntry) UserManager(android.os.UserManager) LauncherActivityInfo(android.content.pm.LauncherActivityInfo) MotionEvent(android.view.MotionEvent) TargetApi(android.annotation.TargetApi)

Example 4 with UsageEvents

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

the class ShadowUsageStatsManagerTest method testQueryEvents_emptyEvents.

@Test
public void testQueryEvents_emptyEvents() throws Exception {
    UsageEvents events = usageStatsManager.queryEvents(1000L, 2000L);
    Event event = new Event();
    assertThat(events.hasNextEvent()).isFalse();
    assertThat(events.getNextEvent(event)).isFalse();
}
Also used : Event(android.app.usage.UsageEvents.Event) UsageEvents(android.app.usage.UsageEvents) Test(org.junit.Test)

Example 5 with UsageEvents

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

the class ShadowUsageStatsManagerTest method testQueryEvents_appendEventData_shouldCombineWithPreviousData.

@Test
public void testQueryEvents_appendEventData_shouldCombineWithPreviousData() throws Exception {
    shadowOf(usageStatsManager).addEvent(TEST_PACKAGE_NAME1, 500L, Event.MOVE_TO_FOREGROUND);
    shadowOf(usageStatsManager).addEvent(TEST_PACKAGE_NAME1, 1000L, Event.MOVE_TO_BACKGROUND);
    shadowOf(usageStatsManager).addEvent(ShadowUsageStatsManager.EventBuilder.buildEvent().setTimeStamp(1500L).setPackage(TEST_PACKAGE_NAME2).setClass(TEST_ACTIVITY_NAME).setEventType(Event.MOVE_TO_FOREGROUND).build());
    shadowOf(usageStatsManager).addEvent(TEST_PACKAGE_NAME2, 2000L, Event.MOVE_TO_BACKGROUND);
    shadowOf(usageStatsManager).addEvent(ShadowUsageStatsManager.EventBuilder.buildEvent().setTimeStamp(2500L).setPackage(TEST_PACKAGE_NAME1).setEventType(Event.MOVE_TO_FOREGROUND).setClass(TEST_ACTIVITY_NAME).build());
    UsageEvents events = usageStatsManager.queryEvents(1000L, 2000L);
    Event event = new Event();
    assertThat(events.hasNextEvent()).isTrue();
    assertThat(events.getNextEvent(event)).isTrue();
    assertThat(event.getPackageName()).isEqualTo(TEST_PACKAGE_NAME1);
    assertThat(event.getTimeStamp()).isEqualTo(1000L);
    assertThat(event.getEventType()).isEqualTo(Event.MOVE_TO_BACKGROUND);
    assertThat(events.hasNextEvent()).isTrue();
    assertThat(events.getNextEvent(event)).isTrue();
    assertThat(event.getPackageName()).isEqualTo(TEST_PACKAGE_NAME2);
    assertThat(event.getTimeStamp()).isEqualTo(1500L);
    assertThat(event.getEventType()).isEqualTo(Event.MOVE_TO_FOREGROUND);
    assertThat(event.getClassName()).isEqualTo(TEST_ACTIVITY_NAME);
    assertThat(events.hasNextEvent()).isFalse();
    assertThat(events.getNextEvent(event)).isFalse();
}
Also used : Event(android.app.usage.UsageEvents.Event) UsageEvents(android.app.usage.UsageEvents) Test(org.junit.Test)

Aggregations

UsageEvents (android.app.usage.UsageEvents)31 Event (android.app.usage.UsageEvents.Event)17 Test (org.junit.Test)16 ArrayList (java.util.ArrayList)12 NotificationsSentState (com.android.settings.applications.AppStateNotificationBridge.NotificationsSentState)7 ResolveInfo (android.content.pm.ResolveInfo)4 Parcel (android.os.Parcel)4 RemoteException (android.os.RemoteException)4 AppEntry (com.android.settingslib.applications.ApplicationsState.AppEntry)4 Intent (android.content.Intent)3 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)3 SuppressLint (android.annotation.SuppressLint)2 UsageStatsManager (android.app.usage.UsageStatsManager)2 NotifyingApp (android.service.notification.NotifyingApp)2 ArrayMap (android.util.ArrayMap)2 MotionEvent (android.view.MotionEvent)2 Preference (androidx.preference.Preference)2 Date (java.util.Date)2 TargetApi (android.annotation.TargetApi)1 ActivityManager (android.app.ActivityManager)1