Merge "Add app entities widget for recently opened apps"

This commit is contained in:
TreeHugger Robot
2019-02-23 02:15:26 +00:00
committed by Android (Google) Code Review
4 changed files with 249 additions and 290 deletions

View File

@@ -23,24 +23,25 @@
settings:initialExpandedChildrenCount="8"> settings:initialExpandedChildrenCount="8">
<!-- the initial count should include the dynamic tiles --> <!-- the initial count should include the dynamic tiles -->
<PreferenceCategory <Preference
android:key="recent_apps_category" android:key="all_app_info"
android:title="@string/recent_app_category_title" android:title="@string/applications_settings"
android:order="-200"> android:order="-999"
<!-- Placeholder for a list of recent apps --> android:fragment="com.android.settings.applications.manageapplications.ManageApplications"/>
<!-- See all apps button --> <com.android.settingslib.widget.LayoutPreference
<Preference android:key="recent_open_apps"
android:title="@string/applications_settings" android:title="@string/recent_app_category_title"
android:key="all_app_info" android:layout="@layout/app_entities_header"
android:fragment="com.android.settings.applications.manageapplications.ManageApplications" android:selectable="false"
android:order="20"/> android:order="-998"
</PreferenceCategory> settings:allowDividerBelow="true"
settings:controller="com.android.settings.applications.RecentAppsPreferenceController"/>
<!-- Empty category to draw divider --> <!-- Empty category to draw divider -->
<PreferenceCategory <PreferenceCategory
android:key="all_app_info_divider" android:key="recent_apps_divider"
android:order="-190"/> android:order="-997"/>
<!-- Notifications (appears before manage_perms), default apps (appears after) --> <!-- Notifications (appears before manage_perms), default apps (appears after) -->
<PreferenceCategory <PreferenceCategory

View File

@@ -16,14 +16,10 @@
package com.android.settings.applications; package com.android.settings.applications;
import android.app.Activity;
import android.app.Application;
import android.app.settings.SettingsEnums; import android.app.settings.SettingsEnums;
import android.content.Context; import android.content.Context;
import android.provider.SearchIndexableResource; import android.provider.SearchIndexableResource;
import androidx.fragment.app.Fragment;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.dashboard.DashboardFragment; import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.notification.EmergencyBroadcastPreferenceController; import com.android.settings.notification.EmergencyBroadcastPreferenceController;
@@ -63,27 +59,20 @@ public class AppAndNotificationDashboardFragment extends DashboardFragment {
@Override @Override
public void onAttach(Context context) { public void onAttach(Context context) {
super.onAttach(context); super.onAttach(context);
use(SpecialAppAccessPreferenceController.class).setSession(getSettingsLifecycle()); use(SpecialAppAccessPreferenceController.class).setSession(getSettingsLifecycle());
use(RecentAppsPreferenceController.class).setFragment(this /* fragment */);
} }
@Override @Override
protected List<AbstractPreferenceController> createPreferenceControllers(Context context) { protected List<AbstractPreferenceController> createPreferenceControllers(Context context) {
final Activity activity = getActivity(); return buildPreferenceControllers(context);
final Application app;
if (activity != null) {
app = activity.getApplication();
} else {
app = null;
}
return buildPreferenceControllers(context, app, this);
} }
private static List<AbstractPreferenceController> buildPreferenceControllers(Context context, private static List<AbstractPreferenceController> buildPreferenceControllers(Context context) {
Application app, Fragment host) {
final List<AbstractPreferenceController> controllers = new ArrayList<>(); final List<AbstractPreferenceController> controllers = new ArrayList<>();
controllers.add(new EmergencyBroadcastPreferenceController(context, controllers.add(new EmergencyBroadcastPreferenceController(context,
"app_and_notif_cell_broadcast_settings")); "app_and_notif_cell_broadcast_settings"));
controllers.add(new RecentAppsPreferenceController(context, app, host));
return controllers; return controllers;
} }
@@ -100,7 +89,7 @@ public class AppAndNotificationDashboardFragment extends DashboardFragment {
@Override @Override
public List<AbstractPreferenceController> createPreferenceControllers( public List<AbstractPreferenceController> createPreferenceControllers(
Context context) { Context context) {
return buildPreferenceControllers(context, null, null /* host */); return buildPreferenceControllers(context);
} }
}; };
} }

View File

