Load work apps in RecentAppStatsMixin

This change will show work apps and personal apps together in the
recent apps settings page, sorted by decreasing last usage time.

Test: see both work and personal apps in the recent apps page in the
correct order.
Fix: 146921442

Change-Id: I174a556010529bc39c085cc006722bc2947535bd
This commit is contained in:
Liahav Eitan
2022-05-20 11:53:11 +00:00
parent 7cebb74e17
commit 82e81e23e0
4 changed files with 214 additions and 65 deletions

View File

@@ -26,6 +26,7 @@ import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.PowerManager;
import android.os.UserHandle;
import android.os.UserManager;
import android.util.ArrayMap;
import android.util.ArraySet;
import android.util.Log;
@@ -33,6 +34,7 @@ import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import com.android.settings.Utils;
import com.android.settingslib.applications.AppUtils;
import com.android.settingslib.applications.ApplicationsState;
import com.android.settingslib.core.lifecycle.LifecycleObserver;
@@ -42,26 +44,31 @@ import com.android.settingslib.utils.ThreadUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class RecentAppStatsMixin implements Comparator<UsageStats>, LifecycleObserver, OnStart {
/**
* A helper class that loads recent app data in the background and sends it in a callback to a
* listener.
*/
public class RecentAppStatsMixin implements LifecycleObserver, OnStart {
private static final String TAG = "RecentAppStatsMixin";
private static final Set<String> SKIP_SYSTEM_PACKAGES = new ArraySet<>();
@VisibleForTesting
final List<UsageStats> mRecentApps;
private final int mUserId;
List<UsageStatsWrapper> mRecentApps;
private final int mMaximumApps;
private final Context mContext;
private final PackageManager mPm;
private final PowerManager mPowerManager;;
private final UsageStatsManager mUsageStatsManager;
private final PowerManager mPowerManager;
private final int mWorkUserId;
private final UsageStatsManager mPersonalUsageStatsManager;
private final Optional<UsageStatsManager> mWorkUsageStatsManager;
private final ApplicationsState mApplicationsState;
private final List<RecentAppStatsListener> mAppStatsListeners;
private Calendar mCalendar;
@@ -80,10 +87,15 @@ public class RecentAppStatsMixin implements Comparator<UsageStats>, LifecycleObs
public RecentAppStatsMixin(Context context, int maximumApps) {
mContext = context;
mMaximumApps = maximumApps;
mUserId = UserHandle.myUserId();
mPm = mContext.getPackageManager();
mPowerManager = mContext.getSystemService(PowerManager.class);
mUsageStatsManager = mContext.getSystemService(UsageStatsManager.class);
final UserManager userManager = mContext.getSystemService(UserManager.class);
mWorkUserId = Utils.getManagedProfileId(userManager, UserHandle.myUserId());
mPersonalUsageStatsManager = mContext.getSystemService(UsageStatsManager.class);
final UserHandle workUserHandle = Utils.getManagedProfile(userManager);
mWorkUsageStatsManager = Optional.ofNullable(workUserHandle).map(
handle -> mContext.createContextAsUser(handle, /* flags */ 0)
.getSystemService(UsageStatsManager.class));
mApplicationsState = ApplicationsState.getInstance(
(Application) mContext.getApplicationContext());
mRecentApps = new ArrayList<>();
@@ -100,32 +112,56 @@ public class RecentAppStatsMixin implements Comparator<UsageStats>, LifecycleObs
});
}
@Override
public final int compare(UsageStats a, UsageStats b) {
// return by descending order
return Long.compare(b.getLastTimeUsed(), a.getLastTimeUsed());
}
public void addListener(@NonNull RecentAppStatsListener listener) {
mAppStatsListeners.add(listener);
}
@VisibleForTesting
void loadDisplayableRecentApps(int number) {
void loadDisplayableRecentApps(int limit) {
mRecentApps.clear();
mCalendar = Calendar.getInstance();
mCalendar.add(Calendar.DAY_OF_YEAR, -1);
final List<UsageStats> mStats = mPowerManager.isPowerSaveMode()
final int personalUserId = UserHandle.myUserId();
final List<UsageStats> personalStats =
getRecentAppsStats(mPersonalUsageStatsManager, personalUserId);
final List<UsageStats> workStats = mWorkUsageStatsManager
.map(statsManager -> getRecentAppsStats(statsManager, mWorkUserId))
.orElse(new ArrayList<>());
// Both lists are already sorted, so we can create a sorted merge in linear time
int personal = 0;
int work = 0;
while (personal < personalStats.size() && work < workStats.size()
&& mRecentApps.size() < limit) {
UsageStats currentPersonal = personalStats.get(personal);
UsageStats currentWork = workStats.get(work);
if (currentPersonal.getLastTimeUsed() > currentWork.getLastTimeUsed()) {
mRecentApps.add(new UsageStatsWrapper(currentPersonal, personalUserId));
personal++;
} else {
mRecentApps.add(new UsageStatsWrapper(currentWork, mWorkUserId));
work++;
}
}
while (personal < personalStats.size() && mRecentApps.size() < limit) {
mRecentApps.add(new UsageStatsWrapper(personalStats.get(personal++), personalUserId));
}
while (work < workStats.size() && mRecentApps.size() < limit) {
mRecentApps.add(new UsageStatsWrapper(workStats.get(work++), mWorkUserId));
}
}
private List<UsageStats> getRecentAppsStats(UsageStatsManager usageStatsManager, int userId) {
final List<UsageStats> recentAppStats = mPowerManager.isPowerSaveMode()
? new ArrayList<>()
: mUsageStatsManager.queryUsageStats(
: usageStatsManager.queryUsageStats(
UsageStatsManager.INTERVAL_BEST, mCalendar.getTimeInMillis(),
System.currentTimeMillis());
final Map<String, UsageStats> map = new ArrayMap<>();
final int statCount = mStats.size();
for (int i = 0; i < statCount; i++) {
final UsageStats pkgStats = mStats.get(i);
if (!shouldIncludePkgInRecents(pkgStats)) {
for (final UsageStats pkgStats : recentAppStats) {
if (!shouldIncludePkgInRecents(pkgStats, userId)) {
continue;
}
final String pkgName = pkgStats.getPackageName();
@@ -136,28 +172,15 @@ public class RecentAppStatsMixin implements Comparator<UsageStats>, LifecycleObs
existingStats.add(pkgStats);
}
}
final List<UsageStats> packageStats = new ArrayList<>();
packageStats.addAll(map.values());
Collections.sort(packageStats, this /* comparator */);
int count = 0;
for (UsageStats stat : packageStats) {
final ApplicationsState.AppEntry appEntry = mApplicationsState.getEntry(
stat.getPackageName(), mUserId);
if (appEntry == null) {
continue;
}
mRecentApps.add(stat);
count++;
if (count >= number) {
break;
}
}
final List<UsageStats> packageStats = new ArrayList<>(map.values());
packageStats.sort(Comparator.comparingLong(UsageStats::getLastTimeUsed).reversed());
return packageStats;
}
/**
* Whether or not the app should be included in recent list.
*/
private boolean shouldIncludePkgInRecents(UsageStats stat) {
private boolean shouldIncludePkgInRecents(UsageStats stat, int userId) {
final String pkgName = stat.getPackageName();
if (stat.getLastTimeUsed() < mCalendar.getTimeInMillis()) {
Log.d(TAG, "Invalid timestamp (usage time is more than 24 hours ago), skipping "
@@ -169,26 +192,49 @@ public class RecentAppStatsMixin implements Comparator<UsageStats>, LifecycleObs
Log.d(TAG, "System package, skipping " + pkgName);
return false;
}
if (AppUtils.isHiddenSystemModule(mContext, pkgName)) {
return false;
}
final ApplicationsState.AppEntry appEntry = mApplicationsState.getEntry(pkgName, userId);
if (appEntry == null) {
return false;
}
final Intent launchIntent = new Intent().addCategory(Intent.CATEGORY_LAUNCHER)
.setPackage(pkgName);
if (mPm.resolveActivity(launchIntent, 0) == null) {
if (mPm.resolveActivityAsUser(launchIntent, 0, userId) == null) {
// Not visible on launcher -> likely not a user visible app, skip if non-instant.
final ApplicationsState.AppEntry appEntry =
mApplicationsState.getEntry(pkgName, mUserId);
if (appEntry == null || appEntry.info == null || !AppUtils.isInstant(appEntry.info)) {
if (appEntry.info == null || !AppUtils.isInstant(appEntry.info)) {
Log.d(TAG, "Not a user visible or instant app, skipping " + pkgName);
return false;
}
}
return true;
}
public interface RecentAppStatsListener {
void onReloadDataCompleted(List<UsageStats> recentApps);
/** A callback after loading the recent app data. */
void onReloadDataCompleted(List<UsageStatsWrapper> recentApps);
}
static class UsageStatsWrapper {
public final UsageStats mUsageStats;
public final int mUserId;
UsageStatsWrapper(UsageStats usageStats, int userId) {
mUsageStats = usageStats;
mUserId = userId;
}
@Override
public String toString() {
return String.format("UsageStatsWrapper(pkg:%s,uid:%s)",
mUsageStats.getPackageName(), mUserId);
}
}
}