Cleanup to screensaver settings for O

Reworked the way screensaver settings are laid out for O. Instead of
using the options menu and dialogs to navigate screensaver options,
there are now two rows: one row for the screensaver choice and
optionally its own settings, and one row for the "when to show" setting.
And now there's a nice obvious button you can press to preview your
choices.

Test: 'export ROBOTEST_FILTER="RadioButtonListFragmentTest";\
mmm -j20 packages/apps/Settings/tests/robotests'

Bug: 35031991
Change-Id: Ie7d2055fb45f6dfe72e34cb9598d9a25f7bee75a
This commit is contained in:
Evan Laird
2017-03-22 11:36:18 -04:00
parent e6c87c4684
commit 227affaf29
22 changed files with 1263 additions and 461 deletions

View File

@@ -1,94 +0,0 @@
<!--
Copyright (C) 2012 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.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:clickable="true"
android:focusable="true"
android:orientation="horizontal"
android:background="?android:attr/selectableItemBackground" >
<!-- Dream icon -->
<ImageView
android:id="@android:id/icon"
android:layout_width="@android:dimen/app_icon_size"
android:layout_height="@android:dimen/app_icon_size"
android:layout_centerVertical="true"
android:layout_marginBottom="10dp"
android:layout_marginStart="0dp"
android:layout_marginEnd="6dp"
android:layout_marginTop="10dp"
android:contentDescription="@null"
android:maxHeight="@android:dimen/app_icon_size"
android:maxWidth="@android:dimen/app_icon_size"
android:scaleType="fitCenter" />
<!-- Dream caption -->
<TextView
android:id="@android:id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_centerVertical="true"
android:ellipsize="end"
android:singleLine="true"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textAlignment="viewStart"
android:labelFor="@android:id/button2" />
<!-- Dream radio button -->
<RadioButton
android:id="@android:id/button1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:duplicateParentState="true"
android:clickable="false"
android:focusable="false" />
<!-- Divider -->
<ImageView
android:id="@+id/divider"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:contentDescription="@null"
android:src="@drawable/nav_divider" />
<!-- Settings icon -->
<ImageView
android:id="@android:id/button2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_margin="0dip"
android:background="?android:attr/selectableItemBackground"
android:contentDescription="@string/screensaver_settings_button"
android:padding="8dip"
android:clickable="true"
android:focusable="true"
android:src="@drawable/ic_settings" />
</LinearLayout>

View File

@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (C) 2017 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.
-->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:gravity="bottom"
android:paddingTop="4dp"
android:paddingStart="72dp"
android:paddingEnd="72dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/dream_start_now_button"
style="@style/DreamStartButton"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/screensaver_settings_dream_start"
android:paddingEnd="8dp" />
</LinearLayout>

View File

@@ -1056,4 +1056,18 @@
<item>90</item>
</string-array>
<string-array name="when_to_start_screensaver_entries" translatable="false">
<item>@string/screensaver_settings_summary_sleep</item>
<item>@string/screensaver_settings_summary_dock</item>
<item>@string/screensaver_settings_summary_either_long</item>
<item>@string/screensaver_settings_summary_never</item>
</string-array>
<string-array name="when_to_start_screensaver_values" translatable="false">
<item>while_charging_only</item>
<item>while_docked_only</item>
<item>either_charging_or_docked</item>
<item>never</item>
</string-array>
</resources>

View File

@@ -421,6 +421,8 @@
<style name="AppActionPrimaryButton" parent="android:Widget.Material.Button.Colored"/>
<style name="DreamStartButton" parent="android:Widget.Material.Button" />
<style name="LockPatternStyle">
<item name="*android:regularColor">@color/lock_pattern_view_regular_color</item>
<item name="*android:successColor">@color/lock_pattern_view_success_color</item>

View File

@@ -76,7 +76,7 @@
<Preference
android:key="screensaver"
android:title="@string/screensaver_settings_title"
android:fragment="com.android.settings.DreamSettings" />
android:fragment="com.android.settings.dream.DreamSettings" />
<!-- Hide night mode for now
<ListPreference

View File

@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2017 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/com.android.settings"
android:title="@string/screensaver_settings_title" >
<com.android.settings.widget.GearPreference
android:key="current_screensaver"
android:title="@string/screensaver_settings_current"
android:fragment="com.android.settings.dream.CurrentDreamPicker" />
<Preference
android:key="when_to_start"
android:title="@string/screensaver_settings_when_to_dream"
android:fragment="com.android.settings.dream.WhenToDreamPicker" />
<!-- Layout preference doesn't obey allowDividerAbove, so put it in a PreferenceCategory -->
<PreferenceCategory>
<com.android.settings.applications.LayoutPreference
android:key="dream_start_now_button_container"
android:selectable="false"
android:layout="@layout/dream_start_button" />
</PreferenceCategory>
</PreferenceScreen>

View File

