Implement work-profile infra in BasePreferenceController

- Add settings:forWork in xml
- Set mIsForWork based on xml attribute
- Delete WorkProfilePreferenceController and move its function to
BasePreferenceController

Fixes: 123376083
Test: Add work profile, go to Settings->System->Language&input,
UI should show work profile related items
Change-Id: Id2dcbb0e158c117cdfd363466a275f4e133c345e
This commit is contained in:
Raff Tsai
2019-12-02 10:55:29 +08:00
parent 9700435b4d
commit f71db73025
13 changed files with 132 additions and 149 deletions

View File

@@ -13,17 +13,24 @@
*/
package com.android.settings.core;
import static com.android.settings.dashboard.DashboardFragment.CATEGORY;
import android.annotation.IntDef;
import android.app.settings.SettingsEnums;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.SettingsSlicesContract;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import com.android.settings.Utils;
import com.android.settings.slices.SettingsSliceProvider;
import com.android.settings.slices.SliceData;
import com.android.settings.slices.Sliceable;
@@ -109,9 +116,11 @@ public abstract class BasePreferenceController extends AbstractPreferenceControl
*/
public static final int DISABLED_DEPENDENT_SETTING = 5;
protected final String mPreferenceKey;
protected UiBlockListener mUiBlockListener;
private boolean mIsForWork;
@Nullable
private UserHandle mWorkProfileUser;
/**
* Instantiate a controller as specified controller type and user-defined key.
@@ -151,6 +160,34 @@ public abstract class BasePreferenceController extends AbstractPreferenceControl
}
}
/**
* Instantiate a controller as specified controller type and work profile
* <p/>
* This is done through reflection. Do not use this method unless you know what you are doing.
*
* @param context application context
* @param controllerName class name of the {@link BasePreferenceController}
* @param key attribute android:key of the {@link Preference}
* @param isWorkProfile is this controller only for work profile user?
*/
public static BasePreferenceController createInstance(Context context, String controllerName,
String key, boolean isWorkProfile) {
try {
final Class<?> clazz = Class.forName(controllerName);
final Constructor<?> preferenceConstructor =
clazz.getConstructor(Context.class, String.class);
final Object[] params = new Object[]{context, key};
final BasePreferenceController controller =
(BasePreferenceController) preferenceConstructor.newInstance(params);
controller.setForWork(isWorkProfile);
return controller;
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException
| IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException(
"Invalid preference controller: " + controllerName, e);
}
}
public BasePreferenceController(Context context, String preferenceKey) {
super(context);
mPreferenceKey = preferenceKey;
@@ -166,6 +203,9 @@ public abstract class BasePreferenceController extends AbstractPreferenceControl
* </p>
* The status is used for the convenience methods: {@link #isAvailable()},
* {@link #isSupported()}
* </p>
* The inherited class doesn't need to check work profile is existed or not if
* android:forWork="true" is set in preference xml.
*/
@AvailabilityStatus
public abstract int getAvailabilityStatus();
@@ -198,12 +238,18 @@ public abstract class BasePreferenceController extends AbstractPreferenceControl
* {@link #DISABLED_DEPENDENT_SETTING}, then the setting will be disabled by default in the
* DashboardFragment, and it is up to the {@link BasePreferenceController} to enable the
* preference at the right time.
*
* <p>
* This function also check if work profile is existed when android:forWork="true" is set for
* the controller in preference xml.
* TODO (mfritze) Build a dependency mechanism to allow a controller to easily define the
* dependent setting.
*/
@Override
public final boolean isAvailable() {
if (mIsForWork && mWorkProfileUser == null) {
return false;
}
final int availabilityStatus = getAvailabilityStatus();
return (availabilityStatus == AVAILABLE
|| availabilityStatus == AVAILABLE_UNSEARCHABLE
@@ -266,6 +312,41 @@ public abstract class BasePreferenceController extends AbstractPreferenceControl
}
}
/**
* Indicates this controller is only for work profile user
*/
void setForWork(boolean forWork) {
mIsForWork = forWork;
if (mIsForWork) {
mWorkProfileUser = Utils.getManagedProfile(UserManager.get(mContext));
}
}
/**
* Launches the specified fragment for the work profile user if the associated
* {@link Preference} is clicked. Otherwise just forward it to the super class.
*
* @param preference the preference being clicked.
* @return {@code true} if handled.
*/
@Override
public boolean handlePreferenceTreeClick(Preference preference) {
if (!TextUtils.equals(preference.getKey(), getPreferenceKey())) {
return super.handlePreferenceTreeClick(preference);
}
if (!mIsForWork || mWorkProfileUser == null) {
return super.handlePreferenceTreeClick(preference);
}
new SubSettingLauncher(preference.getContext())
.setDestination(preference.getFragment())
.setSourceMetricsCategory(preference.getExtras().getInt(CATEGORY,
SettingsEnums.PAGE_UNKNOWN))
.setArguments(preference.getExtras())
.setUserHandle(mWorkProfileUser)
.launch();
return true;
}
/**
* Updates raw data for search provider.
*
@@ -316,4 +397,13 @@ public abstract class BasePreferenceController extends AbstractPreferenceControl
*/
public interface UiBlocker {
}
/**
* @return Non-{@code null} {@link UserHandle} when a work profile is enabled.
* Otherwise {@code null}.
*/
@Nullable
protected UserHandle getWorkProfileUser() {
return mWorkProfileUser;
}
}

View File

@@ -17,6 +17,7 @@
package com.android.settings.core;
import static com.android.settings.core.PreferenceXmlParserUtils.METADATA_CONTROLLER;
import static com.android.settings.core.PreferenceXmlParserUtils.METADATA_FOR_WORK;
import static com.android.settings.core.PreferenceXmlParserUtils.METADATA_KEY;
import android.annotation.NonNull;
@@ -55,7 +56,7 @@ public class PreferenceControllerListHelper {
try {
preferenceMetadata = PreferenceXmlParserUtils.extractMetadata(context, xmlResId,
MetadataFlag.FLAG_NEED_KEY | MetadataFlag.FLAG_NEED_PREF_CONTROLLER
| MetadataFlag.FLAG_INCLUDE_PREF_SCREEN);
| MetadataFlag.FLAG_INCLUDE_PREF_SCREEN | MetadataFlag.FLAG_FOR_WORK);
} catch (IOException | XmlPullParserException e) {
Log.e(TAG, "Failed to parse preference xml for getting controllers", e);
return controllers;
@@ -72,6 +73,7 @@ public class PreferenceControllerListHelper {
} catch (IllegalStateException e) {
Log.d(TAG, "Could not find Context-only controller for pref: " + controllerName);
final String key = metadata.getString(METADATA_KEY);
final boolean isWorkProfile = metadata.getBoolean(METADATA_FOR_WORK, false);
if (TextUtils.isEmpty(key)) {
Log.w(TAG, "Controller requires key but it's not defined in xml: "
+ controllerName);
@@ -79,7 +81,7 @@ public class PreferenceControllerListHelper {
}
try {
controller = BasePreferenceController.createInstance(context, controllerName,
key);
key, isWorkProfile);
} catch (IllegalStateException e2) {
Log.w(TAG, "Cannot instantiate controller from reflection: " + controllerName);
continue;

View File

@@ -72,7 +72,8 @@ public class PreferenceXmlParserUtils {
MetadataFlag.FLAG_NEED_PREF_SUMMARY,
MetadataFlag.FLAG_NEED_PREF_ICON,
MetadataFlag.FLAG_NEED_SEARCHABLE,
MetadataFlag.FLAG_UNAVAILABLE_SLICE_SUBTITLE})
MetadataFlag.FLAG_UNAVAILABLE_SLICE_SUBTITLE,
MetadataFlag.FLAG_FOR_WORK})
@Retention(RetentionPolicy.SOURCE)
public @interface MetadataFlag {
@@ -87,6 +88,7 @@ public class PreferenceXmlParserUtils {
int FLAG_NEED_SEARCHABLE = 1 << 9;
int FLAG_NEED_PREF_APPEND = 1 << 10;
int FLAG_UNAVAILABLE_SLICE_SUBTITLE = 1 << 11;
int FLAG_FOR_WORK = 1 << 12;
}
public static final String METADATA_PREF_TYPE = "type";
@@ -98,8 +100,8 @@ public class PreferenceXmlParserUtils {
public static final String METADATA_KEYWORDS = "keywords";
public static final String METADATA_SEARCHABLE = "searchable";
public static final String METADATA_APPEND = "staticPreferenceLocation";
public static final String METADATA_UNAVAILABLE_SLICE_SUBTITLE =
"unavailable_slice_subtitle";
public static final String METADATA_UNAVAILABLE_SLICE_SUBTITLE = "unavailable_slice_subtitle";
public static final String METADATA_FOR_WORK = "for_work";
private static final String ENTRIES_SEPARATOR = "|";
@@ -244,6 +246,10 @@ public class PreferenceXmlParserUtils {
preferenceMetadata.putString(METADATA_UNAVAILABLE_SLICE_SUBTITLE,
getUnavailableSliceSubtitle(preferenceAttributes));
}
if (hasFlag(flags, MetadataFlag.FLAG_FOR_WORK)) {
preferenceMetadata.putBoolean(METADATA_FOR_WORK,
isForWork(preferenceAttributes));
}
metadata.add(preferenceMetadata);
preferenceAttributes.recycle();
@@ -329,4 +335,9 @@ public class PreferenceXmlParserUtils {
return styledAttributes.getString(
R.styleable.Preference_unavailableSliceSubtitle);
}
private static boolean isForWork(TypedArray styledAttributes) {
return styledAttributes.getBoolean(
R.styleable.Preference_forWork, false);
}
}

View File

@@ -1,97 +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.core;
import android.content.Context;
import android.os.UserHandle;
import android.os.UserManager;
import android.text.TextUtils;
import androidx.annotation.Nullable;
import androidx.preference.Preference;
import com.android.settings.Utils;
/**
* Abstract class to provide additional logic to deal with optional {@link Preference} entries that
* are used only when work profile is enabled.
*
* <p>TODO(b/123376083): Consider merging this into {@link BasePreferenceController}.</p>
*/
public abstract class WorkProfilePreferenceController extends BasePreferenceController {
@Nullable
private final UserHandle mWorkProfileUser;
/**
* Constructor of {@link WorkProfilePreferenceController}. Called by
* {@link BasePreferenceController#createInstance(Context, String)} through reflection.
*
* @param context {@link Context} to instantiate this controller.
* @param preferenceKey Preference key to be associated with the {@link Preference}.
*/
public WorkProfilePreferenceController(Context context, String preferenceKey) {
super(context, preferenceKey);
mWorkProfileUser = Utils.getManagedProfile(UserManager.get(context));
}
/**
* @return Non-{@code null} {@link UserHandle} when a work profile is enabled.
* Otherwise {@code null}.
*/
@Nullable
protected UserHandle getWorkProfileUser() {
return mWorkProfileUser;
}
/**
* Called back from {@link #handlePreferenceTreeClick(Preference)} to associate source metrics
* category.
*
* @return One of {@link android.app.settings.SettingsEnums}.
*/
protected abstract int getSourceMetricsCategory();
/**
* {@inheritDoc}
*
* <p>When you override this method, do not forget to check {@link #getWorkProfileUser()} to
* see if work profile user actually exists or not.</p>
*/
@AvailabilityStatus
@Override
public int getAvailabilityStatus() {
return mWorkProfileUser != null ? AVAILABLE : DISABLED_FOR_USER;
}
/**
* Launches the specified fragment for the work profile user if the associated
* {@link Preference} is clicked. Otherwise just forward it to the super class.
*
* @param preference the preference being clicked.
* @return {@code true} if handled.
*/
public boolean handlePreferenceTreeClick(Preference preference) {
if (!TextUtils.equals(preference.getKey(), getPreferenceKey())) {
return super.handlePreferenceTreeClick(preference);
}
new SubSettingLauncher(preference.getContext())
.setDestination(preference.getFragment())
.setSourceMetricsCategory(getSourceMetricsCategory())
.setArguments(preference.getExtras())
.setUserHandle(mWorkProfileUser)
.launch();
return true;
}
}