@@ -27,26 +27,28 @@ import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.PowerManager; import android.os.PowerManager;
import android.os.UserHandle; import android.os.UserHandle;
import android.text.TextUtils;
import android.util.ArrayMap; import android.util.ArrayMap;
import android.util.ArraySet; import android.util.ArraySet;
import android.util.IconDrawableFactory; import android.util.IconDrawableFactory;
import android.util.Log; import android.util.Log;
import android.view.View;
import androidx.annotation.VisibleForTesting; import androidx.annotation.VisibleForTesting;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import androidx.preference.Preference; import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceScreen;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.applications.appinfo.AppInfoDashboardFragment; import com.android.settings.applications.appinfo.AppInfoDashboardFragment;
import com.android.settings.core.PreferenceControllerMixin; import com.android.settings.applications.manageapplications.ManageApplications;
import com.android.settings.core.BasePreferenceController;
import com.android.settings.core.SubSettingLauncher;
import com.android.settingslib.applications.AppUtils; import com.android.settingslib.applications.AppUtils;
import com.android.settingslib.applications.ApplicationsState; import com.android.settingslib.applications.ApplicationsState;
import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.utils.StringUtil; import com.android.settingslib.utils.StringUtil;
import com.android.settingslib.widget.apppreference.AppPreference; import com.android.settingslib.widget.AppEntitiesHeaderController;
import com.android.settingslib.widget.AppEntityInfo;
import com.android.settingslib.widget.LayoutPreference;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -58,22 +60,29 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
* This controller displays a list of recently used apps and a "See all" button. If there is * This controller displays up to three recently used apps.
* no recently used app, "See all" will be displayed as "App info". * If there is no recently used app, we only show up an "App Info" preference.
*/ */
public class RecentAppsPreferenceController extends AbstractPreferenceController public class RecentAppsPreferenceController extends BasePreferenceController
implements PreferenceControllerMixin, Comparator<UsageStats> { implements Comparator<UsageStats> {
@VisibleForTesting
static final String KEY_ALL_APP_INFO = "all_app_info";
@VisibleForTesting
static final String KEY_DIVIDER = "recent_apps_divider";
private static final String TAG = "RecentAppsCtrl"; private static final String TAG = "RecentAppsCtrl";
private static final String KEY_PREF_CATEGORY = "recent_apps_category";
@VisibleForTesting
static final String KEY_DIVIDER = "all_app_info_divider";
@VisibleForTesting
static final String KEY_SEE_ALL = "all_app_info";
private static final int SHOW_RECENT_APP_COUNT = 5;
private static final Set<String> SKIP_SYSTEM_PACKAGES = new ArraySet<>(); private static final Set<String> SKIP_SYSTEM_PACKAGES = new ArraySet<>();
private final Fragment mHost; @VisibleForTesting
AppEntitiesHeaderController mAppEntitiesController;
@VisibleForTesting
LayoutPreference mRecentAppsPreference;
@VisibleForTesting
Preference mAllAppPref;
@VisibleForTesting
Preference mDivider;
private final PackageManager mPm; private final PackageManager mPm;
private final UsageStatsManager mUsageStatsManager; private final UsageStatsManager mUsageStatsManager;
private final ApplicationsState mApplicationsState; private final ApplicationsState mApplicationsState;
@@ -81,12 +90,9 @@ public class RecentAppsPreferenceController extends AbstractPreferenceController
private final IconDrawableFactory mIconDrawableFactory; private final IconDrawableFactory mIconDrawableFactory;
private final PowerManager mPowerManager; private final PowerManager mPowerManager;
private Fragment mHost;
private Calendar mCal; private Calendar mCal;
private List<UsageStats> mStats; private List<UsageStats> mStats;
private PreferenceCategory mCategory;
private Preference mSeeAllPref;
private Preference mDivider;
private boolean mHasRecentApps; private boolean mHasRecentApps;
static { static {
@@ -100,68 +106,67 @@ public class RecentAppsPreferenceController extends AbstractPreferenceController
)); ));
} }
public RecentAppsPreferenceController(Context context, Application app, Fragment host) { public RecentAppsPreferenceController(Context context, String key) {
this(context, app == null ? null : ApplicationsState.getInstance(app), host); super(context, key);
} mApplicationsState = ApplicationsState.getInstance(
(Application) mContext.getApplicationContext());
@VisibleForTesting(otherwise = VisibleForTesting.NONE)
RecentAppsPreferenceController(Context context, ApplicationsState appState, Fragment host) {
super(context);
mIconDrawableFactory = IconDrawableFactory.newInstance(context);
mUserId = UserHandle.myUserId(); mUserId = UserHandle.myUserId();
mPm = context.getPackageManager(); mPm = mContext.getPackageManager();
mPowerManager = context.getSystemService(PowerManager.class); mIconDrawableFactory = IconDrawableFactory.newInstance(mContext);
mPowerManager = mContext.getSystemService(PowerManager.class);
mUsageStatsManager = mContext.getSystemService(UsageStatsManager.class);
}
mHost = host; public void setFragment(Fragment fragment) {
mUsageStatsManager = mHost = fragment;
(UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
mApplicationsState = appState;
} }
@Override @Override
public boolean isAvailable() { public int getAvailabilityStatus() {
return true; reloadData();
} return getDisplayableRecentAppList().isEmpty() ? AVAILABLE_UNSEARCHABLE : AVAILABLE;
@Override
public String getPreferenceKey() {
return KEY_PREF_CATEGORY;
}
@Override
public void updateNonIndexableKeys(List<String> keys) {
PreferenceControllerMixin.super.updateNonIndexableKeys(keys);
// Don't index category name into search. It's not actionable.
keys.add(KEY_PREF_CATEGORY);
keys.add(KEY_DIVIDER);
} }
@Override @Override
public void displayPreference(PreferenceScreen screen) { public void displayPreference(PreferenceScreen screen) {
mCategory = screen.findPreference(getPreferenceKey());
mSeeAllPref = screen.findPreference(KEY_SEE_ALL);
mDivider = screen.findPreference(KEY_DIVIDER);
super.displayPreference(screen); super.displayPreference(screen);
refreshUi(mCategory.getContext());
mAllAppPref = screen.findPreference(KEY_ALL_APP_INFO);
mDivider = screen.findPreference(KEY_DIVIDER);
mRecentAppsPreference = (LayoutPreference) screen.findPreference(getPreferenceKey());
final View view = mRecentAppsPreference.findViewById(R.id.app_entities_header);
mAppEntitiesController = AppEntitiesHeaderController.newInstance(mContext, view)
.setHeaderTitleRes(R.string.recent_app_category_title)
.setHeaderDetailsClickListener((View v) -> {
new SubSettingLauncher(mContext)
.setDestination(ManageApplications.class.getName())
.setArguments(null /* arguments */)
.setTitleRes(R.string.application_info_label)
.setSourceMetricsCategory(SettingsEnums.SETTINGS_APP_NOTIF_CATEGORY)
.launch();
});
refreshUi();
} }
@Override @Override
public void updateState(Preference preference) { public void updateState(Preference preference) {
super.updateState(preference); super.updateState(preference);
refreshUi(mCategory.getContext()); refreshUi();
// Show total number of installed apps as See all's summary. // Show total number of installed apps as See all's summary.
new InstalledAppCounter(mContext, InstalledAppCounter.IGNORE_INSTALL_REASON, new InstalledAppCounter(mContext, InstalledAppCounter.IGNORE_INSTALL_REASON,
mContext.getPackageManager()) { mContext.getPackageManager()) {
@Override @Override
protected void onCountComplete(int num) { protected void onCountComplete(int num) {
if (mHasRecentApps) { if (mHasRecentApps) {
mSeeAllPref.setTitle(mContext.getString(R.string.see_all_apps_title, num)); mAppEntitiesController.setHeaderDetails(
mContext.getString(R.string.see_all_apps_title, num));
mAppEntitiesController.apply();
} else { } else {
mSeeAllPref.setSummary(mContext.getString(R.string.apps_summary, num)); mAllAppPref.setSummary(mContext.getString(R.string.apps_summary, num));
} }
} }
}.execute(); }.execute();
} }
@Override @Override
@@ -171,12 +176,12 @@ public class RecentAppsPreferenceController extends AbstractPreferenceController
} }
@VisibleForTesting @VisibleForTesting
void refreshUi(Context prefContext) { void refreshUi() {
reloadData(); reloadData();
final List<UsageStats> recentApps = getDisplayableRecentAppList(); final List<UsageStats> recentApps = getDisplayableRecentAppList();
if (recentApps != null && !recentApps.isEmpty()) { if (recentApps != null && !recentApps.isEmpty()) {
mHasRecentApps = true; mHasRecentApps = true;
displayRecentApps(prefContext, recentApps); displayRecentApps(recentApps);
} else { } else {
mHasRecentApps = false; mHasRecentApps = false;
displayOnlyAppInfo(); displayOnlyAppInfo();
@@ -195,73 +200,50 @@ public class RecentAppsPreferenceController extends AbstractPreferenceController
} }
private void displayOnlyAppInfo() { private void displayOnlyAppInfo() {
mCategory.setTitle(null);
mDivider.setVisible(false); mDivider.setVisible(false);
mSeeAllPref.setTitle(R.string.applications_settings); mAllAppPref.setTitle(R.string.applications_settings);
mSeeAllPref.setIcon(null); mAllAppPref.setVisible(true);
int prefCount = mCategory.getPreferenceCount(); mRecentAppsPreference.setVisible(false);
for (int i = prefCount - 1; i >= 0; i--) {
final Preference pref = mCategory.getPreference(i);
if (!TextUtils.equals(pref.getKey(), KEY_SEE_ALL)) {
mCategory.removePreference(pref);
}
}
} }
private void displayRecentApps(Context prefContext, List<UsageStats> recentApps) { private void displayRecentApps(List<UsageStats> recentApps) {
mCategory.setTitle(R.string.recent_app_category_title); int showAppsCount = 0;
for (UsageStats stat : recentApps) {
final AppEntityInfo appEntityInfoInfo = createAppEntity(stat);
if (appEntityInfoInfo != null) {
mAppEntitiesController.setAppEntity(showAppsCount++, appEntityInfoInfo);
}
if (showAppsCount == AppEntitiesHeaderController.MAXIMUM_APPS) {
break;
}
}
mAppEntitiesController.apply();
mRecentAppsPreference.setVisible(true);
mAllAppPref.setVisible(false);
mDivider.setVisible(true); mDivider.setVisible(true);
mSeeAllPref.setSummary(null); }
mSeeAllPref.setIcon(R.drawable.ic_chevron_right_24dp);
// Rebind prefs/avoid adding new prefs if possible. Adding/removing prefs causes jank. private AppEntityInfo createAppEntity(UsageStats stat) {
// Build a cached preference pool final String pkgName = stat.getPackageName();
final Map<String, Preference> appPreferences = new ArrayMap<>(); final ApplicationsState.AppEntry appEntry =
int prefCount = mCategory.getPreferenceCount(); mApplicationsState.getEntry(pkgName, mUserId);
for (int i = 0; i < prefCount; i++) { if (appEntry == null) {
final Preference pref = mCategory.getPreference(i); return null;
final String key = pref.getKey();
if (!TextUtils.equals(key, KEY_SEE_ALL)) {
appPreferences.put(key, pref);
}
} }
final int recentAppsCount = recentApps.size();
for (int i = 0; i < recentAppsCount; i++) {
final UsageStats stat = recentApps.get(i);
// Bind recent apps to existing prefs if possible, or create a new pref.
final String pkgName = stat.getPackageName();
final ApplicationsState.AppEntry appEntry =
mApplicationsState.getEntry(pkgName, mUserId);
if (appEntry == null) {
continue;
}
boolean rebindPref = true; return new AppEntityInfo.Builder()
Preference pref = appPreferences.remove(pkgName); .setIcon(mIconDrawableFactory.getBadgedIcon(appEntry.info))
if (pref == null) { .setTitle(appEntry.label)
pref = new AppPreference(prefContext); .setSummary(StringUtil.formatRelativeTime(mContext,
rebindPref = false; System.currentTimeMillis() - stat.getLastTimeUsed(), false))
} .setOnClickListener(v ->
pref.setKey(pkgName); AppInfoBase.startAppInfoFragment(AppInfoDashboardFragment.class,
pref.setTitle(appEntry.label); R.string.application_info_label, pkgName, appEntry.info.uid,
pref.setIcon(mIconDrawableFactory.getBadgedIcon(appEntry.info)); mHost, 1001 /*RequestCode*/,
pref.setSummary(StringUtil.formatRelativeTime(mContext, SettingsEnums.SETTINGS_APP_NOTIF_CATEGORY))
System.currentTimeMillis() - stat.getLastTimeUsed(), false)); .build();
pref.setOrder(i);
pref.setOnPreferenceClickListener(preference -> {
AppInfoBase.startAppInfoFragment(AppInfoDashboardFragment.class,
R.string.application_info_label, pkgName, appEntry.info.uid, mHost,
1001 /*RequestCode*/, SettingsEnums.SETTINGS_APP_NOTIF_CATEGORY);
return true;
});
if (!rebindPref) {
mCategory.addPreference(pref);
}
}
// Remove unused prefs from pref cache pool
for (Preference unusedPrefs : appPreferences.values()) {
mCategory.removePreference(unusedPrefs);
}
} }
private List<UsageStats> getDisplayableRecentAppList() { private List<UsageStats> getDisplayableRecentAppList() {
@@ -293,7 +275,7 @@ public class RecentAppsPreferenceController extends AbstractPreferenceController
} }
recentApps.add(stat); recentApps.add(stat);
count++; count++;
if (count >= SHOW_RECENT_APP_COUNT) { if (count >= AppEntitiesHeaderController.MAXIMUM_APPS) {
break; break;
} }
} }

