Fix UI issue in LocationSettings

- Add WorkPreferenceController to support directly use work profile
related feature in xml
- Get only work/personal infos in RecentLocationRequestPreferenceController
and RecentLocationRequestSeeAllPreferenceController
- Remove ProfileSelectStorageFragment

Bug: 141601408
Fixes: 146080649
Test: manual, robolectric
Change-Id: Ide39c7a3796e16421f3a5690309c3d746a956de8
This commit is contained in:
Raff Tsai
2019-12-13 16:46:33 +08:00
parent d230b552f5
commit 5ec8efe7e0
21 changed files with 442 additions and 246 deletions

View File

@@ -572,7 +572,7 @@
<item name="android:showDividers">middle</item> <item name="android:showDividers">middle</item>
</style> </style>
<style name="TextAppearance.Tab" parent="TextAppearance.Design.Tab"> <style name="TextAppearance.Tab" parent="@android:style/TextAppearance.DeviceDefault">
<item name="android:textAllCaps">false</item> <item name="android:textAllCaps">false</item>
</style> </style>

View File

@@ -109,7 +109,7 @@
android:title="@string/spellcheckers_settings_for_work_title" android:title="@string/spellcheckers_settings_for_work_title"
android:fragment="com.android.settings.inputmethod.SpellCheckersSettings" android:fragment="com.android.settings.inputmethod.SpellCheckersSettings"
settings:forWork="true" settings:forWork="true"
settings:controller="com.android.settings.language.UserDictionaryForWorkPreferenceController" /> settings:controller="com.android.settings.core.WorkPreferenceController" />
<Preference <Preference
android:key="user_dictionary_settings_for_work_pref" android:key="user_dictionary_settings_for_work_pref"

View File

@@ -32,6 +32,8 @@
android:title="@string/location_recent_location_requests_see_all" android:title="@string/location_recent_location_requests_see_all"
android:icon="@drawable/ic_chevron_right_24dp" android:icon="@drawable/ic_chevron_right_24dp"
android:fragment="com.android.settings.location.RecentLocationRequestSeeAllFragment" android:fragment="com.android.settings.location.RecentLocationRequestSeeAllFragment"
settings:controller="com.android.settings.core.WorkPreferenceController"
settings:forWork="true"
settings:searchable="false"/> settings:searchable="false"/>
<com.android.settingslib.RestrictedSwitchPreference <com.android.settingslib.RestrictedSwitchPreference

View File

@@ -1,28 +0,0 @@
<!--
~ Copyright (C) 2019 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License
-->
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:settings="http://schemas.android.com/apk/res-auto"
android:key="storage_dashboard_screen"
android:title="@string/storage_settings"
android:orderingFromXml="false">
<com.android.settings.deviceinfo.storage.StorageSummaryDonutPreference
android:key="pref_summary"
android:order="0"
settings:searchable="false"
settings:controller="com.android.settings.deviceinfo.storage.StorageSummaryDonutPreferenceController"/>
</PreferenceScreen>

View File