@@ -1,364 +0,0 @@
/*
* Copyright (C) 2012 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;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceViewHolder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Switch;
import android.widget.TextView;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.widget.SwitchBar;
import com.android.settingslib.dream.DreamBackend;
import com.android.settingslib.dream.DreamBackend.DreamInfo;
import java.util.List;
public class DreamSettings extends SettingsPreferenceFragment implements
SwitchBar.OnSwitchChangeListener {
private static final String TAG = DreamSettings.class.getSimpleName();
static final boolean DEBUG = false;
private static final int DIALOG_WHEN_TO_DREAM = 1;
private static final String PACKAGE_SCHEME = "package";
private final PackageReceiver mPackageReceiver = new PackageReceiver();
private Context mContext;
private DreamBackend mBackend;
private SwitchBar mSwitchBar;
private MenuItem[] mMenuItemsWhenEnabled;
private boolean mRefreshing;
@Override
public int getHelpResource() {
return R.string.help_url_dreams;
}
@Override
public void onAttach(Activity activity) {
logd("onAttach(%s)", activity.getClass().getSimpleName());
super.onAttach(activity);
mContext = activity;
}
@Override
public int getMetricsCategory() {
return MetricsEvent.DREAM;
}
@Override
public void onCreate(Bundle icicle) {
logd("onCreate(%s)", icicle);
super.onCreate(icicle);
mBackend = new DreamBackend(getActivity());
setHasOptionsMenu(true);
}
@Override
public void onSwitchChanged(Switch switchView, boolean isChecked) {
if (!mRefreshing) {
mBackend.setEnabled(isChecked);
refreshFromBackend();
}
}
@Override
public void onStart() {
logd("onStart()");
super.onStart();
}
@Override
public void onDestroyView() {
logd("onDestroyView()");
super.onDestroyView();
mSwitchBar.removeOnSwitchChangeListener(this);
mSwitchBar.hide();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
logd("onActivityCreated(%s)", savedInstanceState);
super.onActivityCreated(savedInstanceState);
TextView emptyView = (TextView) getView().findViewById(android.R.id.empty);
emptyView.setText(R.string.screensaver_settings_disabled_prompt);
setEmptyView(emptyView);
final SettingsActivity sa = (SettingsActivity) getActivity();
mSwitchBar = sa.getSwitchBar();
mSwitchBar.addOnSwitchChangeListener(this);
mSwitchBar.show();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
logd("onCreateOptionsMenu()");
boolean isEnabled = mBackend.isEnabled();
// create "start" action
MenuItem start = createMenuItem(menu, R.string.screensaver_settings_dream_start,
MenuItem.SHOW_AS_ACTION_NEVER,
isEnabled, new Runnable(){
@Override
public void run() {
mBackend.startDreaming();
}});
// create "when to dream" overflow menu item
MenuItem whenToDream = createMenuItem(menu,
R.string.screensaver_settings_when_to_dream,
MenuItem.SHOW_AS_ACTION_NEVER,
isEnabled,
new Runnable() {
@Override
public void run() {
showDialog(DIALOG_WHEN_TO_DREAM);
}});
// create "help" overflow menu item (make sure it appears last)
super.onCreateOptionsMenu(menu, inflater);
mMenuItemsWhenEnabled = new MenuItem[] { start, whenToDream };
}
private MenuItem createMenuItem(Menu menu,
int titleRes, int actionEnum, boolean isEnabled, final Runnable onClick) {
MenuItem item = menu.add(titleRes);
item.setShowAsAction(actionEnum);
item.setEnabled(isEnabled);
item.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
onClick.run();
return true;
}
});
return item;
}
@Override
public Dialog onCreateDialog(int dialogId) {
logd("onCreateDialog(%s)", dialogId);
if (dialogId == DIALOG_WHEN_TO_DREAM)
return createWhenToDreamDialog();
return super.onCreateDialog(dialogId);
}
@Override
public int getDialogMetricsCategory(int dialogId) {
if (dialogId == DIALOG_WHEN_TO_DREAM) {
return MetricsEvent.DIALOG_DREAM_START_DELAY;
}
return 0;
}
private Dialog createWhenToDreamDialog() {
final CharSequence[] items = {
mContext.getString(R.string.screensaver_settings_summary_dock),
mContext.getString(R.string.screensaver_settings_summary_sleep),
mContext.getString(R.string.screensaver_settings_summary_either_short)
};
int initialSelection = mBackend.isActivatedOnDock() && mBackend.isActivatedOnSleep() ? 2
: mBackend.isActivatedOnDock() ? 0
: mBackend.isActivatedOnSleep() ? 1
: -1;
return new AlertDialog.Builder(mContext)
.setTitle(R.string.screensaver_settings_when_to_dream)
.setSingleChoiceItems(items, initialSelection, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
mBackend.setActivatedOnDock(item == 0 || item == 2);
mBackend.setActivatedOnSleep(item == 1 || item == 2);
dialog.dismiss();
}
})
.create();
}
@Override
public void onPause() {
logd("onPause()");
super.onPause();
mContext.unregisterReceiver(mPackageReceiver);
}
@Override
public void onResume() {
logd("onResume()");
super.onResume();
refreshFromBackend();
// listen for package changes
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addDataScheme(PACKAGE_SCHEME);
mContext.registerReceiver(mPackageReceiver , filter);
}
public static int getSummaryResource(Context context) {
DreamBackend backend = new DreamBackend(context);
boolean isEnabled = backend.isEnabled();
boolean activatedOnSleep = backend.isActivatedOnSleep();
boolean activatedOnDock = backend.isActivatedOnDock();
boolean activatedOnEither = activatedOnSleep && activatedOnDock;
return !isEnabled ? R.string.screensaver_settings_summary_off
: activatedOnEither ? R.string.screensaver_settings_summary_either_long
: activatedOnSleep ? R.string.screensaver_settings_summary_sleep
: activatedOnDock ? R.string.screensaver_settings_summary_dock
: 0;
}
public static CharSequence getSummaryTextWithDreamName(Context context) {
DreamBackend backend = new DreamBackend(context);
boolean isEnabled = backend.isEnabled();
if (!isEnabled) {
return context.getString(R.string.screensaver_settings_summary_off);
} else {
return backend.getActiveDreamName();
}
}
private void refreshFromBackend() {
logd("refreshFromBackend()");
mRefreshing = true;
boolean dreamsEnabled = mBackend.isEnabled();
if (mSwitchBar.isChecked() != dreamsEnabled) {
mSwitchBar.setChecked(dreamsEnabled);
}
if (getPreferenceScreen() == null) {
setPreferenceScreen(getPreferenceManager().createPreferenceScreen(getContext()));
}
getPreferenceScreen().removeAll();
if (dreamsEnabled) {
List<DreamBackend.DreamInfo> dreamInfos = mBackend.getDreamInfos();
final int N = dreamInfos.size();
for (int i = 0; i < N; i++) {
getPreferenceScreen().addPreference(
new DreamInfoPreference(getPrefContext(), dreamInfos.get(i)));
}
}
if (mMenuItemsWhenEnabled != null) {
for (MenuItem menuItem : mMenuItemsWhenEnabled) {
menuItem.setEnabled(dreamsEnabled);
}
}
mRefreshing = false;
}
private static void logd(String msg, Object... args) {
if (DEBUG) Log.d(TAG, args == null || args.length == 0 ? msg : String.format(msg, args));
}
private class DreamInfoPreference extends Preference {
private final DreamInfo mInfo;
public DreamInfoPreference(Context context, DreamInfo info) {
super(context);
mInfo = info;
setLayoutResource(R.layout.dream_info_row);
setTitle(mInfo.caption);
setIcon(mInfo.icon);
}
public void onBindViewHolder(final PreferenceViewHolder holder) {
super.onBindViewHolder(holder);
// bind radio button
RadioButton radioButton = (RadioButton) holder.findViewById(android.R.id.button1);
radioButton.setChecked(mInfo.isActive);
radioButton.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
holder.itemView.onTouchEvent(event);
return false;
}
});
// bind settings button + divider
boolean showSettings = mInfo.settingsComponentName != null;
View settingsDivider = holder.findViewById(R.id.divider);
settingsDivider.setVisibility(showSettings ? View.VISIBLE : View.INVISIBLE);
ImageView settingsButton = (ImageView) holder.findViewById(android.R.id.button2);
settingsButton.setVisibility(showSettings ? View.VISIBLE : View.INVISIBLE);
settingsButton.setAlpha(mInfo.isActive ? 1f : Utils.DISABLED_ALPHA);
settingsButton.setEnabled(mInfo.isActive);
settingsButton.setFocusable(mInfo.isActive);
settingsButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mBackend.launchSettings(mInfo);
}
});
}
@Override
public void performClick() {
if (mInfo.isActive)
return;
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
DreamInfoPreference preference =
(DreamInfoPreference) getPreferenceScreen().getPreference(i);
preference.mInfo.isActive = false;
preference.notifyChanged();
}
mInfo.isActive = true;
mBackend.setActiveDream(mInfo.componentName);
notifyChanged();
}
}
private class PackageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
logd("PackageReceiver.onReceive");
refreshFromBackend();
}
}
}

View File

@@ -25,7 +25,7 @@ import com.android.settings.DateTimeSettings;
import com.android.settings.DeviceAdminSettings;
import com.android.settings.DeviceInfoSettings;
import com.android.settings.DisplaySettings;
import com.android.settings.DreamSettings;
import com.android.settings.dream.DreamSettings;
import com.android.settings.IccLockSettings;
import com.android.settings.MasterClear;
import com.android.settings.PrivacySettings;

View File

@@ -16,8 +16,8 @@ package com.android.settings.display;
import android.content.Context;
import android.support.v7.preference.Preference;
import com.android.settings.DreamSettings;
import com.android.settings.core.PreferenceController;
import com.android.settings.dream.DreamSettings;
public class ScreenSaverPreferenceController extends PreferenceController {

View File

@@ -0,0 +1,117 @@
/*
* Copyright (C) 2017 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.dream;
import android.content.ComponentName;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.widget.RadioButtonPickerFragment;
import com.android.settingslib.dream.DreamBackend;
import com.android.settingslib.dream.DreamBackend.DreamInfo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public final class CurrentDreamPicker extends RadioButtonPickerFragment {
private DreamBackend mBackend;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mBackend = DreamBackend.getInstance(context);
}
@Override
public int getMetricsCategory() {
return MetricsProto.MetricsEvent.DREAM;
}
@Override
protected boolean setDefaultKey(String key) {
Map<String, ComponentName> componentNameMap = getDreamComponentsMap();
if (componentNameMap.get(key) != null) {
mBackend.setActiveDream(componentNameMap.get(key));
return true;
}
return false;
}
@Override
protected String getDefaultKey() {
return mBackend.getActiveDream().flattenToString();
}
@Override
protected List<? extends CandidateInfo> getCandidates() {
final List<DreamCandidateInfo> candidates;
candidates = mBackend.getDreamInfos().stream()
.map(DreamCandidateInfo::new)
.collect(Collectors.toList());
return candidates;
}
@Override
protected void onSelectionPerformed(boolean success) {
super.onSelectionPerformed(success);
getActivity().finish();
}
private Map<String, ComponentName> getDreamComponentsMap() {
Map<String, ComponentName> comps = new HashMap<>();
mBackend.getDreamInfos()
.forEach((info) ->
comps.put(info.componentName.flattenToString(), info.componentName));
return comps;
}
private static final class DreamCandidateInfo extends CandidateInfo {
private final CharSequence name;
private final Drawable icon;
private final String key;
DreamCandidateInfo(DreamInfo info) {
super(true);
name = info.caption;
icon = info.icon;
key = info.componentName.flattenToString();
}
@Override
public CharSequence loadLabel() {
return name;
}
@Override
public Drawable loadIcon() {
return icon;
}
@Override
public String getKey() {
return key;
}
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright (C) 2017 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.dream;
import android.content.Context;
import android.support.v7.preference.Preference;
import com.android.settings.core.PreferenceController;
import com.android.settings.widget.GearPreference;
import com.android.settingslib.dream.DreamBackend;
import com.android.settingslib.dream.DreamBackend.DreamInfo;
import java.util.Optional;
public class CurrentDreamPreferenceController extends PreferenceController {
private final DreamBackend mBackend;
private final static String TAG = "CurrentDreamPreferenceController";
private final static String CURRENT_SCREENSAVER = "current_screensaver";
public CurrentDreamPreferenceController(Context context) {
super(context);
mBackend = DreamBackend.getInstance(context);
}
@Override
public boolean isAvailable() {
return mBackend.getDreamInfos().size() > 0;
}
@Override
public String getPreferenceKey() {
return CURRENT_SCREENSAVER;
}
@Override
public void updateState(Preference preference) {
super.updateState(preference);
preference.setSummary(mBackend.getActiveDreamName());
setGearClickListenerForPreference(preference);
}
private void setGearClickListenerForPreference(Preference preference) {
if (!(preference instanceof GearPreference)) return;
GearPreference gearPreference = (GearPreference)preference;
Optional<DreamInfo> info = getActiveDreamInfo();
if (!info.isPresent() || info.get().settingsComponentName == null) {
gearPreference.setOnGearClickListener(null);
return;
}
gearPreference.setOnGearClickListener(gearPref -> launchScreenSaverSettings());
}
private void launchScreenSaverSettings() {
Optional<DreamInfo> info = getActiveDreamInfo();
if (!info.isPresent()) return;
mBackend.launchSettings(info.get());
}
private Optional<DreamInfo> getActiveDreamInfo() {
return mBackend.getDreamInfos()
.stream()
.filter((info) -> info.isActive)
.findFirst();
}
}

View File

@@ -0,0 +1,147 @@
/*
* Copyright (C) 2017 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.dream;
import android.provider.SearchIndexableResource;
import android.support.annotation.VisibleForTesting;
import com.android.settings.R;
import com.android.settings.core.PreferenceController;
import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.search.BaseSearchIndexProvider;
import com.android.settingslib.dream.DreamBackend;
import com.android.settingslib.dream.DreamBackend.WhenToDream;
import java.util.ArrayList;
import android.content.Context;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import java.util.Arrays;
import java.util.List;
import static com.android.settingslib.dream.DreamBackend.EITHER;
import static com.android.settingslib.dream.DreamBackend.NEVER;
import static com.android.settingslib.dream.DreamBackend.WHILE_CHARGING;
import static com.android.settingslib.dream.DreamBackend.WHILE_DOCKED;
public class DreamSettings extends DashboardFragment {
private static final String TAG = "DreamSettings";
static final String WHILE_CHARGING_ONLY = "while_charging_only";
static final String WHILE_DOCKED_ONLY = "while_docked_only";
static final String EITHER_CHARGING_OR_DOCKED = "either_charging_or_docked";
static final String NEVER_DREAM = "never";
@WhenToDream
static int getSettingFromPrefKey(String key) {
switch (key) {
case WHILE_CHARGING_ONLY:
return WHILE_CHARGING;
case WHILE_DOCKED_ONLY:
return WHILE_DOCKED;
case EITHER_CHARGING_OR_DOCKED:
return EITHER;
case NEVER_DREAM:
default:
return NEVER;
}
}
static String getKeyFromSetting(@WhenToDream int dreamSetting) {
switch (dreamSetting) {
case WHILE_CHARGING:
return WHILE_CHARGING_ONLY;
case WHILE_DOCKED:
return WHILE_DOCKED_ONLY;
case EITHER:
return EITHER_CHARGING_OR_DOCKED;
case NEVER:
default:
return NEVER_DREAM;
}
}
static int getDreamSettingDescriptionResId(@WhenToDream int dreamSetting) {
switch (dreamSetting) {
case WHILE_CHARGING:
return R.string.screensaver_settings_summary_sleep;
case WHILE_DOCKED:
return R.string.screensaver_settings_summary_dock;
case EITHER:
return R.string.screensaver_settings_summary_either_long;
case NEVER:
default:
return R.string.screensaver_settings_summary_never;
}
}
@Override
public int getMetricsCategory() {
return MetricsEvent.DREAM;
}
@Override
protected int getPreferenceScreenResId() {
return R.xml.dream_fragment_overview;
}
@Override
protected String getLogTag() {
return TAG;
}
@Override
protected List<PreferenceController> getPreferenceControllers(Context context) {
return buildPreferenceControllers(context);
}
public static CharSequence getSummaryTextWithDreamName(Context context) {
DreamBackend backend = DreamBackend.getInstance(context);
return getSummaryTextFromBackend(backend, context);
}
@VisibleForTesting
static CharSequence getSummaryTextFromBackend(DreamBackend backend, Context context) {
if (!backend.isEnabled()) {
return context.getString(R.string.screensaver_settings_summary_off);
} else {
return backend.getActiveDreamName();
}
}
private static List<PreferenceController> buildPreferenceControllers(Context context) {
List<PreferenceController> controllers = new ArrayList<>();
controllers.add(new CurrentDreamPreferenceController(context));
controllers.add(new WhenToDreamPreferenceController(context));
controllers.add(new StartNowPreferenceController(context));
return controllers;
}
public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER
= new BaseSearchIndexProvider() {
@Override
public List<SearchIndexableResource> getXmlResourcesToIndex(
Context context, boolean enabled) {
final SearchIndexableResource sir = new SearchIndexableResource(context);
sir.xmlResId = R.xml.dream_fragment_overview;
return Arrays.asList(sir);
}
@Override
public List<PreferenceController> getPreferenceControllers(Context context) {
return buildPreferenceControllers(context);
}
};
}

View File

@@ -0,0 +1,66 @@
/*
* Copyright (C) 2017 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.dream;
import android.content.Context;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceScreen;
import android.widget.Button;
import com.android.settings.R;
import com.android.settings.applications.LayoutPreference;
import com.android.settings.core.PreferenceController;
import com.android.settingslib.dream.DreamBackend;
public class StartNowPreferenceController extends PreferenceController {
private static final String TAG = "StartNowPreferenceController";
private static final String PREF_KEY = "dream_start_now_button_container";
private final DreamBackend mBackend;
public StartNowPreferenceController(Context context) {
super(context);
mBackend = DreamBackend.getInstance(context);
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public String getPreferenceKey() {
return PREF_KEY;
}
@Override
public void displayPreference(PreferenceScreen screen) {
super.displayPreference(screen);
LayoutPreference pref = (LayoutPreference) screen.findPreference(getPreferenceKey());
Button startButton = (Button)pref.findViewById(R.id.dream_start_now_button);
startButton.setOnClickListener(v -> mBackend.startDreaming());
}
@Override
public void updateState(Preference preference) {
super.updateState(preference);
Button startButton = (Button)((LayoutPreference)preference)
.findViewById(R.id.dream_start_now_button);
startButton.setEnabled(mBackend.getWhenToDreamSetting() != DreamBackend.NEVER);
}
}

View File

@@ -0,0 +1,115 @@
/*
* Copyright (C) 2017 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.dream;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.R;
import com.android.settings.widget.RadioButtonPickerFragment;
import com.android.settingslib.dream.DreamBackend;
import java.util.ArrayList;
import java.util.List;
public class WhenToDreamPicker extends RadioButtonPickerFragment {
private static final String TAG = "WhenToDreamPicker";
private DreamBackend mBackend;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mBackend = DreamBackend.getInstance(context);
}
@Override
public int getMetricsCategory() {
return MetricsProto.MetricsEvent.DREAM;
}
@Override
protected List<? extends CandidateInfo> getCandidates() {
final String[] entries = entries();
final String[] values = keys();
final List<WhenToDreamCandidateInfo> candidates = new ArrayList<>();
if (entries == null || entries.length <= 0) return null;
if (values == null || values.length != entries.length) {
throw new IllegalArgumentException("Entries and values must be of the same length.");
}
for (int i = 0; i < entries.length; i++) {
candidates.add(new WhenToDreamCandidateInfo(entries[i], values[i]));
}
return candidates;
}
private String[] entries() {
return getResources().getStringArray(R.array.when_to_start_screensaver_entries);
}
private String[] keys() {
return getResources().getStringArray(R.array.when_to_start_screensaver_values);
}
@Override
protected String getDefaultKey() {
return DreamSettings.getKeyFromSetting(mBackend.getWhenToDreamSetting());
}
@Override
protected boolean setDefaultKey(String key) {
mBackend.setWhenToDream(DreamSettings.getSettingFromPrefKey(key));
return true;
}
@Override
protected void onSelectionPerformed(boolean success) {
super.onSelectionPerformed(success);
getActivity().finish();
}
private final class WhenToDreamCandidateInfo extends CandidateInfo {
private final String name;
private final String key;
WhenToDreamCandidateInfo(String title, String value) {
super(true);
name = title;
key = value;
}
@Override
public CharSequence loadLabel() {
return name;
}
@Override
public Drawable loadIcon() {
return null;
}
@Override
public String getKey() {
return key;
}
}
}

View File

@@ -0,0 +1,52 @@
/*
* Copyright (C) 2017 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.dream;
import android.content.Context;
import android.support.v7.preference.Preference;
import com.android.settings.core.PreferenceController;
import com.android.settingslib.dream.DreamBackend;
public class WhenToDreamPreferenceController extends PreferenceController {
private static final String WHEN_TO_START = "when_to_start";
private final DreamBackend mBackend;
WhenToDreamPreferenceController(Context context) {
super(context);
mBackend = DreamBackend.getInstance(context);
}
@Override
public void updateState(Preference preference) {
super.updateState(preference);
int resId = DreamSettings.getDreamSettingDescriptionResId(mBackend.getWhenToDreamSetting());
preference.setSummary(preference.getContext().getString(resId));
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public String getPreferenceKey() {
return WHEN_TO_START;
}
}

View File

@@ -47,6 +47,7 @@ import com.android.settings.development.DevelopmentSettings;
import com.android.settings.deviceinfo.StorageDashboardFragment;
import com.android.settings.deviceinfo.StorageSettings;
import com.android.settings.display.ScreenZoomSettings;
import com.android.settings.dream.DreamSettings;
import com.android.settings.enterprise.EnterprisePrivacySettings;
import com.android.settings.fuelgauge.BatterySaverSettings;
import com.android.settings.fuelgauge.PowerUsageAdvanced;
@@ -185,6 +186,7 @@ public final class SearchIndexableResources {
R.drawable.ic_settings_accessibility);
addIndex(ChannelImportanceSettings.class, NO_DATA_RES_ID,
R.drawable.ic_settings_notifications);
addIndex(DreamSettings.class, NO_DATA_RES_ID, R.drawable.ic_settings_display);
}
private SearchIndexableResources() {

View File

@@ -0,0 +1,91 @@
/*
* Copyright (C) 2017 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.dream;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.os.UserManager;
import com.android.settings.SettingsRobolectricTestRunner;
import com.android.settings.TestConfig;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settingslib.dream.DreamBackend;
import com.android.settingslib.dream.DreamBackend.DreamInfo;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class CurrentDreamPickerTest {
private static String COMPONENT_KEY = "mocked_component_name_string";
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private DreamBackend mBackend;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Activity mActivity;
@Mock
private UserManager mUserManager;
private CurrentDreamPicker mPicker;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
FakeFeatureFactory.setupForTest(mActivity);
mPicker = new CurrentDreamPicker();
mPicker.onAttach((Context)mActivity);
ReflectionHelpers.setField(mPicker, "mBackend", mBackend);
}
@Test
public void getDefaultShouldReturnActiveDream() {
ComponentName mockComponentName = mock(ComponentName.class);
when(mockComponentName.flattenToString()).thenReturn(COMPONENT_KEY);
when(mBackend.getActiveDream()).thenReturn(mockComponentName);
assertThat(mPicker.getDefaultKey()).isEqualTo(COMPONENT_KEY);
}
@Test
public void setDefaultShouldUpdateActiveDream() {
DreamInfo mockInfo = mock(DreamInfo.class);
ComponentName mockName = mock(ComponentName.class);
mockInfo.componentName = mockName;
when(mockName.flattenToString()).thenReturn(COMPONENT_KEY);
when(mBackend.getDreamInfos()).thenReturn(new ArrayList<>(Arrays.asList(mockInfo)));
mPicker.setDefaultKey(COMPONENT_KEY);
verify(mBackend).setActiveDream(mockName);
}
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright (C) 2017 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.dream;
import android.content.ComponentName;
import android.content.Context;
import com.android.settings.SettingsRobolectricTestRunner;
import com.android.settings.TestConfig;
import com.android.settings.widget.GearPreference;
import com.android.settingslib.dream.DreamBackend;
import com.android.settingslib.dream.DreamBackend.DreamInfo;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class CurrentDreamPreferenceControllerTest {
private static String TAG = "CurrentDreamPreferenceControllerTest";
private CurrentDreamPreferenceController mController;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private DreamBackend mBackend;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Context mContext;
@Mock
private DreamInfo mDreamInfo;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mController = new CurrentDreamPreferenceController(mContext);
ReflectionHelpers.setField(mController, "mBackend", mBackend);
}
@Test
public void isDisabledIfNoDreamsAvailable() {
when(mBackend.getDreamInfos()).thenReturn(new ArrayList<>(0));
assertThat(mController.isAvailable()).isFalse();
}
@Test
public void isEnabledIfDreamsAvailable() {
when(mBackend.getDreamInfos()).thenReturn(new ArrayList<>(Arrays.asList(mDreamInfo)));
assertThat(mController.isAvailable()).isTrue();
}
@Test
public void gearShowsIfActiveDreamInfoHasOptions() {
mDreamInfo.settingsComponentName = mock(ComponentName.class);
mDreamInfo.isActive = true;
when(mBackend.getDreamInfos()).thenReturn(new ArrayList<>(Arrays.asList(mDreamInfo)));
GearPreference mockPref = mock(GearPreference.class);
ArgumentCaptor<GearPreference.OnGearClickListener> captor =
ArgumentCaptor.forClass(GearPreference.OnGearClickListener.class);
// verify that updateState sets a non-null gear click listener
mController.updateState(mockPref);
verify(mockPref).setOnGearClickListener(captor.capture());
captor.getAllValues().forEach(listener -> assertThat(listener).isNotNull());
}
@Test
public void gearHidesIfActiveDreamInfoHasNoOptions() {
mDreamInfo.settingsComponentName = null;
mDreamInfo.isActive = true;
when(mBackend.getDreamInfos()).thenReturn(new ArrayList<>(Arrays.asList(mDreamInfo)));
GearPreference mockPref = mock(GearPreference.class);
ArgumentCaptor<GearPreference.OnGearClickListener> captor =
ArgumentCaptor.forClass(GearPreference.OnGearClickListener.class);
// setting a null onGearClickListener removes the gear from view
mController.updateState(mockPref);
verify(mockPref).setOnGearClickListener(captor.capture());
captor.getAllValues().forEach(listener -> assertThat(listener).isNull());
}
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright (C) 2017 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.dream;
import android.content.Context;
import com.android.settings.R;
import com.android.settings.SettingsRobolectricTestRunner;
import com.android.settings.TestConfig;
import com.android.settingslib.dream.DreamBackend;
import com.android.settingslib.dream.DreamBackend.WhenToDream;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class DreamSettingsTest {
private static final List<String> KEYS = Arrays.asList(
DreamSettings.WHILE_CHARGING_ONLY,
DreamSettings.WHILE_DOCKED_ONLY,
DreamSettings.EITHER_CHARGING_OR_DOCKED,
DreamSettings.NEVER_DREAM
);
private static final @WhenToDream int[] SETTINGS = {
DreamBackend.WHILE_CHARGING,
DreamBackend.WHILE_DOCKED,
DreamBackend.EITHER,
DreamBackend.NEVER,
};
private static final int[] RES_IDS = {
R.string.screensaver_settings_summary_sleep,
R.string.screensaver_settings_summary_dock,
R.string.screensaver_settings_summary_either_long,
R.string.screensaver_settings_summary_never
};
@Test
public void getSettingFromPrefKey() {
for (int i = 0; i < KEYS.size(); i++) {
assertThat(DreamSettings.getSettingFromPrefKey(KEYS.get(i)))
.isEqualTo(SETTINGS[i]);
}
// Default case
assertThat(DreamSettings.getSettingFromPrefKey("garbage value"))
.isEqualTo(DreamBackend.NEVER);
}
@Test
public void getKeyFromSetting() {
for (int i = 0; i < SETTINGS.length; i++) {
assertThat(DreamSettings.getKeyFromSetting(SETTINGS[i]))
.isEqualTo(KEYS.get(i));
}
// Default
assertThat(DreamSettings.getKeyFromSetting(-1))
.isEqualTo(DreamSettings.NEVER_DREAM);
}
@Test
public void getDreamSettingDescriptionResId() {
for (int i = 0; i < SETTINGS.length; i++) {
assertThat(DreamSettings.getDreamSettingDescriptionResId(SETTINGS[i]))
.isEqualTo(RES_IDS[i]);
}
// Default
assertThat(DreamSettings.getDreamSettingDescriptionResId(-1))
.isEqualTo(R.string.screensaver_settings_summary_never);
}
@Test
public void summaryText_whenDreamsAreOff() {
DreamBackend mockBackend = mock(DreamBackend.class);
Context mockContext = mock(Context.class);
when(mockBackend.isEnabled()).thenReturn(false);
assertThat(DreamSettings.getSummaryTextFromBackend(mockBackend, mockContext))
.isEqualTo(mockContext.getString(R.string.screensaver_settings_summary_off));
}
@Test
public void summaryTest_WhenDreamsAreOn() {
final String fakeName = "test_name";
DreamBackend mockBackend = mock(DreamBackend.class);
Context mockContext = mock(Context.class);
when(mockBackend.isEnabled()).thenReturn(true);
when(mockBackend.getActiveDreamName()).thenReturn(fakeName);
assertThat(DreamSettings.getSummaryTextFromBackend(mockBackend, mockContext))
.isEqualTo(fakeName);
}
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright (C) 2017 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.dream;
import android.content.Context;
import android.support.v7.preference.PreferenceScreen;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.android.settings.R;
import com.android.settings.SettingsRobolectricTestRunner;
import com.android.settings.TestConfig;
import com.android.settings.applications.LayoutPreference;
import com.android.settingslib.dream.DreamBackend;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class StartNowPreferenceControllerTest {
private StartNowPreferenceController mController;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Context mContext;
@Mock
private PreferenceScreen mScreen;
@Mock
private LayoutPreference mLayoutPref;
@Mock
private Button mButton;
@Mock
private DreamBackend mBackend;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mController = new StartNowPreferenceController(mContext);
when(mScreen.findPreference(mController.getPreferenceKey())).thenReturn(mLayoutPref);
when(mLayoutPref.findViewById(R.id.dream_start_now_button)).thenReturn(mButton);
ReflectionHelpers.setField(mController, "mBackend", mBackend);
}
@Test
public void setsOnClickListenerForStartNow() {
ArgumentCaptor<OnClickListener> captor =
ArgumentCaptor.forClass(Button.OnClickListener.class);
mController.displayPreference(mScreen);
verify(mButton).setOnClickListener(captor.capture());
assertThat(captor.getValue()).isNotNull();
}
@Test
public void buttonIsDisabledWhenNeverDreaming() {
when(mBackend.getWhenToDreamSetting()).thenReturn(DreamBackend.NEVER);
mController.updateState(mLayoutPref);
verify(mButton).setEnabled(false);
}
@Test
public void buttonIsEnabledWhenDreamIsAvailable() {
when(mBackend.getWhenToDreamSetting()).thenReturn(DreamBackend.EITHER);
mController.updateState(mLayoutPref);
verify(mButton).setEnabled(true);
}
}

View File

@@ -0,0 +1,108 @@
/*
* Copyright (C) 2017 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.dream;
import android.app.Activity;
import android.content.Context;
import android.os.UserManager;
import com.android.settings.SettingsRobolectricTestRunner;
import com.android.settings.TestConfig;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settingslib.dream.DreamBackend;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class WhenToDreamPickerTest {
private WhenToDreamPicker mPicker;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private DreamBackend mBackend;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Activity mActivity;
@Mock
private UserManager mUserManager;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(mActivity.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
FakeFeatureFactory.setupForTest(mActivity);
mPicker = new WhenToDreamPicker();
mPicker.onAttach((Context)mActivity);
ReflectionHelpers.setField(mPicker, "mBackend", mBackend);
}
@Test
public void getDefaultKeyReturnsCurrentWhenToDreamSetting() {
when(mBackend.getWhenToDreamSetting()).thenReturn(DreamBackend.WHILE_CHARGING);
assertThat(mPicker.getDefaultKey())
.isEqualTo(DreamSettings.getKeyFromSetting(DreamBackend.WHILE_CHARGING));
when(mBackend.getWhenToDreamSetting()).thenReturn(DreamBackend.WHILE_DOCKED);
assertThat(mPicker.getDefaultKey())
.isEqualTo(DreamSettings.getKeyFromSetting(DreamBackend.WHILE_DOCKED));
when(mBackend.getWhenToDreamSetting()).thenReturn(DreamBackend.EITHER);
assertThat(mPicker.getDefaultKey())
.isEqualTo(DreamSettings.getKeyFromSetting(DreamBackend.EITHER));
when(mBackend.getWhenToDreamSetting()).thenReturn(DreamBackend.NEVER);
assertThat(mPicker.getDefaultKey())
.isEqualTo(DreamSettings.getKeyFromSetting(DreamBackend.NEVER));
}
@Test
public void setDreamWhileCharging() {
String key = DreamSettings.getKeyFromSetting(DreamBackend.WHILE_CHARGING);
mPicker.setDefaultKey(key);
verify(mBackend).setWhenToDream(DreamBackend.WHILE_CHARGING);
}
@Test
public void setDreamWhileDocked() {
String key = DreamSettings.getKeyFromSetting(DreamBackend.WHILE_DOCKED);
mPicker.setDefaultKey(key);
verify(mBackend).setWhenToDream(DreamBackend.WHILE_DOCKED);
}
@Test
public void setDreamWhileChargingOrDocked() {
String key = DreamSettings.getKeyFromSetting(DreamBackend.EITHER);
mPicker.setDefaultKey(key);
verify(mBackend).setWhenToDream(DreamBackend.EITHER);
}
@Test
public void setDreamNever() {
String key = DreamSettings.getKeyFromSetting(DreamBackend.NEVER);
mPicker.setDefaultKey(key);
verify(mBackend).setWhenToDream(DreamBackend.NEVER);
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (C) 2017 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.dream;
import android.content.Context;
import android.support.v7.preference.Preference;
import com.android.settings.SettingsRobolectricTestRunner;
import com.android.settings.TestConfig;
import com.android.settingslib.dream.DreamBackend;
import com.android.settingslib.dream.DreamBackend.WhenToDream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class WhenToDreamPreferenceControllerTest {
private WhenToDreamPreferenceController mController;
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Context mContext;
@Mock
private DreamBackend mBackend;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mController = new WhenToDreamPreferenceController(mContext);
ReflectionHelpers.setField(mController, "mBackend", mBackend);
}
@Test
public void updateSummary() {
// Don't have to test the other settings because DreamSettings tests that all
// @WhenToDream values map to the correct ResId
final @WhenToDream int testSetting = DreamBackend.WHILE_CHARGING;
final Preference mockPref = mock(Preference.class);
when(mockPref.getContext()).thenReturn(mContext);
when(mBackend.getWhenToDreamSetting()).thenReturn(testSetting);
final String expectedString =
mContext.getString(DreamSettings.getDreamSettingDescriptionResId(testSetting));
mController.updateState(mockPref);
verify(mockPref).setSummary(expectedString);
}
}