View File

@@ -16,23 +16,23 @@
package com.android.settings.applications; package com.android.settings.applications;
import static com.android.settings.core.BasePreferenceController.AVAILABLE;
import static com.android.settings.core.BasePreferenceController.AVAILABLE_UNSEARCHABLE;
import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import android.app.Application;
import android.app.usage.UsageStats; import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager; import android.app.usage.UsageStatsManager;
import android.content.Context; import android.content.Context;
@@ -44,27 +44,29 @@ import android.content.pm.ResolveInfo;
import android.os.PowerManager; import android.os.PowerManager;
import android.os.UserHandle; import android.os.UserHandle;
import android.os.UserManager; import android.os.UserManager;
import android.text.TextUtils; import android.view.LayoutInflater;
import android.view.View;
import androidx.fragment.app.Fragment;
import androidx.preference.Preference; import androidx.preference.Preference;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceScreen;
import com.android.settings.R; import com.android.settings.R;
import com.android.settingslib.applications.AppUtils; import com.android.settingslib.applications.AppUtils;
import com.android.settingslib.applications.ApplicationsState; import com.android.settingslib.applications.ApplicationsState;
import com.android.settingslib.applications.instantapps.InstantAppDataProvider; import com.android.settingslib.applications.instantapps.InstantAppDataProvider;
import com.android.settingslib.widget.AppEntitiesHeaderController;
import com.android.settingslib.widget.AppEntityInfo;
import com.android.settingslib.widget.LayoutPreference;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatcher; import org.mockito.ArgumentMatcher;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers; import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList; import java.util.ArrayList;
@@ -76,12 +78,6 @@ public class RecentAppsPreferenceControllerTest {
@Mock @Mock
private PreferenceScreen mScreen; private PreferenceScreen mScreen;
@Mock @Mock
private PreferenceCategory mCategory;
@Mock
private Preference mSeeAllPref;
@Mock
private PreferenceCategory mDivider;
@Mock
private UsageStatsManager mUsageStatsManager; private UsageStatsManager mUsageStatsManager;
@Mock @Mock
private UserManager mUserManager; private UserManager mUserManager;
@@ -95,73 +91,130 @@ public class RecentAppsPreferenceControllerTest {
private ApplicationInfo mApplicationInfo; private ApplicationInfo mApplicationInfo;
@Mock @Mock
private PowerManager mPowerManager; private PowerManager mPowerManager;
@Mock
private Fragment mFragment;
private Context mContext; private LayoutPreference mRecentAppsPreference;
private RecentAppsPreferenceController mController; private RecentAppsPreferenceController mController;
@Before @Before
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application); final Context context = spy(RuntimeEnvironment.application);
when(mContext.getApplicationContext()).thenReturn(mContext); when(context.getApplicationContext()).thenReturn(context);
ReflectionHelpers.setStaticField(ApplicationsState.class, "sInstance", mAppState); ReflectionHelpers.setStaticField(ApplicationsState.class, "sInstance", mAppState);
doReturn(mUsageStatsManager).when(mContext).getSystemService(Context.USAGE_STATS_SERVICE); doReturn(mUsageStatsManager).when(context).getSystemService(Context.USAGE_STATS_SERVICE);
doReturn(mUserManager).when(mContext).getSystemService(Context.USER_SERVICE); doReturn(mUserManager).when(context).getSystemService(Context.USER_SERVICE);
doReturn(mPackageManager).when(mContext).getPackageManager(); doReturn(mPackageManager).when(context).getPackageManager();
doReturn(mPowerManager).when(mContext).getSystemService(PowerManager.class); doReturn(mPowerManager).when(context).getSystemService(PowerManager.class);
when(mUserManager.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[] {}); when(mUserManager.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[]{});
mController = new RecentAppsPreferenceController(mContext, mAppState, null); final View appEntitiesHeaderView = LayoutInflater.from(context).inflate(
when(mScreen.findPreference(anyString())).thenReturn(mCategory); R.layout.app_entities_header, null /* root */);
final Preference seeAllPreference = new Preference(context);
final Preference dividerPreference = new Preference(context);
mRecentAppsPreference = spy(new LayoutPreference(context, appEntitiesHeaderView));
when(mScreen.findPreference(RecentAppsPreferenceController.KEY_SEE_ALL)) mController = spy(new RecentAppsPreferenceController(context, "test_key"));
.thenReturn(mSeeAllPref); mController.setFragment(mFragment);
mController.mAppEntitiesController = mock(AppEntitiesHeaderController.class);
mController.mRecentAppsPreference = mRecentAppsPreference;
mController.mAllAppPref = seeAllPreference;
mController.mDivider = dividerPreference;
when(mScreen.findPreference(RecentAppsPreferenceController.KEY_ALL_APP_INFO))
.thenReturn(seeAllPreference);
when(mScreen.findPreference(RecentAppsPreferenceController.KEY_DIVIDER)) when(mScreen.findPreference(RecentAppsPreferenceController.KEY_DIVIDER))
.thenReturn(mDivider); .thenReturn(dividerPreference);
when(mCategory.getContext()).thenReturn(mContext); when(mScreen.findPreference("test_key")).thenReturn(mRecentAppsPreference);
when(mRecentAppsPreference.findViewById(R.id.app_entities_header)).thenReturn(
appEntitiesHeaderView);
} }
@Test @Test
public void isAlwaysAvailable() { public void getAvailabilityStatus_hasRecentApps_shouldReturnAvailable() {
assertThat(mController.isAvailable()).isTrue(); final List<UsageStats> stats = new ArrayList<>();
final UsageStats stat1 = new UsageStats();
stat1.mLastTimeUsed = System.currentTimeMillis();
stat1.mPackageName = "pkg.class";
stats.add(stat1);
// stat1 is valid app.
when(mAppState.getEntry(stat1.mPackageName, UserHandle.myUserId()))
.thenReturn(mAppEntry);
when(mPackageManager.resolveActivity(any(Intent.class), anyInt()))
.thenReturn(new ResolveInfo());
when(mUsageStatsManager.queryUsageStats(anyInt(), anyLong(), anyLong()))
.thenReturn(stats);
mAppEntry.info = mApplicationInfo;
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
} }
@Test @Test
public void doNotIndexCategory() { public void getAvailabilityStatus_noRecentApps_shouldReturnAvailableUnsearchable() {
final List<String> nonIndexable = new ArrayList<>(); // No data
assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE_UNSEARCHABLE);
mController.updateNonIndexableKeys(nonIndexable);
assertThat(nonIndexable).containsAllOf(mController.getPreferenceKey(),
RecentAppsPreferenceController.KEY_DIVIDER);
} }
@Test @Test
public void onDisplayAndUpdateState_shouldRefreshUi() { public void displayPreferenceAndUpdateState_shouldRefreshUi() {
mController = spy(new RecentAppsPreferenceController(mContext, (Application) null, null)); doNothing().when(mController).refreshUi();
doNothing().when(mController).refreshUi(mContext);
mController.displayPreference(mScreen); mController.displayPreference(mScreen);
mController.updateState(mCategory); mController.updateState(mScreen);
verify(mController, times(2)).refreshUi(mContext); verify(mController, times(2)).refreshUi();
} }
@Test @Test
@Config(qualifiers = "mcc999") public void displayPreference_shouldSetupAppEntitiesHeaderController() {
public void display_shouldNotShowRecents_showAppInfoPreference() {
mController.displayPreference(mScreen); mController.displayPreference(mScreen);
verify(mCategory, never()).addPreference(any(Preference.class)); assertThat(mController.mAppEntitiesController).isNotNull();
verify(mCategory).setTitle(null);
verify(mSeeAllPref).setTitle(R.string.applications_settings);
verify(mSeeAllPref).setIcon(null);
verify(mDivider).setVisible(false);
} }
@Test @Test
public void display_showRecents() { public void updateState_threeValidRecentOpenAppsSet_setAppEntityThreeTime() {
final List<UsageStats> stats = new ArrayList<>();
final UsageStats stat1 = new UsageStats();
final UsageStats stat2 = new UsageStats();
final UsageStats stat3 = new UsageStats();
stat1.mLastTimeUsed = System.currentTimeMillis();
stat1.mPackageName = "pkg.class";
stats.add(stat1);
stat2.mLastTimeUsed = System.currentTimeMillis();
stat2.mPackageName = "pkg.class2";
stats.add(stat2);
stat3.mLastTimeUsed = System.currentTimeMillis();
stat3.mPackageName = "pkg.class3";
stats.add(stat3);
// stat1, stat2 are valid apps. stat3 is invalid.
when(mAppState.getEntry(stat1.mPackageName, UserHandle.myUserId()))
.thenReturn(mAppEntry);
when(mAppState.getEntry(stat2.mPackageName, UserHandle.myUserId()))
.thenReturn(mAppEntry);
when(mAppState.getEntry(stat3.mPackageName, UserHandle.myUserId()))
.thenReturn(mAppEntry);
when(mPackageManager.resolveActivity(any(Intent.class), anyInt()))
.thenReturn(new ResolveInfo());
when(mUsageStatsManager.queryUsageStats(anyInt(), anyLong(), anyLong()))
.thenReturn(stats);
mAppEntry.info = mApplicationInfo;
mController.updateState(mRecentAppsPreference);
verify(mController.mAppEntitiesController, times(3))
.setAppEntity(anyInt(), any(AppEntityInfo.class));
assertThat(mController.mRecentAppsPreference.isVisible()).isTrue();
assertThat(mController.mDivider.isVisible()).isTrue();
assertThat(mController.mAllAppPref.isVisible()).isFalse();
}
@Test
public void updateState_oneValidRecentOpenAppSet_setAppEntityOneTime() {
final List<UsageStats> stats = new ArrayList<>(); final List<UsageStats> stats = new ArrayList<>();
final UsageStats stat1 = new UsageStats(); final UsageStats stat1 = new UsageStats();
final UsageStats stat2 = new UsageStats(); final UsageStats stat2 = new UsageStats();
@@ -175,7 +228,7 @@ public class RecentAppsPreferenceControllerTest {
stats.add(stat2); stats.add(stat2);
stat3.mLastTimeUsed = System.currentTimeMillis(); stat3.mLastTimeUsed = System.currentTimeMillis();
stat3.mPackageName = "pkg.class2"; stat3.mPackageName = "pkg.class3";
stats.add(stat3); stats.add(stat3);
// stat1, stat2 are valid apps. stat3 is invalid. // stat1, stat2 are valid apps. stat3 is invalid.
@@ -191,20 +244,19 @@ public class RecentAppsPreferenceControllerTest {
.thenReturn(stats); .thenReturn(stats);
mAppEntry.info = mApplicationInfo; mAppEntry.info = mApplicationInfo;
mController.displayPreference(mScreen); mController.updateState(mRecentAppsPreference);
verify(mCategory).setTitle(R.string.recent_app_category_title);
// Only add stat1. stat2 is skipped because of the package name, stat3 skipped because // Only add stat1. stat2 is skipped because of the package name, stat3 skipped because
// it's invalid app. // it's invalid app.
verify(mCategory, times(1)).addPreference(any(Preference.class)); verify(mController.mAppEntitiesController, times(1))
.setAppEntity(anyInt(), any(AppEntityInfo.class));
verify(mSeeAllPref).setSummary(null); assertThat(mController.mRecentAppsPreference.isVisible()).isTrue();
verify(mSeeAllPref).setIcon(R.drawable.ic_chevron_right_24dp); assertThat(mController.mDivider.isVisible()).isTrue();
verify(mDivider).setVisible(true); assertThat(mController.mAllAppPref.isVisible()).isFalse();
} }
@Test @Test
public void display_powerSaverMode_showNoRecents() { public void updateState_powerSaverModeOn_headerIsNotVisible() {
when(mPowerManager.isPowerSaveMode()).thenReturn(true); when(mPowerManager.isPowerSaveMode()).thenReturn(true);
final List<UsageStats> stats = new ArrayList<>(); final List<UsageStats> stats = new ArrayList<>();
@@ -223,17 +275,15 @@ public class RecentAppsPreferenceControllerTest {
.thenReturn(stats); .thenReturn(stats);
mAppEntry.info = mApplicationInfo; mAppEntry.info = mApplicationInfo;
mController.displayPreference(mScreen); mController.updateState(mRecentAppsPreference);
verify(mCategory, never()).addPreference(any(Preference.class)); assertThat(mController.mRecentAppsPreference.isVisible()).isFalse();
verify(mCategory).setTitle(null); assertThat(mController.mDivider.isVisible()).isFalse();
verify(mSeeAllPref).setTitle(R.string.applications_settings); assertThat(mController.mAllAppPref.isVisible()).isTrue();
verify(mSeeAllPref).setIcon(null);
verify(mDivider).setVisible(false);
} }
@Test @Test
public void display_showRecentsWithInstantApp() { public void updateState_instantAppSet_shouldSetAppEntityForInstantApp() {
// Regular app. // Regular app.
final List<UsageStats> stats = new ArrayList<>(); final List<UsageStats> stats = new ArrayList<>();
final UsageStats stat1 = new UsageStats(); final UsageStats stat1 = new UsageStats();
@@ -258,7 +308,6 @@ public class RecentAppsPreferenceControllerTest {
// Only the regular app stat1 should have its intent resolve. // Only the regular app stat1 should have its intent resolve.
when(mPackageManager.resolveActivity(argThat(intentMatcher(stat1.mPackageName)), anyInt())) when(mPackageManager.resolveActivity(argThat(intentMatcher(stat1.mPackageName)), anyInt()))
.thenReturn(new ResolveInfo()); .thenReturn(new ResolveInfo());
when(mUsageStatsManager.queryUsageStats(anyInt(), anyLong(), anyLong())) when(mUsageStatsManager.queryUsageStats(anyInt(), anyLong(), anyLong()))
.thenReturn(stats); .thenReturn(stats);
@@ -266,17 +315,14 @@ public class RecentAppsPreferenceControllerTest {
ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider", ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
(InstantAppDataProvider) (ApplicationInfo info) -> info == stat2Entry.info); (InstantAppDataProvider) (ApplicationInfo info) -> info == stat2Entry.info);
mController.displayPreference(mScreen); mController.updateState(mRecentAppsPreference);
ArgumentCaptor<Preference> prefCaptor = ArgumentCaptor.forClass(Preference.class); verify(mController.mAppEntitiesController, times(2))
verify(mCategory, times(2)).addPreference(prefCaptor.capture()); .setAppEntity(anyInt(), any(AppEntityInfo.class));
List<Preference> prefs = prefCaptor.getAllValues();
assertThat(prefs.get(1).getKey()).isEqualTo(stat1.mPackageName);
assertThat(prefs.get(0).getKey()).isEqualTo(stat2.mPackageName);
} }
@Test @Test
public void display_showRecentsWithNullAppEntryOrInfo() { public void updateState_withNullAppEntryOrInfo_shouldNotCrash() {
final List<UsageStats> stats = new ArrayList<>(); final List<UsageStats> stats = new ArrayList<>();
final UsageStats stat1 = new UsageStats(); final UsageStats stat1 = new UsageStats();
final UsageStats stat2 = new UsageStats(); final UsageStats stat2 = new UsageStats();
@@ -299,63 +345,11 @@ public class RecentAppsPreferenceControllerTest {
.thenReturn(stats); .thenReturn(stats);
// We should not crash here. // We should not crash here.
mController.displayPreference(mScreen); mController.updateState(mRecentAppsPreference);
} }
@Test @Test
public void display_hasRecentButNoneDisplayable_showAppInfo() { public void updateState_hiddenSystemModuleSet_shouldNotShowHiddenSystemModule() {
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(mPackageManager.resolveActivity(any(Intent.class), anyInt()))
.thenReturn(new ResolveInfo());
when(mUsageStatsManager.queryUsageStats(anyInt(), anyLong(), anyLong()))
.thenReturn(stats);
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);
}
@Test
public void display_showRecents_formatSummary() {
final UsageStats stat1 = new UsageStats();
stat1.mLastTimeUsed = System.currentTimeMillis();
stat1.mPackageName = "pkg.class";
final List<UsageStats> stats = new ArrayList<>();
stats.add(stat1);
when(mAppState.getEntry(stat1.mPackageName, UserHandle.myUserId()))
.thenReturn(mAppEntry);
when(mPackageManager.resolveActivity(any(Intent.class), anyInt()))
.thenReturn(new ResolveInfo());
when(mUsageStatsManager.queryUsageStats(anyInt(), anyLong(), anyLong()))
.thenReturn(stats);
mAppEntry.info = mApplicationInfo;
mController.displayPreference(mScreen);
verify(mCategory).addPreference(argThat(summaryMatches("0 minutes ago")));
}
@Test
public void displayPreference_shouldNotShowHiddenSystemModule() {
final List<UsageStats> stats = new ArrayList<>(); final List<UsageStats> stats = new ArrayList<>();
// Regular app. // Regular app.
final UsageStats stat1 = new UsageStats(); final UsageStats stat1 = new UsageStats();
@@ -389,24 +383,17 @@ public class RecentAppsPreferenceControllerTest {
final List<ModuleInfo> modules = new ArrayList<>(); final List<ModuleInfo> modules = new ArrayList<>();
modules.add(moduleInfo2); modules.add(moduleInfo2);
when(mPackageManager.getInstalledModules(anyInt() /* flags */)) when(mPackageManager.getInstalledModules(anyInt() /* flags */))
.thenReturn(modules); .thenReturn(modules);
when(mPackageManager.resolveActivity(any(Intent.class), anyInt())) when(mPackageManager.resolveActivity(any(Intent.class), anyInt()))
.thenReturn(new ResolveInfo()); .thenReturn(new ResolveInfo());
when(mUsageStatsManager.queryUsageStats(anyInt(), anyLong(), anyLong())) when(mUsageStatsManager.queryUsageStats(anyInt(), anyLong(), anyLong()))
.thenReturn(stats); .thenReturn(stats);
mController.displayPreference(mScreen); mController.updateState(mRecentAppsPreference);
// Only add stat1. stat2 is skipped because it is hidden module. // Only add stat1. stat2 is skipped because it is hidden module.
final ArgumentCaptor<Preference> prefCaptor = ArgumentCaptor.forClass(Preference.class); verify(mController.mAppEntitiesController).setAppEntity(anyInt(), any(AppEntityInfo.class));
verify(mCategory).addPreference(prefCaptor.capture());
final Preference pref = prefCaptor.getValue();
assertThat(pref.getKey()).isEqualTo(stat1.mPackageName);
}
private static ArgumentMatcher<Preference> summaryMatches(String expected) {
return preference -> TextUtils.equals(expected, preference.getSummary());
} }
// Used for matching an intent with a specific package name. // Used for matching an intent with a specific package name.