@@ -191,19 +191,6 @@ public final class Utils extends com.android.settingslib.Utils {
return false; return false;
} }
/**
* Returns the UserManager for a given context
*
* @throws IllegalStateException if no UserManager could be retrieved.
*/
public static UserManager getUserManager(Context context) {
final UserManager um = UserManager.get(context);
if (um == null) {
throw new IllegalStateException("Unable to load UserManager");
}
return um;
}
/** /**
* Returns true if Monkey is running. * Returns true if Monkey is running.
*/ */
@@ -679,7 +666,7 @@ public final class Utils extends com.android.settingslib.Utils {
* @throws SecurityException if the given userId does not belong to the current user group. * @throws SecurityException if the given userId does not belong to the current user group.
*/ */
public static int enforceSameOwner(Context context, int userId) { public static int enforceSameOwner(Context context, int userId) {
final UserManager um = getUserManager(context); final UserManager um = UserManager.get(context);
final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId()); final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
if (ArrayUtils.contains(profileIds, userId)) { if (ArrayUtils.contains(profileIds, userId)) {
return userId; return userId;
@@ -699,7 +686,7 @@ public final class Utils extends com.android.settingslib.Utils {
* Returns the user id of the credential owner of the given user id. * Returns the user id of the credential owner of the given user id.
*/ */
public static int getCredentialOwnerUserId(Context context, int userId) { public static int getCredentialOwnerUserId(Context context, int userId) {
final UserManager um = getUserManager(context); final UserManager um = UserManager.get(context);
return um.getCredentialOwnerProfile(userId); return um.getCredentialOwnerProfile(userId);
} }
@@ -836,7 +823,7 @@ public final class Utils extends com.android.settingslib.Utils {
} }
public static boolean isDemoUser(Context context) { public static boolean isDemoUser(Context context) {
return UserManager.isDeviceInDemoMode(context) && getUserManager(context).isDemoUser(); return UserManager.isDeviceInDemoMode(context) && UserManager.get(context).isDemoUser();
} }
public static ComponentName getDeviceOwnerComponent(Context context) { public static ComponentName getDeviceOwnerComponent(Context context) {

View File

@@ -13,6 +13,8 @@
*/ */
package com.android.settings.core; package com.android.settings.core;
import static android.content.Intent.EXTRA_USER_ID;
import static com.android.settings.dashboard.DashboardFragment.CATEGORY; import static com.android.settings.dashboard.DashboardFragment.CATEGORY;
import android.annotation.IntDef; import android.annotation.IntDef;
@@ -20,6 +22,7 @@ import android.app.settings.SettingsEnums;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.Context; import android.content.Context;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle;
import android.os.UserHandle; import android.os.UserHandle;
import android.os.UserManager; import android.os.UserManager;
import android.provider.SettingsSlicesContract; import android.provider.SettingsSlicesContract;
@@ -204,7 +207,7 @@ public abstract class BasePreferenceController extends AbstractPreferenceControl
* The status is used for the convenience methods: {@link #isAvailable()}, * The status is used for the convenience methods: {@link #isAvailable()},
* {@link #isSupported()} * {@link #isSupported()}
* </p> * </p>
* The inherited class doesn't need to check work profile is existed or not if * The inherited class doesn't need to check work profile if
* android:forWork="true" is set in preference xml. * android:forWork="true" is set in preference xml.
*/ */
@AvailabilityStatus @AvailabilityStatus
@@ -337,6 +340,8 @@ public abstract class BasePreferenceController extends AbstractPreferenceControl
if (!mIsForWork || mWorkProfileUser == null) { if (!mIsForWork || mWorkProfileUser == null) {
return super.handlePreferenceTreeClick(preference); return super.handlePreferenceTreeClick(preference);
} }
final Bundle extra = preference.getExtras();
extra.putInt(EXTRA_USER_ID, mWorkProfileUser.getIdentifier());
new SubSettingLauncher(preference.getContext()) new SubSettingLauncher(preference.getContext())
.setDestination(preference.getFragment()) .setDestination(preference.getFragment())
.setSourceMetricsCategory(preference.getExtras().getInt(CATEGORY, .setSourceMetricsCategory(preference.getExtras().getInt(CATEGORY,

View File

@@ -14,27 +14,27 @@
* limitations under the License. * limitations under the License.
*/ */
package com.android.settings.language; package com.android.settings.core;
import android.content.Context; import android.content.Context;
import com.android.settings.core.BasePreferenceController; import androidx.annotation.CallSuper;
/** /**
* Preference controller for "UserDictionary for work". * Base class to be used directly in Xml with settings:forWork="true" attribute.
* * It is used specifically for work profile only preference
* @see UserDictionaryPreferenceController
*/ */
public final class UserDictionaryForWorkPreferenceController public class WorkPreferenceController extends BasePreferenceController {
extends BasePreferenceController {
public UserDictionaryForWorkPreferenceController(Context context, String preferenceKey) { public WorkPreferenceController(Context context, String preferenceKey) {
super(context, preferenceKey); super(context, preferenceKey);
} }
@AvailabilityStatus /**
@Override * Only available when work profile user is existed
*/
@CallSuper
public int getAvailabilityStatus() { public int getAvailabilityStatus() {
return AVAILABLE; return getWorkProfileUser() != null ? AVAILABLE : DISABLED_FOR_USER;
} }
} }

View File

@@ -20,8 +20,8 @@ import android.util.ArrayMap;
import com.android.settings.accounts.AccountDashboardFragment; import com.android.settings.accounts.AccountDashboardFragment;
import com.android.settings.applications.manageapplications.ManageApplications; import com.android.settings.applications.manageapplications.ManageApplications;
import com.android.settings.deviceinfo.StorageDashboardFragment;
import com.android.settings.location.LocationSettings; import com.android.settings.location.LocationSettings;
import com.android.settings.location.RecentLocationRequestSeeAllFragment;
import java.util.Map; import java.util.Map;
@@ -42,9 +42,9 @@ public class ProfileFragmentBridge {
ProfileSelectAccountFragment.class.getName()); ProfileSelectAccountFragment.class.getName());
FRAGMENT_MAP.put(ManageApplications.class.getName(), FRAGMENT_MAP.put(ManageApplications.class.getName(),
ProfileSelectManageApplications.class.getName()); ProfileSelectManageApplications.class.getName());
FRAGMENT_MAP.put(StorageDashboardFragment.class.getName(),
ProfileSelectStorageFragment.class.getName());
FRAGMENT_MAP.put(LocationSettings.class.getName(), FRAGMENT_MAP.put(LocationSettings.class.getName(),
ProfileSelectLocationFragment.class.getName()); ProfileSelectLocationFragment.class.getName());
FRAGMENT_MAP.put(RecentLocationRequestSeeAllFragment.class.getName(),
ProfileSelectRecentLocationRequestFragment.class.getName());
} }
} }

View File

@@ -16,10 +16,13 @@
package com.android.settings.dashboard.profileselector; package com.android.settings.dashboard.profileselector;
import static android.content.Intent.EXTRA_USER_ID;
import android.annotation.IntDef; import android.annotation.IntDef;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.os.Bundle; import android.os.Bundle;
import android.os.UserHandle;
import android.os.UserManager; import android.os.UserManager;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
@@ -27,6 +30,7 @@ import android.view.ViewGroup;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import androidx.annotation.VisibleForTesting;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
@@ -97,21 +101,7 @@ public abstract class ProfileSelectFragment extends DashboardFragment {
Bundle savedInstanceState) { Bundle savedInstanceState) {
mContentView = (ViewGroup) super.onCreateView(inflater, container, savedInstanceState); mContentView = (ViewGroup) super.onCreateView(inflater, container, savedInstanceState);
final Activity activity = getActivity(); final Activity activity = getActivity();
final int intentUser = activity.getIntent().getContentUserHint(); final int selectedTab = getTabId(activity, getArguments());
int selectedTab = 0;
// Start intent from a specific user eg: adb shell --user 10
if (intentUser > 0 && Utils.getManagedProfile(UserManager.get(activity)).getIdentifier()
== intentUser) {
selectedTab = WORK_TAB;
}
// Set selected tab using fragment argument
final int extraTab = getArguments() != null ? getArguments().getInt(
SettingsActivity.EXTRA_SHOW_FRAGMENT_TAB, -1) : -1;
if (extraTab != -1) {
selectedTab = extraTab;
}
final View tabContainer = mContentView.findViewById(R.id.tab_container); final View tabContainer = mContentView.findViewById(R.id.tab_container);
final ViewPager viewPager = tabContainer.findViewById(R.id.view_pager); final ViewPager viewPager = tabContainer.findViewById(R.id.view_pager);
@@ -155,6 +145,28 @@ public abstract class ProfileSelectFragment extends DashboardFragment {
return TAG; return TAG;
} }
@VisibleForTesting
int getTabId(Activity activity, Bundle bundle) {
if (bundle != null) {
final int extraTab = bundle.getInt(SettingsActivity.EXTRA_SHOW_FRAGMENT_TAB, -1);
if (extraTab != -1) {
return WORK_TAB;
}
final int userId = bundle.getInt(EXTRA_USER_ID, UserHandle.SYSTEM.getIdentifier());
final boolean isWorkProfile = UserManager.get(activity).isManagedProfile(userId);
if (isWorkProfile) {
return WORK_TAB;
}
}
// Start intent from a specific user eg: adb shell --user 10
final int intentUser = activity.getIntent().getContentUserHint();
if (UserManager.get(activity).isManagedProfile(intentUser)) {
return WORK_TAB;
}
return PERSONAL_TAB;
}
static class ViewPagerAdapter extends FragmentStatePagerAdapter { static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final Fragment[] mChildFragments; private final Fragment[] mChildFragments;

View File

@@ -46,9 +46,19 @@ public class ProfileSelectLocationFragment extends ProfileSelectFragment {
@Override @Override
public Fragment[] getFragments() { public Fragment[] getFragments() {
final Bundle workOnly = new Bundle();
workOnly.putInt(EXTRA_PROFILE, ProfileSelectFragment.ProfileType.WORK);
final Fragment workFragment = new LocationWorkProfileSettings();
workFragment.setArguments(workOnly);
final Bundle personalOnly = new Bundle();
personalOnly.putInt(EXTRA_PROFILE, ProfileSelectFragment.ProfileType.PERSONAL);
final Fragment personalFragment = new LocationPersonalSettings();
personalFragment.setArguments(personalOnly);
return new Fragment[]{ return new Fragment[]{
new LocationPersonalSettings(), personalFragment,
new LocationWorkProfileSettings() workFragment
}; };
} }
} }

View File

@@ -0,0 +1,46 @@
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.dashboard.profileselector;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import com.android.settings.location.RecentLocationRequestSeeAllFragment;
/**
* Recent location request page for personal/managed profile.
*/
public class ProfileSelectRecentLocationRequestFragment extends ProfileSelectFragment {
@Override
public Fragment[] getFragments() {
final Bundle workOnly = new Bundle();
workOnly.putInt(EXTRA_PROFILE, ProfileSelectFragment.ProfileType.WORK);
final Fragment workFragment = new RecentLocationRequestSeeAllFragment();
workFragment.setArguments(workOnly);
final Bundle personalOnly = new Bundle();
personalOnly.putInt(EXTRA_PROFILE, ProfileSelectFragment.ProfileType.PERSONAL);
final Fragment personalFragment = new RecentLocationRequestSeeAllFragment();
personalFragment.setArguments(personalOnly);
return new Fragment[]{
personalFragment, //0
workFragment
};
}
}

View File

@@ -1,64 +0,0 @@
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.dashboard.profileselector;
import android.os.Bundle;
import android.os.UserHandle;
import android.os.UserManager;
import android.os.storage.VolumeInfo;
import androidx.fragment.app.Fragment;
import com.android.settings.R;
import com.android.settings.Utils;
import com.android.settings.deviceinfo.StorageDashboardFragment;
import com.android.settings.deviceinfo.StorageProfileFragment;
/**
* Storage Setting page for personal/managed profile.
*/
public class ProfileSelectStorageFragment extends ProfileSelectFragment {
@Override
public Fragment[] getFragments() {
final Bundle storageBundle = new Bundle();
storageBundle.putString(VolumeInfo.EXTRA_VOLUME_ID, VolumeInfo.ID_PRIVATE_INTERNAL);
storageBundle.putInt(EXTRA_PROFILE, ProfileSelectFragment.ProfileType.PERSONAL);
final Fragment storageDashboardFragment = new StorageDashboardFragment();
storageDashboardFragment.setArguments(storageBundle);
final UserHandle userHandle = Utils.getManagedProfile(UserManager.get(getActivity()));
if (userHandle != null) {
storageBundle.putInt(StorageProfileFragment.USER_ID_EXTRA, userHandle.getIdentifier());
}
final Fragment storageProfileFragment = new StorageProfileFragment();
storageProfileFragment.setArguments(storageBundle);
return new Fragment[]{
storageDashboardFragment,
storageProfileFragment
};
}
@Override
protected int getPreferenceScreenResId() {
return R.xml.storage_summary_donut;
}
}

View File

@@ -21,6 +21,7 @@ import android.content.Context;
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.dashboard.profileselector.ProfileSelectFragment;
/** /**
* Location Setting page for personal profile. * Location Setting page for personal profile.
@@ -49,9 +50,14 @@ public class LocationPersonalSettings extends DashboardFragment {
super.onAttach(context); super.onAttach(context);
use(AppLocationPermissionPreferenceController.class).init(this); use(AppLocationPermissionPreferenceController.class).init(this);
use(RecentLocationRequestPreferenceController.class).init(this);
use(LocationServicePreferenceController.class).init(this); use(LocationServicePreferenceController.class).init(this);
use(LocationFooterPreferenceController.class).init(this); use(LocationFooterPreferenceController.class).init(this);
final int profileType = getArguments().getInt(ProfileSelectFragment.EXTRA_PROFILE);
final RecentLocationRequestPreferenceController controller = use(
RecentLocationRequestPreferenceController.class);
controller.init(this);
controller.setProfileType(profileType);
} }
@Override @Override

View File

@@ -21,6 +21,7 @@ import android.content.Context;
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.dashboard.profileselector.ProfileSelectFragment;
/** /**
* Location Setting page for managed profile. * Location Setting page for managed profile.
@@ -49,10 +50,15 @@ public class LocationWorkProfileSettings extends DashboardFragment {
super.onAttach(context); super.onAttach(context);
use(AppLocationPermissionPreferenceController.class).init(this); use(AppLocationPermissionPreferenceController.class).init(this);
use(RecentLocationRequestPreferenceController.class).init(this);
use(LocationServiceForWorkPreferenceController.class).init(this); use(LocationServiceForWorkPreferenceController.class).init(this);
use(LocationFooterPreferenceController.class).init(this); use(LocationFooterPreferenceController.class).init(this);
use(LocationForWorkPreferenceController.class).init(this); use(LocationForWorkPreferenceController.class).init(this);
final int profileType = getArguments().getInt(ProfileSelectFragment.EXTRA_PROFILE);
final RecentLocationRequestPreferenceController controller = use(
RecentLocationRequestPreferenceController.class);
controller.init(this);
controller.setProfileType(profileType);
} }
@Override @Override

View File

@@ -16,6 +16,7 @@ package com.android.settings.location;
import android.content.Context; import android.content.Context;
import android.os.Bundle; import android.os.Bundle;
import android.os.UserHandle; import android.os.UserHandle;
import android.os.UserManager;
import androidx.annotation.VisibleForTesting; import androidx.annotation.VisibleForTesting;
import androidx.preference.Preference; import androidx.preference.Preference;
@@ -26,15 +27,20 @@ import com.android.settings.R;
import com.android.settings.applications.appinfo.AppInfoDashboardFragment; import com.android.settings.applications.appinfo.AppInfoDashboardFragment;
import com.android.settings.core.SubSettingLauncher; import com.android.settings.core.SubSettingLauncher;
import com.android.settings.dashboard.DashboardFragment; import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
import com.android.settingslib.location.RecentLocationApps; import com.android.settingslib.location.RecentLocationApps;
import com.android.settingslib.widget.apppreference.AppPreference; import com.android.settingslib.widget.apppreference.AppPreference;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class RecentLocationRequestPreferenceController extends LocationBasePreferenceController { public class RecentLocationRequestPreferenceController extends LocationBasePreferenceController {
private final RecentLocationApps mRecentLocationApps; public static final int MAX_APPS = 3;
@VisibleForTesting
RecentLocationApps mRecentLocationApps;
private PreferenceCategory mCategoryRecentLocationRequests; private PreferenceCategory mCategoryRecentLocationRequests;
private int mType = ProfileSelectFragment.ProfileType.ALL;
/** Used in this class and {@link RecentLocationRequestSeeAllPreferenceController} */ /** Used in this class and {@link RecentLocationRequestSeeAllPreferenceController} */
static class PackageEntryClickedListener implements Preference.OnPreferenceClickListener { static class PackageEntryClickedListener implements Preference.OnPreferenceClickListener {
@@ -75,23 +81,27 @@ public class RecentLocationRequestPreferenceController extends LocationBasePrefe
super.displayPreference(screen); super.displayPreference(screen);
mCategoryRecentLocationRequests = screen.findPreference(getPreferenceKey()); mCategoryRecentLocationRequests = screen.findPreference(getPreferenceKey());
final Context prefContext = mCategoryRecentLocationRequests.getContext(); final Context prefContext = mCategoryRecentLocationRequests.getContext();
final List<RecentLocationApps.Request> recentLocationRequests = final List<RecentLocationApps.Request> recentLocationRequests = new ArrayList<>();
mRecentLocationApps.getAppListSorted(false); final UserManager userManager = UserManager.get(mContext);
if (recentLocationRequests.size() > 3) { for (RecentLocationApps.Request request : mRecentLocationApps.getAppListSorted(
// Display the top 3 preferences to container in original order. false /* systemApps */)) {
for (int i = 0; i < 3; i++) { if (isRequestMatchesProfileType(userManager, request, mType)) {
mCategoryRecentLocationRequests.addPreference( recentLocationRequests.add(request);
createAppPreference(prefContext, recentLocationRequests.get(i))); if (recentLocationRequests.size() == MAX_APPS) {
break;
}
} }
} else if (recentLocationRequests.size() > 0) { }
if (recentLocationRequests.size() > 0) {
// Add preferences to container in original order (already sorted by recency). // Add preferences to container in original order (already sorted by recency).
for (RecentLocationApps.Request request : recentLocationRequests) { for (RecentLocationApps.Request request : recentLocationRequests) {
mCategoryRecentLocationRequests.addPreference( mCategoryRecentLocationRequests.addPreference(
createAppPreference(prefContext, request)); createAppPreference(prefContext, request, mFragment));
} }
} else { } else {
// If there's no item to display, add a "No recent apps" item. // If there's no item to display, add a "No recent apps" item.
final Preference banner = createAppPreference(prefContext); final Preference banner = new AppPreference(prefContext);
banner.setTitle(R.string.location_no_recent_apps); banner.setTitle(R.string.location_no_recent_apps);
banner.setSelectable(false); banner.setSelectable(false);
mCategoryRecentLocationRequests.addPreference(banner); mCategoryRecentLocationRequests.addPreference(banner);
@@ -103,19 +113,42 @@ public class RecentLocationRequestPreferenceController extends LocationBasePrefe
mCategoryRecentLocationRequests.setEnabled(mLocationEnabler.isEnabled(mode)); mCategoryRecentLocationRequests.setEnabled(mLocationEnabler.isEnabled(mode));
} }
@VisibleForTesting /**
AppPreference createAppPreference(Context prefContext) { * Initialize {@link ProfileSelectFragment.ProfileType} of the controller
return new AppPreference(prefContext); *
* @param type {@link ProfileSelectFragment.ProfileType} of the controller.
*/
public void setProfileType(@ProfileSelectFragment.ProfileType int type) {
mType = type;
} }
@VisibleForTesting /**
AppPreference createAppPreference(Context prefContext, RecentLocationApps.Request request) { * Create a {@link AppPreference}
final AppPreference pref = createAppPreference(prefContext); */
pref.setSummary(request.contentDescription); public static AppPreference createAppPreference(Context prefContext,
RecentLocationApps.Request request, DashboardFragment fragment) {
final AppPreference pref = new AppPreference(prefContext);
pref.setIcon(request.icon); pref.setIcon(request.icon);
pref.setTitle(request.label); pref.setTitle(request.label);
pref.setOnPreferenceClickListener(new PackageEntryClickedListener( pref.setOnPreferenceClickListener(new PackageEntryClickedListener(
mFragment, request.packageName, request.userHandle)); fragment, request.packageName, request.userHandle));
return pref; return pref;
} }
/**
* Return if the {@link RecentLocationApps.Request} matches current UI
* {@ProfileSelectFragment.ProfileType}
*/
public static boolean isRequestMatchesProfileType(UserManager userManager,
RecentLocationApps.Request request, @ProfileSelectFragment.ProfileType int type) {
final boolean isWorkProfile = userManager.isManagedProfile(
request.userHandle.getIdentifier());
if (isWorkProfile && (type & ProfileSelectFragment.ProfileType.WORK) != 0) {
return true;
}
if (!isWorkProfile && (type & ProfileSelectFragment.ProfileType.PERSONAL) != 0) {
return true;
}
return false;
}
} }

View File

@@ -23,6 +23,7 @@ import android.view.MenuItem;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent; import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
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.dashboard.profileselector.ProfileSelectFragment;
import com.android.settings.search.BaseSearchIndexProvider; import com.android.settings.search.BaseSearchIndexProvider;
import com.android.settingslib.search.SearchIndexable; import com.android.settingslib.search.SearchIndexable;
@@ -49,9 +50,11 @@ public class RecentLocationRequestSeeAllFragment extends DashboardFragment {
@Override @Override
public void onAttach(Context context) { public void onAttach(Context context) {
super.onAttach(context); super.onAttach(context);
final int profileType = getArguments().getInt(ProfileSelectFragment.EXTRA_PROFILE);
mController = use(RecentLocationRequestSeeAllPreferenceController.class); mController = use(RecentLocationRequestSeeAllPreferenceController.class);
mController.init(this); mController.init(this);
mController.setProfileType(profileType);
} }
@Override @Override

View File

@@ -15,16 +15,21 @@
*/ */
package com.android.settings.location; package com.android.settings.location;
import android.content.Context; import static com.android.settings.location.RecentLocationRequestPreferenceController.createAppPreference;
import static com.android.settings.location.RecentLocationRequestPreferenceController.isRequestMatchesProfileType;
import android.content.Context;
import android.os.UserManager;
import androidx.annotation.VisibleForTesting;
import androidx.preference.Preference; import androidx.preference.Preference;
import androidx.preference.PreferenceScreen; import androidx.preference.PreferenceScreen;
import com.android.settings.R; import com.android.settings.R;
import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
import com.android.settingslib.location.RecentLocationApps; import com.android.settingslib.location.RecentLocationApps;
import com.android.settingslib.widget.apppreference.AppPreference; import com.android.settingslib.widget.apppreference.AppPreference;
import java.util.ArrayList;
import java.util.List; import java.util.List;
/** Preference controller for preference category displaying all recent location requests. */ /** Preference controller for preference category displaying all recent location requests. */
@@ -35,6 +40,7 @@ public class RecentLocationRequestSeeAllPreferenceController
private RecentLocationApps mRecentLocationApps; private RecentLocationApps mRecentLocationApps;
private boolean mShowSystem = false; private boolean mShowSystem = false;
private Preference mPreference; private Preference mPreference;
private int mType = ProfileSelectFragment.ProfileType.ALL;
public RecentLocationRequestSeeAllPreferenceController(Context context, String key) { public RecentLocationRequestSeeAllPreferenceController(Context context, String key) {
super(context, key); super(context, key);
@@ -56,33 +62,39 @@ public class RecentLocationRequestSeeAllPreferenceController
public void updateState(Preference preference) { public void updateState(Preference preference) {
mCategoryAllRecentLocationRequests.removeAll(); mCategoryAllRecentLocationRequests.removeAll();
mPreference = preference; mPreference = preference;
List<RecentLocationApps.Request> requests = mRecentLocationApps.getAppListSorted(
mShowSystem); final UserManager userManager = UserManager.get(mContext);
if (requests.isEmpty()) { final List<RecentLocationApps.Request> recentLocationRequests = new ArrayList<>();
for (RecentLocationApps.Request request : mRecentLocationApps.getAppListSorted(
mShowSystem)) {
if (isRequestMatchesProfileType(userManager, request, mType)) {
recentLocationRequests.add(request);
}
}
if (recentLocationRequests.isEmpty()) {
// If there's no item to display, add a "No recent apps" item. // If there's no item to display, add a "No recent apps" item.
final Preference banner = new AppPreference(mContext); final Preference banner = new AppPreference(mContext);
banner.setTitle(R.string.location_no_recent_apps); banner.setTitle(R.string.location_no_recent_apps);
banner.setSelectable(false); banner.setSelectable(false);
mCategoryAllRecentLocationRequests.addPreference(banner); mCategoryAllRecentLocationRequests.addPreference(banner);
} else { } else {
for (RecentLocationApps.Request request : requests) { for (RecentLocationApps.Request request : recentLocationRequests) {
Preference appPreference = createAppPreference(preference.getContext(), request); final Preference appPreference = createAppPreference(
preference.getContext(),
request, mFragment);
mCategoryAllRecentLocationRequests.addPreference(appPreference); mCategoryAllRecentLocationRequests.addPreference(appPreference);
} }
} }
} }
@VisibleForTesting /**
AppPreference createAppPreference( * Initialize {@link ProfileSelectFragment.ProfileType} of the controller
Context prefContext, RecentLocationApps.Request request) { *
final AppPreference pref = new AppPreference(prefContext); * @param type {@link ProfileSelectFragment.ProfileType} of the controller.
pref.setSummary(request.contentDescription); */
pref.setIcon(request.icon); public void setProfileType(@ProfileSelectFragment.ProfileType int type) {
pref.setTitle(request.label); mType = type;
pref.setOnPreferenceClickListener(
new RecentLocationRequestPreferenceController.PackageEntryClickedListener(
mFragment, request.packageName, request.userHandle));
return pref;
} }
public void setShowSystem(boolean showSystem) { public void setShowSystem(boolean showSystem) {

View File

@@ -16,6 +16,8 @@
package com.android.settings.dashboard.profileselector; package com.android.settings.dashboard.profileselector;
import static android.content.Intent.EXTRA_USER_ID;
import static com.android.settings.dashboard.profileselector.ProfileSelectFragment.PERSONAL_TAB; import static com.android.settings.dashboard.profileselector.ProfileSelectFragment.PERSONAL_TAB;
import static com.android.settings.dashboard.profileselector.ProfileSelectFragment.WORK_TAB; import static com.android.settings.dashboard.profileselector.ProfileSelectFragment.WORK_TAB;
@@ -27,22 +29,13 @@ import static org.mockito.Mockito.when;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.android.settings.R;
import com.android.settings.SettingsActivity; import com.android.settings.SettingsActivity;
import com.android.settings.SettingsPreferenceFragmentTest; import com.android.settings.SettingsPreferenceFragmentTest;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.google.android.material.tabs.TabLayout;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -52,16 +45,18 @@ import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner; import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config; import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements; import java.util.HashSet;
import org.robolectric.shadows.androidx.fragment.FragmentController; import java.util.Set;
@RunWith(RobolectricTestRunner.class) @RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowUserManager.class})
public class ProfileSelectFragmentTest { public class ProfileSelectFragmentTest {
private Context mContext; private Context mContext;
private TestProfileSelectFragment mFragment; private TestProfileSelectFragment mFragment;
private FragmentActivity mActivity; private FragmentActivity mActivity;
private ShadowUserManager mUserManager;
@Before @Before
public void setUp() { public void setUp() {
@@ -71,30 +66,51 @@ public class ProfileSelectFragmentTest {
mFragment = spy(new TestProfileSelectFragment()); mFragment = spy(new TestProfileSelectFragment());
when(mFragment.getContext()).thenReturn(mContext); when(mFragment.getContext()).thenReturn(mContext);
when(mFragment.getActivity()).thenReturn(mActivity); when(mFragment.getActivity()).thenReturn(mActivity);
mUserManager = ShadowUserManager.getShadow();
} }
@Test @Test
@Config(shadows = ShadowPreferenceFragmentCompat.class) public void getTabId_no_setCorrectTab() {
public void onCreateView_no_setCorrectTab() { assertThat(mFragment.getTabId(mActivity, null)).isEqualTo(PERSONAL_TAB);
FragmentController.of(mFragment, new Intent()).create(0 /* containerViewId*/,
null /* bundle */).start().resume().visible().get();
final TabLayout tabs = mFragment.getView().findViewById(R.id.tabs);
assertThat(tabs.getSelectedTabPosition()).isEqualTo(PERSONAL_TAB);
} }
@Test @Test
@Config(shadows = ShadowPreferenceFragmentCompat.class) public void getTabId_setArgument_setCorrectTab() {
public void onCreateView_setArgument_setCorrectTab() {
final Bundle bundle = new Bundle(); final Bundle bundle = new Bundle();
bundle.putInt(SettingsActivity.EXTRA_SHOW_FRAGMENT_TAB, WORK_TAB); bundle.putInt(SettingsActivity.EXTRA_SHOW_FRAGMENT_TAB, WORK_TAB);
mFragment.setArguments(bundle);
FragmentController.of(mFragment, new Intent()).create(0 /* containerViewId*/, assertThat(mFragment.getTabId(mActivity, bundle)).isEqualTo(WORK_TAB);
bundle).start().resume().visible().get(); }
final TabLayout tabs = mFragment.getView().findViewById(R.id.tabs);
assertThat(tabs.getSelectedTabPosition()).isEqualTo(WORK_TAB); @Test
public void getTabId_setWorkId_getCorrectTab() {
final Bundle bundle = new Bundle();
bundle.putInt(EXTRA_USER_ID, 10);
final Set<Integer> profileIds = new HashSet<>();
profileIds.add(10);
mUserManager.setManagedProfiles(profileIds);
assertThat(mFragment.getTabId(mActivity, bundle)).isEqualTo(WORK_TAB);
}
@Test
public void getTabId_setPersonalId_getCorrectTab() {
final Bundle bundle = new Bundle();
bundle.putInt(EXTRA_USER_ID, 0);
assertThat(mFragment.getTabId(mActivity, bundle)).isEqualTo(PERSONAL_TAB);
}
@Test
public void getTabId_setPersonalIdByIntent_getCorrectTab() {
final Set<Integer> profileIds = new HashSet<>();
profileIds.add(10);
mUserManager.setManagedProfiles(profileIds);
final Intent intent = spy(new Intent());
when(intent.getContentUserHint()).thenReturn(10);
when(mActivity.getIntent()).thenReturn(intent);
assertThat(mFragment.getTabId(mActivity, null)).isEqualTo(WORK_TAB);
} }
public static class TestProfileSelectFragment extends ProfileSelectFragment { public static class TestProfileSelectFragment extends ProfileSelectFragment {
@@ -107,41 +123,4 @@ public class ProfileSelectFragmentTest {
}; };
} }
} }
@Implements(PreferenceFragmentCompat.class)
public static class ShadowPreferenceFragmentCompat {
private Context mContext;
@Implementation
protected View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
mContext = inflater.getContext();
return inflater.inflate(R.layout.preference_list_fragment, container);
}
@Implementation
protected RecyclerView getListView() {
final RecyclerView recyclerView = new RecyclerView(mContext);
recyclerView.setAdapter(new RecyclerView.Adapter() {
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup,
int i) {
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
}
@Override
public int getItemCount() {
return 0;
}
});
return recyclerView;
}
}
} }

View File

@@ -0,0 +1,48 @@
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.dashboard.profileselector;
import static com.android.settings.dashboard.profileselector.ProfileSelectFragment.EXTRA_PROFILE;
import static com.google.common.truth.Truth.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class ProfileSelectLocationFragmentTest {
private ProfileSelectLocationFragment mProfileSelectLocationFragment;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mProfileSelectLocationFragment = new ProfileSelectLocationFragment();
}
@Test
public void getFragments_containsCorrectBundle() {
assertThat(mProfileSelectLocationFragment.getFragments().length).isEqualTo(2);
assertThat(mProfileSelectLocationFragment.getFragments()[0].getArguments().getInt(
EXTRA_PROFILE, -1)).isEqualTo(ProfileSelectFragment.ProfileType.PERSONAL);
assertThat(mProfileSelectLocationFragment.getFragments()[1].getArguments().getInt(
EXTRA_PROFILE, -1)).isEqualTo(ProfileSelectFragment.ProfileType.WORK);
}
}

View File

@@ -0,0 +1,129 @@
/*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.location;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.UserHandle;
import androidx.preference.PreferenceCategory;
import androidx.preference.PreferenceScreen;
import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settingslib.location.RecentLocationApps;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowUserManager.class})
public class RecentLocationRequestPreferenceControllerTest {
@Mock
private PreferenceScreen mScreen;
@Mock
private PreferenceCategory mCategory;
private Context mContext;
private RecentLocationRequestPreferenceController mController;
private ShadowUserManager mUserManager;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
mController = spy(
new RecentLocationRequestPreferenceController(mContext, "key"));
when(mCategory.getContext()).thenReturn(mContext);
when(mScreen.findPreference("key")).thenReturn(mCategory);
mUserManager = ShadowUserManager.getShadow();
mController.mRecentLocationApps = spy(new RecentLocationApps(mContext));
}
@Test
public void updateState_whenAppListMoreThanThree_shouldDisplayTopThreeApps() {
final List<RecentLocationApps.Request> requests = createMockRequest(6);
when(mController.mRecentLocationApps.getAppListSorted(false)).thenReturn(requests);
mController.displayPreference(mScreen);
verify(mCategory, times(3)).addPreference(any());
}
@Test
public void updateState_workProfile_shouldShowOnlyWorkProfileApps() {
final List<RecentLocationApps.Request> requests = createMockRequest(6);
when(mController.mRecentLocationApps.getAppListSorted(false)).thenReturn(requests);
mController.setProfileType(ProfileSelectFragment.ProfileType.WORK);
final Set<Integer> profileIds = new HashSet<>();
profileIds.add(4);
profileIds.add(5);
mUserManager.setManagedProfiles(profileIds);
mController.displayPreference(mScreen);
// contains userId 4 and userId 5
verify(mCategory, times(2)).addPreference(any());
}
@Test
public void updateState_Personal_shouldShowOnlyPersonalApps() {
final List<RecentLocationApps.Request> requests = createMockRequest(6);
when(mController.mRecentLocationApps.getAppListSorted(false)).thenReturn(requests);
mController.setProfileType(ProfileSelectFragment.ProfileType.PERSONAL);
final Set<Integer> profileIds = new HashSet<>();
for (int i = 0; i < 4; i++) {
profileIds.add(i);
}
mUserManager.setManagedProfiles(profileIds);
mController.displayPreference(mScreen);
// contains userId 4 and userId 5
verify(mCategory, times(2)).addPreference(any());
}
private List<RecentLocationApps.Request> createMockRequest(int count) {
final List<RecentLocationApps.Request> requests = new ArrayList<>();
for (int i = 0; i < count; i++) {
final Drawable icon = mock(Drawable.class);
// Add mock accesses
final RecentLocationApps.Request request = new RecentLocationApps.Request(
"packageName", UserHandle.of(i), icon,
"appTitle" + i, false, "appSummary" + i, 1000 - i);
requests.add(request);
}
return requests;
}
}

View File

@@ -27,8 +27,8 @@ import com.google.android.collect.Maps;
import org.robolectric.RuntimeEnvironment; import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Implementation; import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements; import org.robolectric.annotation.Implements;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.annotation.Resetter; import org.robolectric.annotation.Resetter;
import org.robolectric.shadow.api.Shadow;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@@ -132,6 +132,16 @@ public class ShadowUserManager extends org.robolectric.shadows.ShadowUserManager
return mUserSwitchEnabled; return mUserSwitchEnabled;
} }
@Implementation
protected boolean isManagedProfile(int userId) {
return mManagedProfiles.contains(userId);
}
public void setManagedProfiles(Set<Integer> profileIds) {
mManagedProfiles.clear();
mManagedProfiles.addAll(profileIds);
}
public void setUserSwitcherEnabled(boolean userSwitchEnabled) { public void setUserSwitcherEnabled(boolean userSwitchEnabled) {
mUserSwitchEnabled = userSwitchEnabled; mUserSwitchEnabled = userSwitchEnabled;
} }