Merge "Revert "Don't use framework strings for formatting file sizes""
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index c13e5f3..facfeab 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -1287,6 +1287,28 @@
android:value="true" />
</activity>
+ <!-- TODO(32953042) Merge with Settings$SecuritySettingsActivity -->
+ <activity android:name="Settings$SecuritySettingsActivityV2"
+ android:label="@string/security_settings_title"
+ android:icon="@drawable/ic_settings_security"
+ android:enabled="false"
+ android:configChanges="orientation|keyboardHidden|screenSize"
+ android:taskAffinity=""
+ android:parentActivityName="Settings">
+ <intent-filter android:priority="-1">
+ <action android:name="android.settings.SECURITY_SETTINGS" />
+ <action android:name="android.credentials.UNLOCK" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ <intent-filter android:priority="4">
+ <action android:name="com.android.settings.action.SETTINGS" />
+ </intent-filter>
+ <meta-data android:name="com.android.settings.category"
+ android:value="com.android.settings.category.ia.homepage" />
+ <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
+ android:value="com.android.settings.security.SecuritySettingsV2" />
+ </activity>
+
<activity android:name="MonitoringCertInfoActivity"
android:label=""
android:theme="@style/Transparent"
diff --git a/res/layout/choose_lock_password_footer.xml b/res/layout/choose_lock_password_footer.xml
index 41306e9..0b7791c 100644
--- a/res/layout/choose_lock_password_footer.xml
+++ b/res/layout/choose_lock_password_footer.xml
@@ -21,12 +21,13 @@
android:layout_width="match_parent"
android:layout_height="wrap_content">
- <!-- left : cancel -->
- <Button android:id="@+id/cancel_button"
+ <!-- left : skip -->
+ <Button android:id="@+id/skip_button"
style="@style/SuwGlifButton.Secondary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:text="@string/lockpassword_cancel_label" />
+ android:text="@string/skip_label"
+ android:visibility="gone" />
<!-- left : clear -->
diff --git a/res/layout/choose_lock_pattern_common.xml b/res/layout/choose_lock_pattern_common.xml
index 949d130..6aee0f9 100644
--- a/res/layout/choose_lock_pattern_common.xml
+++ b/res/layout/choose_lock_pattern_common.xml
@@ -107,6 +107,14 @@
android:textSize="14sp"
android:visibility="gone"/>
+ <Button
+ android:id="@+id/screen_lock_options"
+ style="@style/SuwGlifButton.Tertiary"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="@string/setup_lock_settings_options_button_label"
+ android:visibility="gone" />
+
</com.android.internal.widget.LinearLayoutWithDefaultTouchRecepient>
</com.android.setupwizardlib.GlifLayout>
diff --git a/res/layout/preference_category_no_title.xml b/res/layout/preference_category_no_title.xml
index 136ec6d..d4704bd 100644
--- a/res/layout/preference_category_no_title.xml
+++ b/res/layout/preference_category_no_title.xml
@@ -18,7 +18,7 @@
set height to 0. This will be used in preference category without title in order to remove
extra 32dp blank -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+android:id/title"
+ android:id="@android:id/title"
android:layout_width="match_parent"
android:layout_height="0dp"
android:textAppearance="@android:style/TextAppearance.Material.Body2"
diff --git a/res/layout/preference_widget_master_checkbox.xml b/res/layout/preference_widget_master_checkbox.xml
new file mode 100644
index 0000000..e61839d
--- /dev/null
+++ b/res/layout/preference_widget_master_checkbox.xml
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2018 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.
+ -->
+
+<CheckBox
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/checkboxWidget"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:gravity="center"
+ android:layout_marginStart="?android:attr/listPreferredItemPaddingEnd"
+ android:layout_marginEnd="?android:attr/listPreferredItemPaddingEnd"
+ android:clickable="false" />
diff --git a/res/layout/private_dns_mode_dialog.xml b/res/layout/private_dns_mode_dialog.xml
index 16152a4..652bc63 100644
--- a/res/layout/private_dns_mode_dialog.xml
+++ b/res/layout/private_dns_mode_dialog.xml
@@ -14,43 +14,56 @@
limitations under the License.
-->
-<RadioGroup
+<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/private_dns_radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:padding="8dip">
+ android:orientation="vertical"
+ android:padding="8dp">
- <RadioButton
- android:id="@+id/private_dns_mode_off"
- android:text="@string/private_dns_mode_off"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="8dip"/>
+ <RadioGroup
+ android:id="@+id/private_dns_radio_group"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content">
- <RadioButton
- android:id="@+id/private_dns_mode_opportunistic"
- android:text="@string/private_dns_mode_opportunistic"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="8dip"/>
+ <RadioButton
+ android:id="@+id/private_dns_mode_off"
+ android:text="@string/private_dns_mode_off"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_margin="8dp"/>
- <RadioButton
- android:id="@+id/private_dns_mode_provider"
- android:text="@string/private_dns_mode_provider"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_margin="8dip"/>
+ <RadioButton
+ android:id="@+id/private_dns_mode_opportunistic"
+ android:text="@string/private_dns_mode_opportunistic"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_margin="8dp"/>
- <EditText
- android:id="@+id/private_dns_mode_provider_hostname"
- android:hint="@string/private_dns_mode_provider_hostname_hint"
- style="@android:style/Widget.CompoundButton.RadioButton"
- android:imeOptions="actionDone"
- android:inputType="textFilter|textUri"
+ <RadioButton
+ android:id="@+id/private_dns_mode_provider"
+ android:text="@string/private_dns_mode_provider"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_margin="8dp"/>
+
+ <EditText
+ android:id="@+id/private_dns_mode_provider_hostname"
+ android:hint="@string/private_dns_mode_provider_hostname_hint"
+ style="@android:style/Widget.CompoundButton.RadioButton"
+ android:imeOptions="actionDone"
+ android:inputType="textFilter|textUri"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginStart="40dp"
+ android:layout_marginEnd="8dp"/>
+ </RadioGroup>
+
+ <TextView
+ android:id="@+id/private_dns_help_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:layout_marginStart="40dip"
- android:layout_marginEnd="8dip"/>
-
-</RadioGroup>
+ android:layout_marginTop="16dp"
+ android:paddingStart="16dp"
+ android:textAppearance="?android:attr/textAppearanceSmall"/>
+</LinearLayout>
diff --git a/res/layout/suggestion_tile_remote_container.xml b/res/layout/suggestion_tile_remote_container.xml
deleted file mode 100644
index fd19b80..0000000
--- a/res/layout/suggestion_tile_remote_container.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?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.
--->
-
-<FrameLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:background="@android:color/white"
- android:clickable="true"
- android:focusable="true"
- android:minHeight="@dimen/dashboard_tile_minimum_height" />
diff --git a/res/values/arrays.xml b/res/values/arrays.xml
index aa8a586..dbcfee1 100644
--- a/res/values/arrays.xml
+++ b/res/values/arrays.xml
@@ -309,6 +309,24 @@
<item>Never time out</item>
</string-array>
+ <!-- Bluetooth developer settings: Titles for maximum number of connected audio devices -->
+ <string-array name="bluetooth_max_connected_audio_devices">
+ <item>1 (Default)</item>
+ <item>2</item>
+ <item>3</item>
+ <item>4</item>
+ <item>5</item>
+ </string-array>
+
+ <!-- Bluetooth developer settings: Values for maximum number of connected audio devices -->
+ <string-array name="bluetooth_max_connected_audio_devices_values">
+ <item>1</item>
+ <item>2</item>
+ <item>3</item>
+ <item>4</item>
+ <item>5</item>
+ </string-array>
+
<!-- Match this with drawable.wifi_signal. --> <skip />
<!-- Wi-Fi settings. The signal strength a Wi-Fi network has. -->
<string-array name="wifi_signal">
diff --git a/res/values/bools.xml b/res/values/bools.xml
index 4c1c9c2..687d5bd 100644
--- a/res/values/bools.xml
+++ b/res/values/bools.xml
@@ -49,12 +49,38 @@
<!--Whether help links are defined. -->
<bool name="config_has_help">false</bool>
+ <!-- Whether Wi-Fi settings should be shown or not.
+ This also controls whether Wi-fi related sub-settings (e.g. Wi-Fi preferences) will
+ surface in search results or not.-->
+ <bool name="config_show_wifi_settings">true</bool>
+
<!-- Whether location mode is available or not. -->
<bool name="config_location_mode_available">true</bool>
+ <!-- Whether high_power_apps should be shown or not. -->
+ <bool name="config_show_high_power_apps">true</bool>
+
+ <!-- Whether device_administrators should be shown or not. -->
+ <bool name="config_show_device_administrators">true</bool>
+
+ <!-- Whether premium_sms should be shown or not. -->
+ <bool name="config_show_premium_sms">true</bool>
+
+ <!-- Whether data_saver should be shown or not. -->
+ <bool name="config_show_data_saver">true</bool>
+
+ <!-- Whether enabled_vr_listeners should be shown or not. -->
+ <bool name="config_show_enabled_vr_listeners">true</bool>
+
<!-- Whether wallpaper attribution should be shown or not. -->
<bool name="config_show_wallpaper_attribution">true</bool>
<!-- Whether default_home should be shown or not. -->
<bool name="config_show_default_home">true</bool>
+
+ <!-- Whether accessibility shortcut preference should be shown or not. -->
+ <bool name="config_show_accessibility_shortcut_preference">true</bool>
+
+ <!-- Whether assist_and_voice_input should be shown or not. -->
+ <bool name="config_show_assist_and_voice_input">true</bool>
</resources>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 7153742..78e4f94 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -396,6 +396,11 @@
<!-- Summary for bluetooth item in connection detail page -->
<string name="bluetooth_pref_summary">Allow device to pair and connect to bluetooth devices</string>
+ <!-- Setting Checkbox title for disabling Bluetooth inband ringing in Development Settings -->
+ <string name="bluetooth_disable_inband_ringing">Disable in-band ringing</string>
+ <!-- Summary of checkbox for disabling Bluetooth inband ringing in Development Settings -->
+ <string name="bluetooth_disable_inband_ringing_summary">Don’t play custom phone ringtones on Bluetooth headsets</string>
+
<!-- Title for connected device group [CHAR LIMIT=none]-->
<string name="connected_device_connected_title">Currently connected</string>
<!-- Title for connected device group [CHAR LIMIT=none]-->
@@ -1624,6 +1629,11 @@
<!-- Bluetooth settings. Dock Setting Dialog - Remember setting and don't ask user again -->
<string name="bluetooth_dock_settings_remember">Remember settings</string>
+ <!-- Bluetooth developer settings: Maximum number of connected audio devices -->
+ <string name="bluetooth_max_connected_audio_devices_string">Maximum connected Bluetooth audio devices</string>
+ <!-- Bluetooth developer settings: Maximum number of connected audio devices -->
+ <string name="bluetooth_max_connected_audio_devices_dialog_title">Select maximum number of connected Bluetooth audio devices</string>
+
<!-- Wifi Display settings. The title of the screen. [CHAR LIMIT=40] -->
<string name="wifi_display_settings_title">Cast</string>
<!-- Wifi Display settings. The title of a menu item to enable wireless display [CHAR LIMIT=40] -->
@@ -1951,7 +1961,7 @@
<!-- Message in dialog when the user tries to connect to a carrier network[CHAR_LIMIT=40] -->
<string name="wifi_carrier_connect">Carrier Wi\u2011Fi network</string>
<!-- Message in dialog when the user tries to connect to a carrier network[CHAR_LIMIT=60] -->
- <string name="wifi_carrier_content">Connect via <xliff:g id="name">%1%s</xliff:g></string>
+ <string name="wifi_carrier_content">Connect via <xliff:g id="name">%1$s</xliff:g></string>
<string name="wifi_scan_always_turnon_message">To improve location accuracy and for other purposes, <xliff:g id="app_name">%1$s</xliff:g> wants to turn on network scanning, even when Wi-Fi is off.\n\nAllow this for all apps that want to scan?</string>
<!-- Message informing the user how to turn off [CHAR LIMIT=200] -->
@@ -2264,7 +2274,8 @@
<string name="emergency_address_title">Emergency Address</string>
<!-- Summary of Update Emergency Address preference, explaining usage of emergency address [CHAR LIMIT=NONE] -->
<string name="emergency_address_summary">Used as your location when you make an emergency call over Wi\u2011Fi</string>
-
+ <!-- Message of private dns that provides a help link. [CHAR LIMIT=NONE] -->
+ <string name="private_dns_help_message"><annotation id="url">Learn more</annotation> about Private DNS features</string>
<!-- Sound and alerts settings -->
<skip/>
@@ -3064,6 +3075,9 @@
\n\nDon\u2019t remove the <xliff:g id="name" example="SD card">^2</xliff:g> during the move.
</string>
+ <!-- Body of lock screen challenge message explaining that the given user must be unlocked before data can be moved [CHAR LIMIT=64] -->
+ <string name="storage_wizard_move_unlock">To move data you need to unlock user <xliff:g id="app" example="Joey">^1</xliff:g>.</string>
+
<!-- Title of wizard step showing app move progress [CHAR LIMIT=32] -->
<string name="storage_wizard_move_progress_title">Moving <xliff:g id="app" example="Calculator">^1</xliff:g>\u2026</string>
<!-- Body of wizard step showing app move progress [CHAR LIMIT=NONE] -->
@@ -6333,6 +6347,7 @@
<string name="help_url_icc_lock" translatable="false"></string>
<string name="help_uri_process_stats_summary" translatable="false"></string>
<string name="help_uri_process_stats_apps" translatable="false"></string>
+ <string name="help_uri_private_dns" translatable="false"></string>
<!-- User account title [CHAR LIMIT=30] -->
<string name="user_account_title">Account for content</string>
@@ -6926,7 +6941,7 @@
<string name="notification_group_title">Notification category group</string>
<!-- [CHAR LIMIT=100] Notification importance screen title -->
- <string name="notification_importance_title">Importance</string>
+ <string name="notification_importance_title">Behavior</string>
<!-- [CHAR LIMIT=100 BACKUP_MESSAGE_ID=1820188704793497324] Notification Importance: unspecified importance level description -->
<string name="notification_importance_unspecified">Allow sound</string>
@@ -6991,6 +7006,9 @@
<!-- [CHAR LIMIT=100] Notification Importance title: high importance level title -->
<string name="notification_channel_summary_high">Urgent importance</string>
+ <!-- [CHAR LIMIT=100] Label for on/off toggle -->
+ <string name="notification_switch_label">Show notifications</string>
+
<!-- Default Apps > Default notification assistant -->
<string name="default_notification_assistant">Notification assistant</string>
@@ -7087,13 +7105,13 @@
<string name="loading_notification_apps">Loading apps...</string>
<!-- [CHAR LIMIT=NONE] Text appearing when app notifications are off -->
- <string name="app_notifications_off_desc">Android is blocking this app\'s notifications from appearing on this device</string>
+ <string name="app_notifications_off_desc">At your request, Android is blocking this app\'s notifications from appearing on this device</string>
<!-- [CHAR LIMIT=NONE] Text appearing when channel notifications are off -->
- <string name="channel_notifications_off_desc">Android is blocking this category of notifications from appearing on this device</string>
+ <string name="channel_notifications_off_desc">At your request, Android is blocking this category of notifications from appearing on this device</string>
<!-- [CHAR LIMIT=NONE] Text appearing when channel group notifications are off -->
- <string name="channel_group_notifications_off_desc">Android is blocking this group of notifications from appearing on this device</string>
+ <string name="channel_group_notifications_off_desc">At your request, Android is blocking this group of notifications from appearing on this device</string>
<!-- [CHAR LIMIT=NONE] App notification settings: channels title -->
<string name="notification_channels">Categories</string>
diff --git a/res/xml/channel_notification_settings.xml b/res/xml/channel_notification_settings.xml
index fb2705a..c799c8b 100644
--- a/res/xml/channel_notification_settings.xml
+++ b/res/xml/channel_notification_settings.xml
@@ -15,7 +15,8 @@
-->
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:settings="http://schemas.android.com/apk/res-auto" >
+ xmlns:settings="http://schemas.android.com/apk/res-auto"
+ settings:initialExpandedChildrenCount="3">
<com.android.settings.applications.LayoutPreference
android:key="pref_app_header"
diff --git a/res/xml/development_settings.xml b/res/xml/development_settings.xml
index 60efcab..aad5d23 100644
--- a/res/xml/development_settings.xml
+++ b/res/xml/development_settings.xml
@@ -240,9 +240,9 @@
android:summary="@string/bluetooth_disable_absolute_volume_summary"/>
<SwitchPreference
- android:key="bluetooth_enable_inband_ringing"
- android:title="@string/bluetooth_enable_inband_ringing"
- android:summary="@string/bluetooth_enable_inband_ringing_summary"/>
+ android:key="bluetooth_disable_inband_ringing"
+ android:title="@string/bluetooth_disable_inband_ringing"
+ android:summary="@string/bluetooth_disable_inband_ringing_summary"/>
<ListPreference
android:key="bluetooth_select_avrcp_version"
@@ -286,6 +286,13 @@
android:entries="@array/bluetooth_a2dp_codec_ldac_playback_quality_titles"
android:entryValues="@array/bluetooth_a2dp_codec_ldac_playback_quality_values" />
+ <ListPreference
+ android:key="bluetooth_max_connected_audio_devices"
+ android:title="@string/bluetooth_max_connected_audio_devices_string"
+ android:dialogTitle="@string/bluetooth_max_connected_audio_devices_dialog_title"
+ android:entries="@array/bluetooth_max_connected_audio_devices"
+ android:entryValues="@array/bluetooth_max_connected_audio_devices_values" />
+
</PreferenceCategory>
<PreferenceCategory android:key="debug_input_category"
diff --git a/res/xml/notification_importance.xml b/res/xml/notification_importance.xml
index f801f3c..6f9cc0e 100644
--- a/res/xml/notification_importance.xml
+++ b/res/xml/notification_importance.xml
@@ -19,20 +19,15 @@
<com.android.settings.widget.RadioButtonPreference
android:key="importance_high"
- android:title="@string/notification_importance_high_title"
- android:summary="@string/notification_importance_high"
- />
+ android:title="@string/notification_importance_high" />
<com.android.settings.widget.RadioButtonPreference
android:key="importance_default"
- android:title="@string/notification_importance_default_title"
- android:summary="@string/notification_importance_default" />
+ android:title="@string/notification_importance_default" />
<com.android.settings.widget.RadioButtonPreference
android:key="importance_low"
- android:title="@string/notification_importance_low_title"
- android:summary="@string/notification_importance_low" />
+ android:title="@string/notification_importance_low" />
<com.android.settings.widget.RadioButtonPreference
android:key="importance_min"
- android:title="@string/notification_importance_min_title"
- android:summary="@string/notification_importance_min" />
+ android:title="@string/notification_importance_min" />
</PreferenceScreen>
diff --git a/res/xml/power_usage_summary.xml b/res/xml/power_usage_summary.xml
index 0aec18f..5d6c9e9 100644
--- a/res/xml/power_usage_summary.xml
+++ b/res/xml/power_usage_summary.xml
@@ -31,23 +31,7 @@
android:layout="@layout/preference_category_no_title"/>
<PreferenceCategory
- android:key="device_usage_list">
-
- <com.android.settings.fuelgauge.PowerGaugePreference
- android:key="last_full_charge"
- android:title="@string/battery_last_full_charge"
- android:selectable="false"/>
-
- <com.android.settings.fuelgauge.PowerGaugePreference
- android:key="screen_usage"
- android:title="@string/device_screen_usage"
- android:selectable="false"/>
-
- </PreferenceCategory>
-
- <PreferenceCategory
- android:key="power_management"
- android:title="@string/battery_power_management">
+ android:key="power_management">
<com.android.settings.widget.MasterSwitchPreference
android:fragment="com.android.settings.fuelgauge.BatterySaverSettings"
@@ -59,26 +43,20 @@
android:title="@string/battery_percentage"
android:summary="@string/battery_percentage_description"/>
- <!-- Cross-listed item, if you change this, also change it in display_settings.xml -->
- <SwitchPreference
- android:key="auto_brightness_battery"
- android:title="@string/auto_brightness_title"
- android:summary="@string/auto_brightness_summary"
- settings:keywords="@string/keywords_display_auto_brightness"/>
+ </PreferenceCategory>
- <!-- Cross-listed item, if you change this, also change it in display_settings.xml -->
- <com.android.settings.TimeoutListPreference
- android:key="screen_timeout_battery"
- android:title="@string/screen_timeout"
- android:summary="@string/screen_timeout_summary"
- android:entries="@array/screen_timeout_entries"
- android:entryValues="@array/screen_timeout_values"/>
+ <PreferenceCategory
+ android:key="device_usage_list">
- <!-- Cross-listed item, if you change this, also change it in display_settings.xml -->
- <Preference
- android:key="ambient_display_battery"
- android:title="@string/ambient_display_screen_title"
- android:fragment="com.android.settings.display.AmbientDisplaySettings" />
+ <com.android.settings.fuelgauge.PowerGaugePreference
+ android:key="last_full_charge"
+ android:title="@string/battery_last_full_charge"
+ android:selectable="false"/>
+
+ <com.android.settings.fuelgauge.PowerGaugePreference
+ android:key="screen_usage"
+ android:title="@string/device_screen_usage"
+ android:selectable="false"/>
</PreferenceCategory>
diff --git a/res/xml/security_settings_v2.xml b/res/xml/security_settings_v2.xml
new file mode 100644
index 0000000..571e51f
--- /dev/null
+++ b/res/xml/security_settings_v2.xml
@@ -0,0 +1,171 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ Copyright (C) 2018 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="security_dashboard_page"
+ android:title="@string/security_settings_title"
+ settings:initialExpandedChildrenCount="9">
+
+ <!-- security_settings_status.xml -->
+ <PreferenceCategory
+ android:order="-10"
+ android:key="security_status"
+ android:title="@string/security_status_title" />
+
+ <PreferenceCategory
+ android:order="1"
+ android:key="dashboard_tile_placeholder" />
+
+ <!-- security section -->
+ <PreferenceCategory
+ android:order="10"
+ android:key="security_category"
+ android:title="@string/lock_settings_title">
+
+ <com.android.settings.widget.GearPreference
+ android:key="unlock_set_or_change"
+ android:title="@string/unlock_set_unlock_launch_picker_title"
+ android:summary="@string/unlock_set_unlock_mode_none"
+ settings:keywords="@string/keywords_lockscreen" />
+
+ <Preference
+ android:key="lockscreen_preferences"
+ android:title="@string/lockscreen_settings_title"
+ android:summary="@string/summary_placeholder"
+ android:fragment="com.android.settings.security.LockscreenDashboardFragment" />
+
+ <Preference
+ android:key="fingerprint_settings"
+ android:title="@string/security_settings_fingerprint_preference_title"
+ android:summary="@string/summary_placeholder" />
+
+ </PreferenceCategory>
+
+ <!-- work profile security section -->
+ <PreferenceCategory
+ android:order="20"
+ android:key="security_category_profile"
+ android:title="@string/lock_settings_profile_title">
+
+ <!-- security_settings_unification -->
+ <com.android.settingslib.RestrictedSwitchPreference
+ android:key="unification"
+ android:title="@string/lock_settings_profile_unification_title"
+ android:summary="@string/lock_settings_profile_unification_summary"
+ settings:keywords="@string/keywords_unification" />
+
+ <com.android.settingslib.RestrictedPreference
+ android:key="unlock_set_or_change_profile"
+ android:title="@string/unlock_set_unlock_launch_picker_title_profile"
+ android:summary="@string/unlock_set_unlock_mode_pattern"
+ settings:keywords="@string/keywords_lockscreen" />
+
+ <SwitchPreference
+ android:key="visiblepattern_profile"
+ android:summary="@string/summary_placeholder"
+ android:title="@string/lockpattern_settings_enable_visible_pattern_title_profile" />
+
+ <Preference
+ android:key="fingerprint_settings_profile"
+ android:title="@string/security_settings_fingerprint_preference_title"
+ android:summary="@string/summary_placeholder" />
+
+ </PreferenceCategory>
+
+ <!-- security_settings_misc.xml -->
+ <PreferenceCategory
+ android:order="30"
+ android:key="security_settings_misc_category"
+ android:title="@string/security_passwords_title">
+
+ <Preference
+ android:key="location"
+ android:title="@string/location_settings_title"
+ android:summary="@string/summary_placeholder"
+ android:fragment="com.android.settings.location.LocationSettings" />
+
+ <SwitchPreference
+ android:key="show_password"
+ android:title="@string/show_password"
+ android:summary="@string/show_password_summary" />
+
+ </PreferenceCategory>
+
+ <PreferenceCategory
+ android:order="40"
+ android:key="security_settings_device_admin_category">
+
+ <Preference
+ android:key="manage_device_admin"
+ android:title="@string/manage_device_admin"
+ android:summary="@string/summary_placeholder"
+ android:fragment="com.android.settings.DeviceAdminSettings" />
+
+ <Preference
+ android:key="enterprise_privacy"
+ android:title="@string/enterprise_privacy_settings"
+ android:summary="@string/summary_placeholder"
+ android:fragment="com.android.settings.enterprise.EnterprisePrivacySettings" />
+
+ </PreferenceCategory>
+
+ <Preference
+ android:order="50"
+ android:key="sim_lock_settings"
+ android:title="@string/sim_lock_settings_category">
+
+ <intent
+ android:action="android.intent.action.MAIN"
+ android:targetPackage="com.android.settings"
+ android:targetClass="com.android.settings.Settings$IccLockSettingsActivity" />
+
+ </Preference>
+
+ <Preference
+ android:order="60"
+ android:key="encryption_and_credential"
+ android:title="@string/encryption_and_credential_settings_title"
+ android:summary="@string/encryption_and_credential_settings_summary"
+ android:fragment="com.android.settings.security.EncryptionAndCredential" />
+
+ <Preference
+ android:order="70"
+ android:key="manage_trust_agents"
+ android:title="@string/manage_trust_agents"
+ android:summary="@string/summary_placeholder"
+ android:fragment="com.android.settings.security.trustagent.TrustAgentSettings" />
+
+ <Preference
+ android:order="80"
+ android:key="screen_pinning_settings"
+ android:title="@string/screen_pinning_title"
+ android:summary="@string/summary_placeholder"
+ android:fragment="com.android.settings.security.ScreenPinningSettings" />
+
+ <Preference
+ android:order="90"
+ android:key="security_misc_usage_access"
+ android:title="@string/usage_access_title"
+ android:fragment="com.android.settings.applications.manageapplications.ManageApplications">
+ <extra
+ android:name="classname"
+ android:value="com.android.settings.Settings$UsageAccessSettingsActivity" />
+ </Preference>
+
+</PreferenceScreen>
\ No newline at end of file
diff --git a/res/xml/suggestion_ordering.xml b/res/xml/suggestion_ordering.xml
deleted file mode 100644
index e21fe5b..0000000
--- a/res/xml/suggestion_ordering.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2016 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.
--->
-
-<optional-steps>
- <step category="com.android.settings.suggested.category.DEFERRED_SETUP"
- exclusive="true" />
- <step category="com.android.settings.suggested.category.FIRST_IMPRESSION"
- exclusiveExpireDays="14"
- exclusive="true"
- multiple="true" />
- <step category="com.android.settings.suggested.category.LOCK_SCREEN" />
- <step category="com.android.settings.suggested.category.TRUST_AGENT" />
- <step category="com.android.settings.suggested.category.EMAIL" />
- <step category="com.android.settings.suggested.category.PARTNER_ACCOUNT"
- multiple="true" />
- <step category="com.android.settings.suggested.category.GESTURE" />
- <step category="com.android.settings.suggested.category.HOTWORD" />
- <step category="com.android.settings.suggested.category.DEFAULT"
- multiple="true" />
- <step category="com.android.settings.suggested.category.SETTINGS_ONLY"
- multiple="true" />
-</optional-steps>
diff --git a/src/com/android/settings/PreviewSeekBarPreferenceFragment.java b/src/com/android/settings/PreviewSeekBarPreferenceFragment.java
index f5f3017..026032d 100644
--- a/src/com/android/settings/PreviewSeekBarPreferenceFragment.java
+++ b/src/com/android/settings/PreviewSeekBarPreferenceFragment.java
@@ -67,7 +67,7 @@
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
- setPreviewLayer(progress, true);
+ setPreviewLayer(progress, false);
if (!mSeekByTouch) {
commit();
}
diff --git a/src/com/android/settings/Settings.java b/src/com/android/settings/Settings.java
index 9314952..d21a061 100644
--- a/src/com/android/settings/Settings.java
+++ b/src/com/android/settings/Settings.java
@@ -68,6 +68,7 @@
public static class AccessibilityContrastSettingsActivity extends SettingsActivity { /* empty */ }
public static class AccessibilityDaltonizerSettingsActivity extends SettingsActivity { /* empty */ }
public static class SecuritySettingsActivity extends SettingsActivity { /* empty */ }
+ public static class SecuritySettingsActivityV2 extends SettingsActivity { /* empty */ }
public static class UsageAccessSettingsActivity extends SettingsActivity { /* empty */ }
public static class LocationSettingsActivity extends SettingsActivity { /* empty */ }
public static class PrivacySettingsActivity extends SettingsActivity { /* empty */ }
diff --git a/src/com/android/settings/SettingsActivity.java b/src/com/android/settings/SettingsActivity.java
index e684e5e..d3580d1 100644
--- a/src/com/android/settings/SettingsActivity.java
+++ b/src/com/android/settings/SettingsActivity.java
@@ -751,6 +751,7 @@
PackageManager pm = getPackageManager();
final UserManager um = UserManager.get(this);
final boolean isAdmin = um.isAdminUser();
+ final FeatureFactory featureFactory = FeatureFactory.getFactory(this);
boolean somethingChanged = false;
String packageName = getPackageName();
somethingChanged = setTileEnabled(
@@ -805,12 +806,26 @@
!isConnectedDeviceV2Enabled && !UserManager.isDeviceInDemoMode(this) /* enabled */,
isAdmin) || somethingChanged;
+ final boolean isSecurityV2Enabled = featureFactory.getSecurityFeatureProvider()
+ .isSecuritySettingsV2Enabled(this);
+
+ // Enable new security page if v2 enabled
+ somethingChanged = setTileEnabled(
+ new ComponentName(packageName,Settings.SecuritySettingsActivityV2.class.getName()),
+ isSecurityV2Enabled,
+ isAdmin) || somethingChanged;
+ // Enable old security page if v2 disabled
+ somethingChanged = setTileEnabled(
+ new ComponentName(packageName,Settings.SecuritySettingsActivity.class.getName()),
+ !isSecurityV2Enabled,
+ isAdmin) || somethingChanged;
+
somethingChanged = setTileEnabled(new ComponentName(packageName,
Settings.SimSettingsActivity.class.getName()),
Utils.showSimCardTile(this), isAdmin)
|| somethingChanged;
- final boolean isBatterySettingsV2Enabled = FeatureFactory.getFactory(this)
+ final boolean isBatterySettingsV2Enabled = featureFactory
.getPowerUsageFeatureProvider(this)
.isBatteryV2Enabled();
// Enable new battery page if v2 enabled
diff --git a/src/com/android/settings/Utils.java b/src/com/android/settings/Utils.java
index cab3139..cd64799 100644
--- a/src/com/android/settings/Utils.java
+++ b/src/com/android/settings/Utils.java
@@ -106,6 +106,7 @@
import com.android.internal.app.UnlaunchableAppActivity;
import com.android.internal.util.ArrayUtils;
import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.password.ChooseLockSettingsHelper;
import com.android.settings.wrapper.DevicePolicyManagerWrapper;
import com.android.settings.wrapper.FingerprintManagerWrapper;
@@ -995,20 +996,37 @@
}
/**
- * Returns the user id present in the bundle with {@link Intent#EXTRA_USER_ID} if it
- * belongs to the current user.
+ * Returns the user id present in the bundle with
+ * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
*
- * @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 getUserIdFromBundle(Context context, Bundle bundle) {
+ return getUserIdFromBundle(context, bundle, false);
+ }
+
+ /**
+ * Returns the user id present in the bundle with
+ * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
+ *
+ * @param isInternal indicating if the caller is "internal" to the system,
+ * meaning we're willing to trust extras like
+ * {@link ChooseLockSettingsHelper#EXTRA_ALLOW_ANY_USER}.
+ * @throws SecurityException if the given userId does not belong to the
+ * current user group.
+ */
+ public static int getUserIdFromBundle(Context context, Bundle bundle, boolean isInternal) {
if (bundle == null) {
return getCredentialOwnerUserId(context);
}
+ final boolean allowAnyUser = isInternal
+ && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_ALLOW_ANY_USER, false);
int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
if (userId == LockPatternUtils.USER_FRP) {
- return enforceSystemUser(context, userId);
+ return allowAnyUser ? userId : enforceSystemUser(context, userId);
} else {
- return enforceSameOwner(context, userId);
+ return allowAnyUser ? userId : enforceSameOwner(context, userId);
}
}
@@ -1204,7 +1222,7 @@
public static FingerprintManager getFingerprintManagerOrNull(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
- return context.getSystemService(FingerprintManager.class);
+ return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
} else {
return null;
}
diff --git a/src/com/android/settings/accessibility/AccessibilitySettings.java b/src/com/android/settings/accessibility/AccessibilitySettings.java
index 160176e..cc72280 100644
--- a/src/com/android/settings/accessibility/AccessibilitySettings.java
+++ b/src/com/android/settings/accessibility/AccessibilitySettings.java
@@ -30,6 +30,7 @@
import android.os.UserHandle;
import android.provider.SearchIndexableResource;
import android.provider.Settings;
+import android.support.annotation.VisibleForTesting;
import android.support.v14.preference.SwitchPreference;
import android.support.v4.content.ContextCompat;
import android.support.v7.preference.ListPreference;
@@ -102,8 +103,6 @@
"toggle_master_mono";
private static final String SELECT_LONG_PRESS_TIMEOUT_PREFERENCE =
"select_long_press_timeout_preference";
- private static final String ACCESSIBILITY_SHORTCUT_PREFERENCE =
- "accessibility_shortcut_preference";
private static final String CAPTIONING_PREFERENCE_SCREEN =
"captioning_preference_screen";
private static final String DISPLAY_MAGNIFICATION_PREFERENCE_SCREEN =
@@ -117,6 +116,9 @@
private static final String DISPLAY_DALTONIZER_PREFERENCE_SCREEN =
"daltonizer_preference_screen";
+ @VisibleForTesting static final String ACCESSIBILITY_SHORTCUT_PREFERENCE =
+ "accessibility_shortcut_preference";
+
// Extras passed to sub-fragments.
static final String EXTRA_PREFERENCE_KEY = "preference_key";
static final String EXTRA_CHECKED = "checked";
@@ -452,6 +454,7 @@
// Accessibility shortcut
mAccessibilityShortcutPreferenceScreen = findPreference(ACCESSIBILITY_SHORTCUT_PREFERENCE);
+
}
private void updateAllPreferences() {
@@ -668,6 +671,7 @@
updateAutoclickSummary(mAutoclickPreferenceScreen);
updateAccessibilityShortcut(mAccessibilityShortcutPreferenceScreen);
+ checkAccessibilityShortcutVisibility(mAccessibilityShortcutPreferenceScreen);
}
private void updateMagnificationSummary(Preference pref) {
@@ -765,6 +769,13 @@
}
}
+ @VisibleForTesting void checkAccessibilityShortcutVisibility(Preference preference) {
+ if (!getContext().getResources().getBoolean(
+ R.bool.config_show_accessibility_shortcut_preference)) {
+ removePreference(ACCESSIBILITY_SHORTCUT_PREFERENCE);
+ }
+ }
+
private static void configureMagnificationPreferenceIfNeeded(Preference preference) {
// Some devices support only a single magnification mode. In these cases, we redirect to
// the magnification mode's UI directly, rather than showing a PreferenceScreen with a
@@ -800,6 +811,12 @@
keys.add(FONT_SIZE_PREFERENCE_SCREEN);
keys.add(KEY_DISPLAY_SIZE);
+ // Remove Accessibility Shortcuts if it's not visible
+ if (!context.getResources().getBoolean(
+ R.bool.config_show_accessibility_shortcut_preference)) {
+ keys.add(ACCESSIBILITY_SHORTCUT_PREFERENCE);
+ }
+
// Duplicates in Language & Input
keys.add(TTS_SETTINGS_PREFERENCE);
diff --git a/src/com/android/settings/applications/AppPermissionsPreferenceController.java b/src/com/android/settings/applications/AppPermissionsPreferenceController.java
index c8ff381..6100123 100644
--- a/src/com/android/settings/applications/AppPermissionsPreferenceController.java
+++ b/src/com/android/settings/applications/AppPermissionsPreferenceController.java
@@ -75,7 +75,8 @@
The 3 permissions are the first three from the list which any app has granted:
Location, Microphone, Camera, Sms, Contacts, and Phone
*/
- private String getSummary() {
+ @Override
+ public String getSummary() {
final Set<String> permissions = getAllPermissionsInGroups();
Set<String> grantedPermissionGroups = getGrantedPermissionGroups(permissions);
CharSequence summary = null;
diff --git a/src/com/android/settings/applications/DataSaverController.java b/src/com/android/settings/applications/DataSaverController.java
new file mode 100644
index 0000000..d9710fc
--- /dev/null
+++ b/src/com/android/settings/applications/DataSaverController.java
@@ -0,0 +1,40 @@
+/*
+ * 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.applications;
+
+import android.content.Context;
+import android.support.annotation.VisibleForTesting;
+
+import com.android.settings.core.BasePreferenceController;
+import com.android.settings.R;
+
+public class DataSaverController extends BasePreferenceController {
+
+ @VisibleForTesting static final String KEY_DATA_SAVER = "data_saver";
+
+ public DataSaverController(Context context) {
+ super(context, KEY_DATA_SAVER);
+ }
+
+ @AvailabilityStatus
+ public int getAvailabilityStatus() {
+ return mContext.getResources().getBoolean(R.bool.config_show_data_saver)
+ ? AVAILABLE
+ : DISABLED_UNSUPPORTED;
+ }
+}
\ No newline at end of file
diff --git a/src/com/android/settings/applications/DeviceAdministratorsController.java b/src/com/android/settings/applications/DeviceAdministratorsController.java
new file mode 100644
index 0000000..c7ef8ce
--- /dev/null
+++ b/src/com/android/settings/applications/DeviceAdministratorsController.java
@@ -0,0 +1,39 @@
+/*
+ * 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.applications;
+
+import android.content.Context;
+import android.support.annotation.VisibleForTesting;
+
+import com.android.settings.core.BasePreferenceController;
+import com.android.settings.R;
+
+public class DeviceAdministratorsController extends BasePreferenceController {
+
+ @VisibleForTesting static final String KEY_DEVICE_ADMIN = "device_administrators";
+
+ public DeviceAdministratorsController(Context context) {
+ super(context, KEY_DEVICE_ADMIN);
+ }
+
+ @AvailabilityStatus
+ public int getAvailabilityStatus() {
+ return mContext.getResources().getBoolean(R.bool.config_show_device_administrators)
+ ? AVAILABLE
+ : DISABLED_UNSUPPORTED;
+ }
+}
\ No newline at end of file
diff --git a/src/com/android/settings/applications/EnabledVrListenersController.java b/src/com/android/settings/applications/EnabledVrListenersController.java
new file mode 100644
index 0000000..94a70ef
--- /dev/null
+++ b/src/com/android/settings/applications/EnabledVrListenersController.java
@@ -0,0 +1,39 @@
+/*
+ * 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.applications;
+
+import android.content.Context;
+import android.support.annotation.VisibleForTesting;
+
+import com.android.settings.core.BasePreferenceController;
+import com.android.settings.R;
+
+public class EnabledVrListenersController extends BasePreferenceController {
+
+ @VisibleForTesting static final String KEY_ENABLED_VR_LISTENERS = "enabled_vr_listeners";
+
+ public EnabledVrListenersController(Context context) {
+ super(context, KEY_ENABLED_VR_LISTENERS);
+ }
+
+ @AvailabilityStatus
+ public int getAvailabilityStatus() {
+ return mContext.getResources().getBoolean(R.bool.config_show_enabled_vr_listeners)
+ ? AVAILABLE
+ : DISABLED_UNSUPPORTED;
+ }
+}
\ No newline at end of file
diff --git a/src/com/android/settings/applications/HighPowerAppsController.java b/src/com/android/settings/applications/HighPowerAppsController.java
new file mode 100644
index 0000000..dc847b3
--- /dev/null
+++ b/src/com/android/settings/applications/HighPowerAppsController.java
@@ -0,0 +1,39 @@
+/*
+ * 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.applications;
+
+import android.content.Context;
+import android.support.annotation.VisibleForTesting;
+
+import com.android.settings.core.BasePreferenceController;
+import com.android.settings.R;
+
+public class HighPowerAppsController extends BasePreferenceController {
+
+ @VisibleForTesting static final String KEY_HIGH_POWER_APPS = "high_power_apps";
+
+ public HighPowerAppsController(Context context) {
+ super(context, KEY_HIGH_POWER_APPS);
+ }
+
+ @AvailabilityStatus
+ public int getAvailabilityStatus() {
+ return mContext.getResources().getBoolean(R.bool.config_show_high_power_apps)
+ ? AVAILABLE
+ : DISABLED_UNSUPPORTED;
+ }
+}
\ No newline at end of file
diff --git a/src/com/android/settings/applications/PremiumSmsController.java b/src/com/android/settings/applications/PremiumSmsController.java
new file mode 100644
index 0000000..40911a5
--- /dev/null
+++ b/src/com/android/settings/applications/PremiumSmsController.java
@@ -0,0 +1,39 @@
+/*
+ * 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.applications;
+
+import android.content.Context;
+import android.support.annotation.VisibleForTesting;
+
+import com.android.settings.core.BasePreferenceController;
+import com.android.settings.R;
+
+public class PremiumSmsController extends BasePreferenceController {
+
+ @VisibleForTesting static final String KEY_PREMIUM_SMS = "premium_sms";
+
+ public PremiumSmsController(Context context) {
+ super(context, KEY_PREMIUM_SMS);
+ }
+
+ @AvailabilityStatus
+ public int getAvailabilityStatus() {
+ return mContext.getResources().getBoolean(R.bool.config_show_premium_sms)
+ ? AVAILABLE
+ : DISABLED_UNSUPPORTED;
+ }
+}
\ No newline at end of file
diff --git a/src/com/android/settings/applications/SpecialAccessSettings.java b/src/com/android/settings/applications/SpecialAccessSettings.java
index 73ae744..4e43c05 100644
--- a/src/com/android/settings/applications/SpecialAccessSettings.java
+++ b/src/com/android/settings/applications/SpecialAccessSettings.java
@@ -17,6 +17,7 @@
import android.app.ActivityManager;
import android.content.Context;
import android.os.Bundle;
+import android.support.annotation.NonNull;
import android.provider.SearchIndexableResource;
import android.support.v7.preference.Preference;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
@@ -31,7 +32,6 @@
public class SpecialAccessSettings extends DashboardFragment {
private static final String TAG = "SpecialAccessSettings";
-
private static final String[] DISABLED_FEATURES_LOW_RAM =
new String[]{"notification_access", "zen_access", "enabled_vr_listeners",
"picture_in_picture"};
@@ -62,7 +62,18 @@
@Override
protected List<AbstractPreferenceController> getPreferenceControllers(Context context) {
- return null;
+ return buildPreferenceControllers(context);
+ }
+
+ private static List<AbstractPreferenceController> buildPreferenceControllers(
+ @NonNull Context context) {
+ final List<AbstractPreferenceController> controllers = new ArrayList<>();
+ controllers.add(new HighPowerAppsController(context));
+ controllers.add(new DeviceAdministratorsController(context));
+ controllers.add(new PremiumSmsController(context));
+ controllers.add(new DataSaverController(context));
+ controllers.add(new EnabledVrListenersController(context));
+ return controllers;
}
@Override
@@ -82,5 +93,11 @@
result.add(sir);
return result;
}
+
+ @Override
+ public List<AbstractPreferenceController> getPreferenceControllers(
+ Context context) {
+ return buildPreferenceControllers(context);
+ }
};
}
diff --git a/src/com/android/settings/applications/appinfo/DefaultAppShortcutPreferenceControllerBase.java b/src/com/android/settings/applications/appinfo/DefaultAppShortcutPreferenceControllerBase.java
index fa67ec8..873c98c 100644
--- a/src/com/android/settings/applications/appinfo/DefaultAppShortcutPreferenceControllerBase.java
+++ b/src/com/android/settings/applications/appinfo/DefaultAppShortcutPreferenceControllerBase.java
@@ -14,7 +14,6 @@
package com.android.settings.applications.appinfo;
-import android.app.slice.Slice;
import android.content.Context;
import android.os.Bundle;
import android.os.UserManager;
@@ -52,7 +51,13 @@
@Override
public void updateState(Preference preference) {
- preference.setSummary(isDefaultApp() ? R.string.yes : R.string.no);
+ preference.setSummary(getSummary());
+ }
+
+ @Override
+ public String getSummary() {
+ int summaryResId = isDefaultApp() ? R.string.yes : R.string.no;
+ return mContext.getString(summaryResId);
}
@Override
@@ -69,12 +74,14 @@
/**
* Check whether the app has the default app capability
+ *
* @return true if the app has the default app capability
*/
protected abstract boolean hasAppCapability();
/**
* Check whether the app is the default app
+ *
* @return true if the app is the default app
*/
protected abstract boolean isDefaultApp();
diff --git a/src/com/android/settings/applications/appinfo/DrawOverlayDetailPreferenceController.java b/src/com/android/settings/applications/appinfo/DrawOverlayDetailPreferenceController.java
index 37a9edf..02f52b6 100644
--- a/src/com/android/settings/applications/appinfo/DrawOverlayDetailPreferenceController.java
+++ b/src/com/android/settings/applications/appinfo/DrawOverlayDetailPreferenceController.java
@@ -21,7 +21,6 @@
import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.UserManager;
-import android.support.annotation.VisibleForTesting;
import android.support.v7.preference.Preference;
import com.android.settings.SettingsPreferenceFragment;
@@ -61,9 +60,8 @@
return DrawOverlayDetails.class;
}
- @VisibleForTesting
- CharSequence getSummary() {
- return DrawOverlayDetails.getSummary(mContext, mParent.getAppEntry());
+ @Override
+ public String getSummary() {
+ return DrawOverlayDetails.getSummary(mContext, mParent.getAppEntry()).toString();
}
-
}
diff --git a/src/com/android/settings/applications/appinfo/WriteSystemSettingsPreferenceController.java b/src/com/android/settings/applications/appinfo/WriteSystemSettingsPreferenceController.java
index 2a88d2f..73e7675 100644
--- a/src/com/android/settings/applications/appinfo/WriteSystemSettingsPreferenceController.java
+++ b/src/com/android/settings/applications/appinfo/WriteSystemSettingsPreferenceController.java
@@ -21,7 +21,6 @@
import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.UserManager;
-import android.support.annotation.VisibleForTesting;
import android.support.v7.preference.Preference;
import com.android.settings.SettingsPreferenceFragment;
@@ -62,9 +61,9 @@
return WriteSettingsDetails.class;
}
- @VisibleForTesting
- CharSequence getSummary() {
- return WriteSettingsDetails.getSummary(mContext, mParent.getAppEntry());
- }
+ @Override
+ public String getSummary() {
+ return WriteSettingsDetails.getSummary(mContext, mParent.getAppEntry()).toString();
+ }
}
diff --git a/src/com/android/settings/applications/assist/DefaultAssistPreferenceController.java b/src/com/android/settings/applications/assist/DefaultAssistPreferenceController.java
index cba08c8..f78548b 100644
--- a/src/com/android/settings/applications/assist/DefaultAssistPreferenceController.java
+++ b/src/com/android/settings/applications/assist/DefaultAssistPreferenceController.java
@@ -26,6 +26,7 @@
import android.support.annotation.VisibleForTesting;
import com.android.internal.app.AssistUtils;
+import com.android.settings.R;
import com.android.settings.applications.defaultapps.DefaultAppInfo;
import com.android.settings.applications.defaultapps.DefaultAppPreferenceController;
@@ -73,7 +74,7 @@
@Override
public boolean isAvailable() {
- return true;
+ return mContext.getResources().getBoolean(R.bool.config_show_assist_and_voice_input);
}
@Override
diff --git a/src/com/android/settings/backup/BackupSettingsActivityPreferenceController.java b/src/com/android/settings/backup/BackupSettingsActivityPreferenceController.java
index 7a7530c..dccc310 100644
--- a/src/com/android/settings/backup/BackupSettingsActivityPreferenceController.java
+++ b/src/com/android/settings/backup/BackupSettingsActivityPreferenceController.java
@@ -23,8 +23,6 @@
import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
-import com.android.settings.core.PreferenceControllerMixin;
-import com.android.settingslib.core.AbstractPreferenceController;
public class BackupSettingsActivityPreferenceController extends BasePreferenceController {
private static final String TAG = "BackupSettingActivityPC";
@@ -49,10 +47,15 @@
@Override
public void updateState(Preference preference) {
+ preference.setSummary(getSummary());
+ }
+
+ @Override
+ public String getSummary() {
final boolean backupEnabled = mBackupManager.isBackupEnabled();
- preference.setSummary(backupEnabled
- ? R.string.accessibility_feature_state_on
- : R.string.accessibility_feature_state_off);
+ return backupEnabled
+ ? mContext.getString(R.string.accessibility_feature_state_on)
+ : mContext.getString(R.string.accessibility_feature_state_off);
}
}
\ No newline at end of file
diff --git a/src/com/android/settings/bluetooth/BluetoothDeviceNamePreferenceController.java b/src/com/android/settings/bluetooth/BluetoothDeviceNamePreferenceController.java
index 2d0ce60..bf13e07 100644
--- a/src/com/android/settings/bluetooth/BluetoothDeviceNamePreferenceController.java
+++ b/src/com/android/settings/bluetooth/BluetoothDeviceNamePreferenceController.java
@@ -109,7 +109,19 @@
@Override
public void updateState(Preference preference) {
- updateDeviceName(preference, mLocalAdapter.getName());
+ updateDeviceName(preference);
+ }
+
+ @Override
+ public String getSummary() {
+ String deviceName = getDeviceName();
+ if (TextUtils.isEmpty(deviceName)) {
+ return super.getSummary();
+ }
+
+ return TextUtils.expandTemplate(
+ mContext.getText(R.string.bluetooth_device_name_summary),
+ BidiFormatter.getInstance().unicodeWrap(deviceName)).toString();
}
/**
@@ -132,18 +144,14 @@
* Update device summary with {@code deviceName}, where {@code deviceName} has accent color
*
* @param preference to set the summary for
- * @param deviceName bluetooth device name to show in the summary
*/
- protected void updateDeviceName(final Preference preference, final String deviceName) {
- if (deviceName == null) {
- // TODO: show error message in preference subtitle
- return;
- }
- final CharSequence summary = TextUtils.expandTemplate(
- mContext.getText(R.string.bluetooth_device_name_summary),
- BidiFormatter.getInstance().unicodeWrap(deviceName));
+ protected void updateDeviceName(final Preference preference) {
preference.setSelectable(false);
- preference.setSummary(summary);
+ preference.setSummary(getSummary());
+ }
+
+ protected String getDeviceName() {
+ return mLocalAdapter.getName();
}
/**
@@ -158,7 +166,7 @@
if (TextUtils.equals(action, BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED)) {
if (mPreference != null && mLocalAdapter != null && mLocalAdapter.isEnabled()) {
- updateDeviceName(mPreference, mLocalAdapter.getName());
+ updateDeviceName(mPreference);
}
}
}
diff --git a/src/com/android/settings/bluetooth/BluetoothDeviceRenamePreferenceController.java b/src/com/android/settings/bluetooth/BluetoothDeviceRenamePreferenceController.java
index 69eefcf..a12d1a8 100644
--- a/src/com/android/settings/bluetooth/BluetoothDeviceRenamePreferenceController.java
+++ b/src/com/android/settings/bluetooth/BluetoothDeviceRenamePreferenceController.java
@@ -67,8 +67,13 @@
}
@Override
- protected void updateDeviceName(final Preference preference, final String deviceName) {
- preference.setSummary(deviceName);
+ protected void updateDeviceName(final Preference preference) {
+ preference.setSummary(getSummary());
+ }
+
+ @Override
+ public String getSummary() {
+ return getDeviceName();
}
@Override
diff --git a/src/com/android/settings/bluetooth/BluetoothSwitchPreferenceController.java b/src/com/android/settings/bluetooth/BluetoothSwitchPreferenceController.java
index 3482ee2..8a59768 100644
--- a/src/com/android/settings/bluetooth/BluetoothSwitchPreferenceController.java
+++ b/src/com/android/settings/bluetooth/BluetoothSwitchPreferenceController.java
@@ -98,10 +98,11 @@
}
@Override
- public void setChecked(boolean isChecked) {
+ public boolean setChecked(boolean isChecked) {
if (mBluetoothAdapter != null) {
mBluetoothAdapter.setBluetoothEnabled(isChecked);
}
+ return true;
}
/**
diff --git a/src/com/android/settings/core/FeatureFlags.java b/src/com/android/settings/core/FeatureFlags.java
index 4371b4a..e88fb11 100644
--- a/src/com/android/settings/core/FeatureFlags.java
+++ b/src/com/android/settings/core/FeatureFlags.java
@@ -21,9 +21,9 @@
*/
public class FeatureFlags {
public static final String SEARCH_V2 = "settings_search_v2";
- public static final String SUGGESTIONS_V2 = "new_settings_suggestion";
public static final String APP_INFO_V2 = "settings_app_info_v2";
public static final String CONNECTED_DEVICE_V2 = "settings_connected_device_v2";
public static final String BATTERY_SETTINGS_V2 = "settings_battery_v2";
public static final String BATTERY_DISPLAY_APP_LIST = "settings_battery_display_app_list";
+ public static final String SECURITY_SETTINGS_V2 = "settings_security_settings_v2";
}
diff --git a/src/com/android/settings/core/TogglePreferenceController.java b/src/com/android/settings/core/TogglePreferenceController.java
index 99d2ecc..5431f4d 100644
--- a/src/com/android/settings/core/TogglePreferenceController.java
+++ b/src/com/android/settings/core/TogglePreferenceController.java
@@ -14,8 +14,8 @@
package com.android.settings.core;
import android.content.Context;
-import android.support.v14.preference.SwitchPreference;
import android.support.v7.preference.Preference;
+import android.support.v7.preference.TwoStatePreference;
/**
* Abstract class that consolidates logic for updating toggle controllers.
@@ -40,18 +40,17 @@
* Set the Setting to {@param isChecked}
*
* @param isChecked Is {@true} when the setting should be enabled.
+ * @return {@true} if the underlying setting is updated.
*/
- public abstract void setChecked(boolean isChecked);
+ public abstract boolean setChecked(boolean isChecked);
@Override
public final void updateState(Preference preference) {
- ((SwitchPreference) preference).setChecked(isChecked());
+ ((TwoStatePreference) preference).setChecked(isChecked());
}
@Override
public final boolean onPreferenceChange(Preference preference, Object newValue) {
- boolean auto = (Boolean) newValue;
- setChecked(auto);
- return true;
+ return setChecked((Boolean) newValue);
}
}
\ No newline at end of file
diff --git a/src/com/android/settings/core/gateway/SettingsGateway.java b/src/com/android/settings/core/gateway/SettingsGateway.java
index b7c73f3..4c861fb 100644
--- a/src/com/android/settings/core/gateway/SettingsGateway.java
+++ b/src/com/android/settings/core/gateway/SettingsGateway.java
@@ -115,6 +115,7 @@
import com.android.settings.security.CryptKeeperSettings;
import com.android.settings.security.LockscreenDashboardFragment;
import com.android.settings.security.SecuritySettings;
+import com.android.settings.security.SecuritySettingsV2;
import com.android.settings.sim.SimSettings;
import com.android.settings.support.SupportDashboardActivity;
import com.android.settings.system.ResetDashboardFragment;
@@ -163,6 +164,7 @@
NotificationStation.class.getName(),
LocationSettings.class.getName(),
SecuritySettings.class.getName(),
+ SecuritySettingsV2.class.getName(),
UsageAccessDetails.class.getName(),
PrivacySettings.class.getName(),
DeviceAdminSettings.class.getName(),
diff --git a/src/com/android/settings/core/instrumentation/MetricsFeatureProvider.java b/src/com/android/settings/core/instrumentation/MetricsFeatureProvider.java
index 532ec66..166cbb8 100644
--- a/src/com/android/settings/core/instrumentation/MetricsFeatureProvider.java
+++ b/src/com/android/settings/core/instrumentation/MetricsFeatureProvider.java
@@ -39,7 +39,6 @@
protected void installLogWriters() {
mLoggerWriters.add(new EventLogWriter());
- mLoggerWriters.add(new SettingSuggestionsLogWriter());
}
public void visible(Context context, int source, int category) {
diff --git a/src/com/android/settings/core/instrumentation/SettingSuggestionsLogWriter.java b/src/com/android/settings/core/instrumentation/SettingSuggestionsLogWriter.java
deleted file mode 100644
index 697f0a3..0000000
--- a/src/com/android/settings/core/instrumentation/SettingSuggestionsLogWriter.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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.core.instrumentation;
-
-import android.content.Context;
-import android.util.Pair;
-
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.settings.dashboard.suggestions.EventStore;
-
-/**
- * {@link LogWriter} that writes setting suggestion related logs.
- */
-public class SettingSuggestionsLogWriter implements LogWriter {
-
- private EventStore mEventStore;
-
- @Override
- public void visible(Context context, int source, int category) {
- }
-
- @Override
- public void hidden(Context context, int category) {
- }
-
- @Override
- public void action(Context context, int category, Pair<Integer, Object>... taggedData) {
- }
-
- @Override
- public void actionWithSource(Context context, int source, int category) {
- }
-
- @Override
- public void action(int category, int value, Pair<Integer, Object>... taggedData) {
- }
-
- @Override
- public void action(int category, boolean value, Pair<Integer, Object>... taggedData) {
- }
-
- @Override
- public void action(Context context, int category, int value) {
- }
-
- @Override
- public void action(Context context, int category, boolean value) {
- }
-
- @Override
- public void action(Context context, int category, String pkg,
- Pair<Integer, Object>... taggedData) {
- if (mEventStore == null) {
- mEventStore = new EventStore(context);
- }
- switch (category) {
- case MetricsEvent.ACTION_SHOW_SETTINGS_SUGGESTION:
- mEventStore.writeEvent(pkg, EventStore.EVENT_SHOWN);
- break;
- case MetricsEvent.ACTION_SETTINGS_DISMISS_SUGGESTION:
- mEventStore.writeEvent(pkg, EventStore.EVENT_DISMISSED);
- break;
- case MetricsEvent.ACTION_SETTINGS_SUGGESTION:
- mEventStore.writeEvent(pkg, EventStore.EVENT_CLICKED);
- break;
- }
- }
-
- @Override
- public void count(Context context, String name, int value) {
- }
-
- @Override
- public void histogram(Context context, String name, int bucket) {
- }
-
-}
diff --git a/src/com/android/settings/dashboard/DashboardAdapter.java b/src/com/android/settings/dashboard/DashboardAdapter.java
index 3d473f0..97eef13 100644
--- a/src/com/android/settings/dashboard/DashboardAdapter.java
+++ b/src/com/android/settings/dashboard/DashboardAdapter.java
@@ -52,7 +52,6 @@
import com.android.settingslib.Utils;
import com.android.settingslib.drawer.DashboardCategory;
import com.android.settingslib.drawer.Tile;
-import com.android.settingslib.suggestions.SuggestionParser;
import java.util.ArrayList;
import java.util.List;
@@ -61,7 +60,6 @@
implements SummaryLoader.SummaryConsumer {
public static final String TAG = "DashboardAdapter";
private static final String STATE_SUGGESTION_LIST = "suggestion_list";
- private static final String STATE_SUGGESTION_LIST_V2 = "suggestion_list_v2";
private static final String STATE_CATEGORY_LIST = "category_list";
private static final String STATE_SUGGESTIONS_SHOWN_LOGGED = "suggestions_shown_logged";
@@ -69,8 +67,6 @@
static final String STATE_SUGGESTION_CONDITION_MODE = "suggestion_condition_mode";
@VisibleForTesting
static final int SUGGESTION_CONDITION_HEADER_POSITION = 0;
- @VisibleForTesting
- static final int MAX_SUGGESTION_TO_SHOW = 5;
private final IconCache mCache;
private final Context mContext;
@@ -80,7 +76,6 @@
private final ArrayList<String> mSuggestionsShownLogged;
private boolean mFirstFrameDrawn;
private RecyclerView mRecyclerView;
- private SuggestionParser mSuggestionParser;
private SuggestionAdapter mSuggestionAdapter;
private SuggestionDismissController mSuggestionDismissHandler;
private SuggestionDismissController.Callback mCallback;
@@ -97,13 +92,10 @@
};
public DashboardAdapter(Context context, Bundle savedInstanceState,
- List<Condition> conditions, SuggestionParser suggestionParser,
- SuggestionControllerMixin suggestionControllerMixin,
+ List<Condition> conditions, SuggestionControllerMixin suggestionControllerMixin,
SuggestionDismissController.Callback callback) {
- // @deprecated In favor of suggestionsV2 below.
- List<Tile> suggestions = null;
- List<Suggestion> suggestionsV2 = null;
+ List<Suggestion> suggestions = null;
DashboardCategory category = null;
int suggestionConditionMode = DashboardData.HEADER_MODE_DEFAULT;
@@ -113,14 +105,12 @@
mMetricsFeatureProvider = factory.getMetricsFeatureProvider();
mDashboardFeatureProvider = factory.getDashboardFeatureProvider(context);
mCache = new IconCache(context);
- mSuggestionParser = suggestionParser;
mCallback = callback;
setHasStableIds(true);
if (savedInstanceState != null) {
suggestions = savedInstanceState.getParcelableArrayList(STATE_SUGGESTION_LIST);
- suggestionsV2 = savedInstanceState.getParcelableArrayList(STATE_SUGGESTION_LIST_V2);
category = savedInstanceState.getParcelable(STATE_CATEGORY_LIST);
suggestionConditionMode = savedInstanceState.getInt(
STATE_SUGGESTION_CONDITION_MODE, suggestionConditionMode);
@@ -133,37 +123,15 @@
mDashboardData = new DashboardData.Builder()
.setConditions(conditions)
.setSuggestions(suggestions)
- .setSuggestionsV2(suggestionsV2)
.setCategory(category)
.setSuggestionConditionMode(suggestionConditionMode)
.build();
}
- public List<Tile> getSuggestions() {
- return mDashboardData.getSuggestions();
- }
-
- /**
- * @deprecated in favor of {@link #setCategory(DashboardCategory)} and
- * {@link #setSuggestionsV2(List)}.
- */
- @Deprecated
- public void setCategoriesAndSuggestions(DashboardCategory category, List<Tile> suggestions) {
- tintIcons(category, suggestions);
-
+ public void setSuggestions(List<Suggestion> data) {
final DashboardData prevData = mDashboardData;
mDashboardData = new DashboardData.Builder(prevData)
- .setSuggestions(suggestions.subList(0,
- Math.min(suggestions.size(), MAX_SUGGESTION_TO_SHOW)))
- .setCategory(category)
- .build();
- notifyDashboardDataChanged(prevData);
- }
-
- public void setSuggestionsV2(List<Suggestion> data) {
- final DashboardData prevData = mDashboardData;
- mDashboardData = new DashboardData.Builder(prevData)
- .setSuggestionsV2(data)
+ .setSuggestions(data)
.build();
notifyDashboardDataChanged(prevData);
}
@@ -187,30 +155,8 @@
notifyDashboardDataChanged(prevData);
}
- /**
- * @deprecated in favor of {@link #onSuggestionDismissed(Suggestion)}.
- */
- @Deprecated
- public void onSuggestionDismissed(Tile suggestion) {
- final List<Tile> suggestions = mDashboardData.getSuggestions();
- if (suggestions == null || suggestions.isEmpty()) {
- return;
- }
- if (suggestions.size() == 1) {
- // The only suggestion is dismissed, and the the empty suggestion container will
- // remain as the dashboard item. Need to refresh the dashboard list.
- final DashboardData prevData = mDashboardData;
- mDashboardData = new DashboardData.Builder(prevData)
- .setSuggestions(null)
- .build();
- notifyDashboardDataChanged(prevData);
- } else {
- mSuggestionAdapter.removeSuggestion(suggestion);
- }
- }
-
public void onSuggestionDismissed(Suggestion suggestion) {
- final List<Suggestion> list = mDashboardData.getSuggestionsV2();
+ final List<Suggestion> list = mDashboardData.getSuggestions();
if (list == null || list.size() == 0) {
return;
}
@@ -219,7 +165,7 @@
// remain as the dashboard item. Need to refresh the dashboard list.
final DashboardData prevData = mDashboardData;
mDashboardData = new DashboardData.Builder(prevData)
- .setSuggestionsV2(null)
+ .setSuggestions(null)
.build();
notifyDashboardDataChanged(prevData);
} else {
@@ -309,18 +255,10 @@
return mDashboardData.getItemEntityById(itemId);
}
- /**
- * @deprecated in favor of {@link #getSuggestionV2(int)}.
- */
- @Deprecated
- public Tile getSuggestion(int position) {
+ public Suggestion getSuggestion(int position) {
return mSuggestionAdapter.getSuggestion(position);
}
- public Suggestion getSuggestionV2(int position) {
- return mSuggestionAdapter.getSuggestionsV2(position);
- }
-
@VisibleForTesting
void notifyDashboardDataChanged(DashboardData prevData) {
if (mFirstFrameDrawn && prevData != null) {
@@ -422,26 +360,17 @@
int position) {
// If there is suggestions to show, it will be at position 0 as we don't show the suggestion
// header anymore.
- final List<Suggestion> suggestionsV2 = mDashboardData.getSuggestionsV2();
- final List<Tile> suggestions = mDashboardData.getSuggestions();
+ final List<Suggestion> suggestions = mDashboardData.getSuggestions();
boolean conditionOnly = true;
if (position == SUGGESTION_CONDITION_HEADER_POSITION) {
- if (suggestions != null && suggestions.size() > 0) {
+ if (suggestions != null && suggestions.size() > 0) {
conditionOnly = false;
mSuggestionAdapter = new SuggestionAdapter(mContext, mSuggestionControllerMixin,
- (List<Tile>) mDashboardData.getItemEntityByPosition(position),
- null, mSuggestionsShownLogged);
- mSuggestionDismissHandler = new SuggestionDismissController(mContext,
- holder.data, mSuggestionControllerMixin, mSuggestionParser, mCallback);
- holder.data.setAdapter(mSuggestionAdapter);
- } else if (suggestionsV2 != null && suggestionsV2.size() > 0) {
- conditionOnly = false;
- mSuggestionAdapter = new SuggestionAdapter(mContext, mSuggestionControllerMixin,
- null, (List<Suggestion>) mDashboardData.getItemEntityByPosition(position),
+ (List<Suggestion>) mDashboardData.getItemEntityByPosition(position),
mSuggestionsShownLogged);
mSuggestionDismissHandler = new SuggestionDismissController(mContext,
- holder.data, mSuggestionControllerMixin, null /* parser */, mCallback);
+ holder.data, mSuggestionControllerMixin, mCallback);
holder.data.setAdapter(mSuggestionAdapter);
}
}
@@ -494,14 +423,10 @@
void onSaveInstanceState(Bundle outState) {
final DashboardCategory category = mDashboardData.getCategory();
- final List<Tile> suggestions = mDashboardData.getSuggestions();
- final List<Suggestion> suggestionV2 = mDashboardData.getSuggestionsV2();
+ final List<Suggestion> suggestions = mDashboardData.getSuggestions();
if (suggestions != null) {
- outState.putParcelableArrayList(STATE_SUGGESTION_LIST, new ArrayList<>(suggestions));
- }
- if (suggestionV2 != null) {
- outState.putParcelableArrayList(STATE_SUGGESTION_LIST_V2,
- new ArrayList<>(suggestionV2));
+ outState.putParcelableArrayList(STATE_SUGGESTION_LIST,
+ new ArrayList<>(suggestions));
}
if (category != null) {
outState.putParcelable(STATE_CATEGORY_LIST, category);
diff --git a/src/com/android/settings/dashboard/DashboardData.java b/src/com/android/settings/dashboard/DashboardData.java
index 6407960..da2a526 100644
--- a/src/com/android/settings/dashboard/DashboardData.java
+++ b/src/com/android/settings/dashboard/DashboardData.java
@@ -69,16 +69,14 @@
private final List<Item> mItems;
private final DashboardCategory mCategory;
private final List<Condition> mConditions;
- private final List<Tile> mSuggestions;
- private final List<Suggestion> mSuggestionsV2;
+ private final List<Suggestion> mSuggestions;
@HeaderMode
private final int mSuggestionConditionMode;
private DashboardData(Builder builder) {
mCategory = builder.mCategory;
mConditions = builder.mConditions;
- mSuggestions = builder.mSuggestions;
- mSuggestionsV2 = builder.mSuggestionsV2;
+ mSuggestions = builder.mSuggestionsV2;
mSuggestionConditionMode = builder.mSuggestionConditionMode;
mItems = new ArrayList<>();
@@ -123,14 +121,10 @@
return mConditions;
}
- public List<Tile> getSuggestions() {
+ public List<Suggestion> getSuggestions() {
return mSuggestions;
}
- public List<Suggestion> getSuggestionsV2() {
- return mSuggestionsV2;
- }
-
public int getSuggestionConditionMode() {
return mSuggestionConditionMode;
}
@@ -197,22 +191,15 @@
* and mIsShowingAll, mSuggestionConditionMode flag.
*/
private void buildItemsData() {
- final boolean useSuggestionV2 = mSuggestionsV2 != null;
- final boolean hasSuggestions = useSuggestionV2
- ? sizeOf(mSuggestionsV2) > 0
- : sizeOf(mSuggestions) > 0;
+ final boolean hasSuggestions = sizeOf(mSuggestions) > 0;
final List<Condition> conditions = getConditionsToShow(mConditions);
final boolean hasConditions = sizeOf(conditions) > 0;
- final List<Tile> suggestions = getSuggestionsToShow(mSuggestions);
- final List<Suggestion> suggestionsV2 = getSuggestionsV2ToShow(mSuggestionsV2);
+ final List<Suggestion> suggestions = getSuggestionsToShow(mSuggestions);
- final int hiddenSuggestion;
- if (useSuggestionV2) {
- hiddenSuggestion = hasSuggestions ? sizeOf(mSuggestionsV2) - sizeOf(suggestionsV2) : 0;
- } else {
- hiddenSuggestion = hasSuggestions ? sizeOf(mSuggestions) - sizeOf(suggestions) : 0;
- }
+ final int hiddenSuggestion = hasSuggestions
+ ? sizeOf(mSuggestions) - sizeOf(suggestions)
+ : 0;
final boolean hasSuggestionAndCollapsed = hasSuggestions
&& mSuggestionConditionMode == HEADER_MODE_COLLAPSED;
@@ -231,15 +218,8 @@
R.layout.suggestion_condition_header,
STABLE_ID_SUGGESTION_CONDITION_MIDDLE_HEADER, onlyHasConditionAndCollapsed);
- if (useSuggestionV2) {
- addToItemList(suggestionsV2, R.layout.suggestion_condition_container,
- STABLE_ID_SUGGESTION_CONTAINER, sizeOf(suggestionsV2) > 0);
- } else {
- /* Suggestion container. This is the card view that contains the list of suggestions.
- * This will be added whenever the suggestion list is not empty */
- addToItemList(suggestions, R.layout.suggestion_condition_container,
- STABLE_ID_SUGGESTION_CONTAINER, sizeOf(suggestions) > 0);
- }
+ addToItemList(suggestions, R.layout.suggestion_condition_container,
+ STABLE_ID_SUGGESTION_CONTAINER, sizeOf(suggestions) > 0);
/* Second suggestion/condition header. This will be added when there is at least one
* suggestion or condition that is not currently displayed, and the user can expand the
@@ -296,22 +276,7 @@
return result;
}
- /**
- * @deprecated in favor of {@link #getSuggestionsV2ToShow}.
- */
- @Deprecated
- private List<Tile> getSuggestionsToShow(List<Tile> suggestions) {
- if (suggestions == null || mSuggestionConditionMode == HEADER_MODE_COLLAPSED) {
- return null;
- }
- if (mSuggestionConditionMode != HEADER_MODE_DEFAULT
- || suggestions.size() <= DEFAULT_SUGGESTION_COUNT) {
- return suggestions;
- }
- return suggestions.subList(0, DEFAULT_SUGGESTION_COUNT);
- }
-
- private List<Suggestion> getSuggestionsV2ToShow(List<Suggestion> suggestions) {
+ private List<Suggestion> getSuggestionsToShow(List<Suggestion> suggestions) {
if (suggestions == null || mSuggestionConditionMode == HEADER_MODE_COLLAPSED) {
return null;
}
@@ -333,11 +298,6 @@
private DashboardCategory mCategory;
private List<Condition> mConditions;
- /**
- * @deprecated in favor of SuggestionList
- */
- @Deprecated
- private List<Tile> mSuggestions;
private List<Suggestion> mSuggestionsV2;
public Builder() {
@@ -346,8 +306,7 @@
public Builder(DashboardData dashboardData) {
mCategory = dashboardData.mCategory;
mConditions = dashboardData.mConditions;
- mSuggestions = dashboardData.mSuggestions;
- mSuggestionsV2 = dashboardData.mSuggestionsV2;
+ mSuggestionsV2 = dashboardData.mSuggestions;
mSuggestionConditionMode = dashboardData.mSuggestionConditionMode;
}
@@ -361,16 +320,7 @@
return this;
}
- /**
- * @deprecated in favor of {@link #setSuggestionsV2(List)})}
- */
- @Deprecated
- public Builder setSuggestions(List<Tile> suggestions) {
- this.mSuggestions = suggestions;
- return this;
- }
-
- public Builder setSuggestionsV2(List<Suggestion> suggestions) {
+ public Builder setSuggestions(List<Suggestion> suggestions) {
this.mSuggestionsV2 = suggestions;
return this;
}
diff --git a/src/com/android/settings/dashboard/DashboardFeatureProviderImpl.java b/src/com/android/settings/dashboard/DashboardFeatureProviderImpl.java
index 9ef38b8..048f6ed 100644
--- a/src/com/android/settings/dashboard/DashboardFeatureProviderImpl.java
+++ b/src/com/android/settings/dashboard/DashboardFeatureProviderImpl.java
@@ -218,6 +218,10 @@
preference.setSummary(tile.summary);
} else if (tile.metaData != null
&& tile.metaData.containsKey(META_DATA_PREFERENCE_SUMMARY_URI)) {
+ // Set a placeholder summary before starting to fetch real summary, this is necessary
+ // to avoid preference height change.
+ preference.setSummary(R.string.summary_placeholder);
+
ThreadUtils.postOnBackgroundThread(() -> {
final Map<String, IContentProvider> providerMap = new ArrayMap<>();
final String uri = tile.metaData.getString(META_DATA_PREFERENCE_SUMMARY_URI);
diff --git a/src/com/android/settings/dashboard/DashboardFragment.java b/src/com/android/settings/dashboard/DashboardFragment.java
index 3e1e881..6a88a38 100644
--- a/src/com/android/settings/dashboard/DashboardFragment.java
+++ b/src/com/android/settings/dashboard/DashboardFragment.java
@@ -54,7 +54,7 @@
SummaryLoader.SummaryConsumer {
private static final String TAG = "DashboardFragment";
- private final Map<Class, AbstractPreferenceController> mPreferenceControllers =
+ private final Map<Class, List<AbstractPreferenceController>> mPreferenceControllers =
new ArrayMap<>();
private final Set<String> mDashboardTilePrefKeys = new ArraySet<>();
@@ -156,14 +156,17 @@
@Override
public boolean onPreferenceTreeClick(Preference preference) {
- Collection<AbstractPreferenceController> controllers = mPreferenceControllers.values();
+ Collection<List<AbstractPreferenceController>> controllers =
+ mPreferenceControllers.values();
// If preference contains intent, log it before handling.
mMetricsFeatureProvider.logDashboardStartIntent(
getContext(), preference.getIntent(), getMetricsCategory());
// Give all controllers a chance to handle click.
- for (AbstractPreferenceController controller : controllers) {
- if (controller.handlePreferenceTreeClick(preference)) {
- return true;
+ for (List<AbstractPreferenceController> controllerList : controllers) {
+ for (AbstractPreferenceController controller : controllerList) {
+ if (controller.handlePreferenceTreeClick(preference)) {
+ return true;
+ }
}
}
return super.onPreferenceTreeClick(preference);
@@ -189,12 +192,23 @@
protected abstract int getPreferenceScreenResId();
protected <T extends AbstractPreferenceController> T getPreferenceController(Class<T> clazz) {
- AbstractPreferenceController controller = mPreferenceControllers.get(clazz);
- return (T) controller;
+ List<AbstractPreferenceController> controllerList = mPreferenceControllers.get(clazz);
+ if (controllerList != null) {
+ if (controllerList.size() > 1) {
+ Log.w(TAG, "Multiple controllers of Class " + clazz.getSimpleName()
+ + " found, returning first one.");
+ }
+ return (T) controllerList.get(0);
+ }
+
+ return null;
}
protected void addPreferenceController(AbstractPreferenceController controller) {
- mPreferenceControllers.put(controller.getClass(), controller);
+ if (mPreferenceControllers.get(controller.getClass()) == null) {
+ mPreferenceControllers.put(controller.getClass(), new ArrayList<>());
+ }
+ mPreferenceControllers.get(controller.getClass()).add(controller);
}
/**
@@ -249,31 +263,32 @@
}
addPreferencesFromResource(resId);
final PreferenceScreen screen = getPreferenceScreen();
- Collection<AbstractPreferenceController> controllers = mPreferenceControllers.values();
- for (AbstractPreferenceController controller : controllers) {
- controller.displayPreference(screen);
- }
+ mPreferenceControllers.values().stream().flatMap(Collection::stream).forEach(
+ controller -> controller.displayPreference(screen));
}
/**
* Update state of each preference managed by PreferenceController.
*/
protected void updatePreferenceStates() {
- Collection<AbstractPreferenceController> controllers = mPreferenceControllers.values();
final PreferenceScreen screen = getPreferenceScreen();
- for (AbstractPreferenceController controller : controllers) {
- if (!controller.isAvailable()) {
- continue;
- }
- final String key = controller.getPreferenceKey();
+ Collection<List<AbstractPreferenceController>> controllerLists =
+ mPreferenceControllers.values();
+ for (List<AbstractPreferenceController> controllerList : controllerLists) {
+ for (AbstractPreferenceController controller : controllerList) {
+ if (!controller.isAvailable()) {
+ continue;
+ }
+ final String key = controller.getPreferenceKey();
- final Preference preference = screen.findPreference(key);
- if (preference == null) {
- Log.d(TAG, String.format("Cannot find preference with key %s in Controller %s",
- key, controller.getClass().getSimpleName()));
- continue;
+ final Preference preference = screen.findPreference(key);
+ if (preference == null) {
+ Log.d(TAG, String.format("Cannot find preference with key %s in Controller %s",
+ key, controller.getClass().getSimpleName()));
+ continue;
+ }
+ controller.updateState(preference);
}
- controller.updateState(preference);
}
}
diff --git a/src/com/android/settings/dashboard/DashboardFragmentRegistry.java b/src/com/android/settings/dashboard/DashboardFragmentRegistry.java
index e841496..0536403 100644
--- a/src/com/android/settings/dashboard/DashboardFragmentRegistry.java
+++ b/src/com/android/settings/dashboard/DashboardFragmentRegistry.java
@@ -33,7 +33,7 @@
import com.android.settings.notification.ConfigureNotificationSettings;
import com.android.settings.notification.SoundSettings;
import com.android.settings.security.LockscreenDashboardFragment;
-import com.android.settings.security.SecuritySettings;
+import com.android.settings.security.SecuritySettingsV2;
import com.android.settings.system.SystemDashboardFragment;
import com.android.settingslib.drawer.CategoryKey;
@@ -77,7 +77,7 @@
CategoryKey.CATEGORY_SOUND);
PARENT_TO_CATEGORY_KEY_MAP.put(StorageDashboardFragment.class.getName(),
CategoryKey.CATEGORY_STORAGE);
- PARENT_TO_CATEGORY_KEY_MAP.put(SecuritySettings.class.getName(),
+ PARENT_TO_CATEGORY_KEY_MAP.put(SecuritySettingsV2.class.getName(),
CategoryKey.CATEGORY_SECURITY);
PARENT_TO_CATEGORY_KEY_MAP.put(AccountDetailDashboardFragment.class.getName(),
CategoryKey.CATEGORY_ACCOUNT_DETAIL);
diff --git a/src/com/android/settings/dashboard/DashboardSummary.java b/src/com/android/settings/dashboard/DashboardSummary.java
index ff2a76a..61c202e 100644
--- a/src/com/android/settings/dashboard/DashboardSummary.java
+++ b/src/com/android/settings/dashboard/DashboardSummary.java
@@ -19,7 +19,6 @@
import android.app.Activity;
import android.app.LoaderManager;
import android.content.Context;
-import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.service.settings.suggestions.Suggestion;
@@ -41,19 +40,14 @@
import com.android.settings.dashboard.conditional.FocusRecyclerView.FocusListener;
import com.android.settings.dashboard.suggestions.SuggestionControllerMixin;
import com.android.settings.dashboard.suggestions.SuggestionDismissController;
-import com.android.settings.dashboard.suggestions.SuggestionFeatureProvider;
import com.android.settings.overlay.FeatureFactory;
import com.android.settings.widget.ActionBarShadowController;
import com.android.settingslib.drawer.CategoryKey;
import com.android.settingslib.drawer.DashboardCategory;
import com.android.settingslib.drawer.SettingsDrawerActivity;
import com.android.settingslib.drawer.SettingsDrawerActivity.CategoryListener;
-import com.android.settingslib.drawer.Tile;
-import com.android.settingslib.suggestions.SuggestionList;
-import com.android.settingslib.suggestions.SuggestionParser;
import com.android.settingslib.utils.ThreadUtils;
-import java.util.ArrayList;
import java.util.List;
public class DashboardSummary extends InstrumentedFragment
@@ -73,11 +67,9 @@
private DashboardAdapter mAdapter;
private SummaryLoader mSummaryLoader;
private ConditionManager mConditionManager;
- private SuggestionParser mSuggestionParser;
private LinearLayoutManager mLayoutManager;
private SuggestionControllerMixin mSuggestionControllerMixin;
private DashboardFeatureProvider mDashboardFeatureProvider;
- private SuggestionFeatureProvider mSuggestionFeatureProvider;
private boolean isOnCategoriesChangedCalled;
private boolean mOnConditionsChangedCalled;
@@ -92,13 +84,9 @@
@Override
public void onAttach(Context context) {
super.onAttach(context);
- mSuggestionFeatureProvider = FeatureFactory.getFactory(context)
- .getSuggestionFeatureProvider(context);
- if (mSuggestionFeatureProvider.isSuggestionV2Enabled(context)) {
- Log.d(TAG, "Suggestion v2 is enabled, creating SuggestionControllerMixin");
- mSuggestionControllerMixin = new SuggestionControllerMixin(context, this /* host */,
- getLifecycle());
- }
+ Log.d(TAG, "Creating SuggestionControllerMixin");
+ mSuggestionControllerMixin = new SuggestionControllerMixin(context, this /* host */,
+ getLifecycle());
}
@Override
@@ -121,10 +109,6 @@
mConditionManager = ConditionManager.get(activity, false);
getLifecycle().addObserver(mConditionManager);
- if (mSuggestionFeatureProvider.isSuggestionEnabled(activity)) {
- mSuggestionParser = new SuggestionParser(activity,
- mSuggestionFeatureProvider.getSharedPrefs(activity), R.xml.suggestion_ordering);
- }
if (DEBUG_TIMING) {
Log.d(TAG, "onCreate took " + (System.currentTimeMillis() - startTime) + " ms");
}
@@ -211,8 +195,7 @@
mDashboard.setHasFixedSize(true);
mDashboard.setListener(this);
mAdapter = new DashboardAdapter(getContext(), bundle, mConditionManager.getConditions(),
- mSuggestionParser, mSuggestionControllerMixin,
- this /* SuggestionDismissController.Callback */);
+ mSuggestionControllerMixin, this /* SuggestionDismissController.Callback */);
mDashboard.setAdapter(mAdapter);
mDashboard.setItemAnimator(new DashboardItemAnimator());
mSummaryLoader.setSummaryConsumer(mAdapter);
@@ -228,16 +211,7 @@
@VisibleForTesting
void rebuildUI() {
- if (!mSuggestionFeatureProvider.isSuggestionEnabled(getContext())) {
- Log.d(TAG, "Suggestion v1 feature is disabled, skipping suggestion v1");
- ThreadUtils.postOnBackgroundThread(() -> updateCategory());
- } else {
- new SuggestionLoader().execute();
- // Set categories on their own if loading suggestions takes too long.
- mHandler.postDelayed(() -> {
- updateCategory();
- }, MAX_WAIT_MILLIS);
- }
+ ThreadUtils.postOnBackgroundThread(() -> updateCategory());
}
@Override
@@ -274,20 +248,10 @@
@Override
public Suggestion getSuggestionAt(int position) {
- return mAdapter.getSuggestionV2(position);
- }
-
- @Override
- public Tile getSuggestionForPosition(int position) {
return mAdapter.getSuggestion(position);
}
@Override
- public void onSuggestionDismissed(Tile suggestion) {
- mAdapter.onSuggestionDismissed(suggestion);
- }
-
- @Override
public void onSuggestionDismissed(Suggestion suggestion) {
mAdapter.onSuggestionDismissed(suggestion);
}
@@ -295,7 +259,7 @@
@Override
public void onSuggestionReady(List<Suggestion> suggestions) {
mStagingSuggestions = suggestions;
- mAdapter.setSuggestionsV2(suggestions);
+ mAdapter.setSuggestions(suggestions);
if (mStagingCategory != null) {
Log.d(TAG, "Category has loaded, setting category from suggestionReady");
mHandler.removeCallbacksAndMessages(null);
@@ -303,49 +267,6 @@
}
}
- /**
- * @deprecated in favor of {@link #mSuggestionControllerMixin}.
- */
- @Deprecated
- private class SuggestionLoader extends AsyncTask<Void, Void, List<Tile>> {
- @Override
- protected List<Tile> doInBackground(Void... params) {
- final Context context = getContext();
- boolean isSmartSuggestionEnabled =
- mSuggestionFeatureProvider.isSmartSuggestionEnabled(context);
- final SuggestionList sl = mSuggestionParser.getSuggestions(isSmartSuggestionEnabled);
- final List<Tile> suggestions = sl.getSuggestions();
-
- if (isSmartSuggestionEnabled) {
- List<String> suggestionIds = new ArrayList<>(suggestions.size());
- for (Tile suggestion : suggestions) {
- suggestionIds.add(mSuggestionFeatureProvider.getSuggestionIdentifier(
- context, suggestion));
- }
- // TODO: create a Suggestion class to maintain the id and other info
- mSuggestionFeatureProvider.rankSuggestions(suggestions, suggestionIds);
- }
- for (int i = 0; i < suggestions.size(); i++) {
- Tile suggestion = suggestions.get(i);
- if (mSuggestionFeatureProvider.isSuggestionComplete(context,
- suggestion.intent.getComponent())) {
- suggestions.remove(i--);
- }
- }
- if (sl.isExclusiveSuggestionCategory()) {
- mSuggestionFeatureProvider.filterExclusiveSuggestions(suggestions);
- }
- return suggestions;
- }
-
- @Override
- protected void onPostExecute(List<Tile> tiles) {
- // tell handler that suggestions were loaded quickly enough
- mHandler.removeCallbacksAndMessages(null);
- updateCategoryAndSuggestion(tiles);
- }
- }
-
@WorkerThread
void updateCategory() {
final DashboardCategory category = mDashboardFeatureProvider.getTilesForCategory(
@@ -356,7 +277,7 @@
Log.d(TAG, "Suggestion has loaded, setting suggestion/category");
ThreadUtils.postOnMainThread(() -> {
if (mStagingSuggestions != null) {
- mAdapter.setSuggestionsV2(mStagingSuggestions);
+ mAdapter.setSuggestions(mStagingSuggestions);
}
mAdapter.setCategory(mStagingCategory);
});
@@ -365,26 +286,4 @@
mHandler.postDelayed(() -> mAdapter.setCategory(mStagingCategory), MAX_WAIT_MILLIS);
}
}
-
- /**
- * @deprecated in favor of {@link #mSuggestionControllerMixin}.
- */
- @Deprecated
- @VisibleForTesting
- void updateCategoryAndSuggestion(List<Tile> suggestions) {
- final Activity activity = getActivity();
- if (activity == null) {
- return;
- }
-
- final DashboardCategory category = mDashboardFeatureProvider.getTilesForCategory(
- CategoryKey.CATEGORY_HOMEPAGE);
- mSummaryLoader.updateSummaryToCache(category);
- if (suggestions != null) {
- mAdapter.setCategoriesAndSuggestions(category, suggestions);
- } else {
- mAdapter.setCategory(category);
- }
- }
-
}
diff --git a/src/com/android/settings/dashboard/SummaryLoader.java b/src/com/android/settings/dashboard/SummaryLoader.java
index 5af276c..c91882d 100644
--- a/src/com/android/settings/dashboard/SummaryLoader.java
+++ b/src/com/android/settings/dashboard/SummaryLoader.java
@@ -306,7 +306,7 @@
makeProviderW(tile);
break;
case MSG_SET_LISTENING:
- boolean listening = msg.arg1 != 0;
+ boolean listening = msg.obj != null && msg.obj.equals(1);
setListeningW(listening);
break;
}
diff --git a/src/com/android/settings/dashboard/suggestions/EventStore.java b/src/com/android/settings/dashboard/suggestions/EventStore.java
deleted file mode 100644
index cc3872e..0000000
--- a/src/com/android/settings/dashboard/suggestions/EventStore.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * 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.dashboard.suggestions;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.util.Log;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Stores suggestion related statistics.
- */
-public class EventStore {
-
- public static final String TAG = "SuggestionEventStore";
-
- public static final String EVENT_SHOWN = "shown";
- public static final String EVENT_DISMISSED = "dismissed";
- public static final String EVENT_CLICKED = "clicked";
- public static final String METRIC_LAST_EVENT_TIME = "last_event_time";
- public static final String METRIC_COUNT = "count";
-
- private static final Set<String> EVENTS = new HashSet<String>(
- Arrays.asList(new String[] {EVENT_SHOWN, EVENT_DISMISSED, EVENT_CLICKED}));
- private static final Set<String> METRICS = new HashSet<String>(
- Arrays.asList(new String[] {METRIC_LAST_EVENT_TIME, METRIC_COUNT}));
-
- private final SharedPreferences mSharedPrefs;
-
- public EventStore(Context context) {
- mSharedPrefs = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
- }
-
- /**
- * Writes individual log events.
- * @param pkgName: Package for which this event is reported.
- * @param eventType: Type of event (one of {@link #EVENTS}).
- */
- public void writeEvent(String pkgName, String eventType) {
- if (!EVENTS.contains(eventType)) {
- Log.w(TAG, "Reported event type " + eventType + " is not a valid type!");
- return;
- }
- final String lastTimePrefKey = getPrefKey(pkgName, eventType, METRIC_LAST_EVENT_TIME);
- final String countPrefKey = getPrefKey(pkgName, eventType, METRIC_COUNT);
- writePref(lastTimePrefKey, System.currentTimeMillis());
- writePref(countPrefKey, readPref(countPrefKey, (long) 0) + 1);
- }
-
- /**
- * Reads metric of the the reported events (e.g., counts).
- * @param pkgName: Package for which this metric is queried.
- * @param eventType: Type of event (one of {@link #EVENTS}).
- * @param metricType: Type of the queried metric (one of {@link #METRICS}).
- * @return the corresponding metric.
- */
- public long readMetric(String pkgName, String eventType, String metricType) {
- if (!EVENTS.contains(eventType)) {
- Log.w(TAG, "Reported event type " + eventType + " is not a valid event!");
- return 0;
- } else if (!METRICS.contains(metricType)) {
- Log.w(TAG, "Required stat type + " + metricType + " is not a valid stat!");
- return 0;
- }
- return readPref(getPrefKey(pkgName, eventType, metricType), (long) 0);
- }
-
- private void writePref(String prefKey, long value) {
- mSharedPrefs.edit().putLong(prefKey, value).apply();
- }
-
- private long readPref(String prefKey, Long defaultValue) {
- return mSharedPrefs.getLong(prefKey, defaultValue);
- }
-
- private String getPrefKey(String pkgName, String eventType, String statType) {
- return new StringBuilder()
- .append("setting_suggestion_")
- .append(pkgName)
- .append("_")
- .append(eventType)
- .append("_")
- .append(statType)
- .toString();
- }
-}
diff --git a/src/com/android/settings/dashboard/suggestions/SuggestionAdapter.java b/src/com/android/settings/dashboard/suggestions/SuggestionAdapter.java
index 293c95a..fc11029 100644
--- a/src/com/android/settings/dashboard/suggestions/SuggestionAdapter.java
+++ b/src/com/android/settings/dashboard/suggestions/SuggestionAdapter.java
@@ -27,12 +27,10 @@
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.R;
-import com.android.settings.SettingsActivity;
import com.android.settings.core.instrumentation.MetricsFeatureProvider;
import com.android.settings.dashboard.DashboardAdapter.DashboardItemHolder;
import com.android.settings.dashboard.DashboardAdapter.IconCache;
import com.android.settings.overlay.FeatureFactory;
-import com.android.settingslib.drawer.Tile;
import java.util.List;
import java.util.Objects;
@@ -42,26 +40,20 @@
private final Context mContext;
private final MetricsFeatureProvider mMetricsFeatureProvider;
- private final SuggestionFeatureProvider mSuggestionFeatureProvider;
- @Deprecated // in favor of mSuggestionsV2
- private final List<Tile> mSuggestions;
- private final List<Suggestion> mSuggestionsV2;
+ private final List<Suggestion> mSuggestions;
private final IconCache mCache;
private final List<String> mSuggestionsShownLogged;
private final SuggestionControllerMixin mSuggestionControllerMixin;
public SuggestionAdapter(Context context, SuggestionControllerMixin suggestionControllerMixin,
- List<Tile> suggestions, List<Suggestion> suggestionsV2,
- List<String> suggestionsShownLogged) {
+ List<Suggestion> suggestions, List<String> suggestionsShownLogged) {
mContext = context;
mSuggestionControllerMixin = suggestionControllerMixin;
mSuggestions = suggestions;
- mSuggestionsV2 = suggestionsV2;
mSuggestionsShownLogged = suggestionsShownLogged;
mCache = new IconCache(context);
final FeatureFactory factory = FeatureFactory.getFactory(context);
mMetricsFeatureProvider = factory.getMetricsFeatureProvider();
- mSuggestionFeatureProvider = factory.getSuggestionFeatureProvider(context);
setHasStableIds(true);
}
@@ -74,15 +66,11 @@
@Override
public void onBindViewHolder(DashboardItemHolder holder, int position) {
- if (mSuggestions != null) {
- bindSuggestionTile(holder, position);
- } else {
- bindSuggestion(holder, position);
- }
+ bindSuggestion(holder, position);
}
private void bindSuggestion(DashboardItemHolder holder, int position) {
- final Suggestion suggestion = mSuggestionsV2.get(position);
+ final Suggestion suggestion = mSuggestions.get(position);
final String id = suggestion.getId();
if (!mSuggestionsShownLogged.contains(id)) {
mMetricsFeatureProvider.action(
@@ -101,7 +89,7 @@
}
final View divider = holder.itemView.findViewById(R.id.divider);
if (divider != null) {
- divider.setVisibility(position < mSuggestionsV2.size() - 1 ? View.VISIBLE : View.GONE);
+ divider.setVisibility(position < mSuggestions.size() - 1 ? View.VISIBLE : View.GONE);
}
View clickHandler = holder.itemView;
// If a view with @android:id/primary is defined, use that as the click handler
@@ -121,110 +109,32 @@
});
}
- /**
- * @deprecated in favor {@link #bindSuggestion(DashboardItemHolder, int)}.
- */
- @Deprecated
- private void bindSuggestionTile(DashboardItemHolder holder, int position) {
- final Tile suggestion = (Tile) mSuggestions.get(position);
- final String suggestionId = mSuggestionFeatureProvider.getSuggestionIdentifier(
- mContext, suggestion);
- // This is for cases when a suggestion is dismissed and the next one comes to view
- if (!mSuggestionsShownLogged.contains(suggestionId)) {
- mMetricsFeatureProvider.action(
- mContext, MetricsEvent.ACTION_SHOW_SETTINGS_SUGGESTION, suggestionId,
- mSuggestionFeatureProvider.getLoggingTaggedData(mContext));
- mSuggestionsShownLogged.add(suggestionId);
- }
- if (suggestion.remoteViews != null) {
- final ViewGroup itemView = (ViewGroup) holder.itemView;
- itemView.removeAllViews();
- itemView.addView(suggestion.remoteViews.apply(itemView.getContext(), itemView));
- } else {
- holder.icon.setImageDrawable(mCache.getIcon(suggestion.icon));
- holder.title.setText(suggestion.title);
- if (!TextUtils.isEmpty(suggestion.summary)) {
- holder.summary.setText(suggestion.summary);
- holder.summary.setVisibility(View.VISIBLE);
- } else {
- holder.summary.setVisibility(View.GONE);
- }
- }
- final View divider = holder.itemView.findViewById(R.id.divider);
- if (divider != null) {
- divider.setVisibility(position < mSuggestions.size() - 1 ? View.VISIBLE : View.GONE);
- }
- View clickHandler = holder.itemView;
- // If a view with @android:id/primary is defined, use that as the click handler
- // instead.
- final View primaryAction = holder.itemView.findViewById(android.R.id.primary);
- if (primaryAction != null) {
- clickHandler = primaryAction;
- }
-
- clickHandler.setOnClickListener(v -> {
- mMetricsFeatureProvider.action(mContext,
- MetricsEvent.ACTION_SETTINGS_SUGGESTION, suggestionId,
- mSuggestionFeatureProvider.getLoggingTaggedData(mContext));
- ((SettingsActivity) mContext).startSuggestion(suggestion.intent);
- });
- }
-
@Override
public long getItemId(int position) {
- if (mSuggestions != null) {
- return Objects.hash(mSuggestions.get(position).title);
- } else {
- return Objects.hash(mSuggestionsV2.get(position).getId());
- }
+ return Objects.hash(mSuggestions.get(position).getId());
}
@Override
public int getItemViewType(int position) {
- if (mSuggestions != null) {
- Tile suggestion = getSuggestion(position);
-
- return suggestion.remoteViews != null
- ? R.layout.suggestion_tile_remote_container
- : R.layout.suggestion_tile;
+ final Suggestion suggestion = getSuggestion(position);
+ if ((suggestion.getFlags() & Suggestion.FLAG_HAS_BUTTON) != 0) {
+ return R.layout.suggestion_tile_with_button;
} else {
- final Suggestion suggestion = getSuggestionsV2(position);
- if ((suggestion.getFlags() & Suggestion.FLAG_HAS_BUTTON) != 0) {
- return R.layout.suggestion_tile_with_button;
- } else {
- return R.layout.suggestion_tile;
- }
+ return R.layout.suggestion_tile;
}
}
@Override
public int getItemCount() {
- if (mSuggestions != null) {
- return mSuggestions.size();
- } else {
- return mSuggestionsV2.size();
- }
+ return mSuggestions.size();
}
- public Tile getSuggestion(int position) {
+ public Suggestion getSuggestion(int position) {
final long itemId = getItemId(position);
if (mSuggestions == null) {
return null;
}
- for (Tile tile : mSuggestions) {
- if (Objects.hash(tile.title) == itemId) {
- return tile;
- }
- }
- return null;
- }
-
- public Suggestion getSuggestionsV2(int position) {
- final long itemId = getItemId(position);
- if (mSuggestionsV2 == null) {
- return null;
- }
- for (Suggestion suggestion : mSuggestionsV2) {
+ for (Suggestion suggestion : mSuggestions) {
if (Objects.hash(suggestion.getId()) == itemId) {
return suggestion;
}
@@ -232,13 +142,8 @@
return null;
}
- public void removeSuggestion(Tile suggestion) {
- mSuggestions.remove(suggestion);
- notifyDataSetChanged();
- }
-
public void removeSuggestion(Suggestion suggestion) {
- mSuggestionsV2.remove(suggestion);
+ mSuggestions.remove(suggestion);
notifyDataSetChanged();
}
}
diff --git a/src/com/android/settings/dashboard/suggestions/SuggestionDismissController.java b/src/com/android/settings/dashboard/suggestions/SuggestionDismissController.java
index f269f69..de0c129 100644
--- a/src/com/android/settings/dashboard/suggestions/SuggestionDismissController.java
+++ b/src/com/android/settings/dashboard/suggestions/SuggestionDismissController.java
@@ -23,27 +23,10 @@
import com.android.settings.R;
import com.android.settings.overlay.FeatureFactory;
-import com.android.settingslib.drawer.Tile;
-import com.android.settingslib.suggestions.SuggestionParser;
public class SuggestionDismissController extends ItemTouchHelper.SimpleCallback {
public interface Callback {
-
- /**
- * @deprecated in favor of {@link #getSuggestionAt(int)}
- * Returns suggestion tile data from the callback
- */
- @Deprecated
- Tile getSuggestionForPosition(int position);
-
- /**
- * @deprecated in favor of {@link #onSuggestionDismissed(Suggestion)}
- * Called when a suggestion is dismissed.
- */
- @Deprecated
- void onSuggestionDismissed(Tile suggestion);
-
/**
* Returns suggestion tile data from the callback
*/
@@ -58,20 +41,13 @@
private final Context mContext;
private final SuggestionFeatureProvider mSuggestionFeatureProvider;
private final SuggestionControllerMixin mSuggestionMixin;
-
- /**
- * @deprecated in favor of the new Suggestion backend.
- */
- @Deprecated
- private final SuggestionParser mSuggestionParser;
private final Callback mCallback;
public SuggestionDismissController(Context context, RecyclerView recyclerView,
- SuggestionControllerMixin suggestionMixin, SuggestionParser parser, Callback callback) {
+ SuggestionControllerMixin suggestionMixin, Callback callback) {
super(0, ItemTouchHelper.START | ItemTouchHelper.END);
mSuggestionMixin = suggestionMixin;
mContext = context;
- mSuggestionParser = parser;
mSuggestionFeatureProvider = FeatureFactory.getFactory(context)
.getSuggestionFeatureProvider(context);
mCallback = callback;
@@ -103,13 +79,7 @@
}
final int position = viewHolder.getAdapterPosition();
final Suggestion suggestionV2 = mCallback.getSuggestionAt(position);
- if (suggestionV2 != null) {
- mSuggestionFeatureProvider.dismissSuggestion(mContext, mSuggestionMixin, suggestionV2);
- mCallback.onSuggestionDismissed(suggestionV2);
- } else {
- final Tile suggestion = mCallback.getSuggestionForPosition(position);
- mSuggestionFeatureProvider.dismissSuggestion(mContext, mSuggestionParser, suggestion);
- mCallback.onSuggestionDismissed(suggestion);
- }
+ mSuggestionFeatureProvider.dismissSuggestion(mContext, mSuggestionMixin, suggestionV2);
+ mCallback.onSuggestionDismissed(suggestionV2);
}
}
diff --git a/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProvider.java b/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProvider.java
index f911401..bdc29e7 100644
--- a/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProvider.java
+++ b/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProvider.java
@@ -24,7 +24,6 @@
import android.util.Pair;
import com.android.settingslib.drawer.Tile;
-import com.android.settingslib.suggestions.SuggestionParser;
import java.util.List;
@@ -33,14 +32,6 @@
/**
* Whether or not the whole suggestion feature is enabled.
- *
- * @deprecated in favor of {@link #isSuggestionV2Enabled(Context)}
- */
- @Deprecated
- boolean isSuggestionEnabled(Context context);
-
- /**
- * Whether or not the suggestion v2 feature is enabled.
*/
boolean isSuggestionV2Enabled(Context context);
@@ -63,44 +54,17 @@
SharedPreferences getSharedPrefs(Context context);
/**
- * Ranks the list of suggestions in place.
- *
- * @param suggestions List of suggestion Tiles
- * @param suggestionIds List of suggestion ids corresponding to the suggestion tiles.
- * @deprecated in favor of SettingsIntelligence
- */
- @Deprecated
- void rankSuggestions(final List<Tile> suggestions, List<String> suggestionIds);
-
- /**
* Only keep top few suggestions from exclusive suggestions.
*/
void filterExclusiveSuggestions(List<Tile> suggestions);
/**
* Dismisses a suggestion.
- *
- * @deprecated in favor of {@link #dismissSuggestion(Context, SuggestionControllerMixin,
- * Suggestion)}
- */
- @Deprecated
- void dismissSuggestion(Context context, SuggestionParser parser, Tile suggestion);
-
- /**
- * Dismisses a suggestion.
*/
void dismissSuggestion(Context context, SuggestionControllerMixin suggestionMixin,
Suggestion suggestion);
/**
- * Returns an identifier for the suggestion
- *
- * @deprecated in favor or {@link Suggestion#getId()}
- */
- @Deprecated
- String getSuggestionIdentifier(Context context, Tile suggestion);
-
- /**
* Returns common tagged data for suggestion logging.
*/
Pair<Integer, Object>[] getLoggingTaggedData(Context context);
diff --git a/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProviderImpl.java b/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProviderImpl.java
index 3fc2fb2..fe19b95 100644
--- a/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProviderImpl.java
+++ b/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProviderImpl.java
@@ -16,19 +16,15 @@
package com.android.settings.dashboard.suggestions;
-import static com.android.settings.core.FeatureFlags.SUGGESTIONS_V2;
-
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
-import android.content.pm.PackageManager;
import android.provider.Settings.Secure;
import android.service.settings.suggestions.Suggestion;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
-import android.util.FeatureFlagUtils;
import android.util.Log;
import android.util.Pair;
@@ -54,7 +50,6 @@
import com.android.settings.wallpaper.WallpaperSuggestionActivity;
import com.android.settings.wifi.WifiCallingSuggestionActivity;
import com.android.settingslib.drawer.Tile;
-import com.android.settingslib.suggestions.SuggestionParser;
import java.util.List;
@@ -65,23 +60,13 @@
private static final String SHARED_PREF_FILENAME = "suggestions";
- private final SuggestionRanker mSuggestionRanker;
private final MetricsFeatureProvider mMetricsFeatureProvider;
@Override
- public boolean isSuggestionEnabled(Context context) {
- final ActivityManager am =
- (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
- boolean isLowRamDevice = am.isLowRamDevice();
- return !isLowRamDevice && !isV2Enabled(context);
- }
-
- @Override
public boolean isSuggestionV2Enabled(Context context) {
final ActivityManager am =
(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
- boolean isLowRamDevice = am.isLowRamDevice();
- return !isLowRamDevice && isV2Enabled(context);
+ return !am.isLowRamDevice();
}
@Override
@@ -91,10 +76,6 @@
"com.android.settings.intelligence.suggestions.SuggestionService");
}
- private static boolean isV2Enabled(Context context) {
- return FeatureFlagUtils.isEnabled(context, SUGGESTIONS_V2);
- }
-
@Override
public boolean isSmartSuggestionEnabled(Context context) {
return false;
@@ -143,18 +124,11 @@
public SuggestionFeatureProviderImpl(Context context) {
final Context appContext = context.getApplicationContext();
- mSuggestionRanker = new SuggestionRanker(
- new SuggestionFeaturizer(new EventStore(appContext)));
mMetricsFeatureProvider = FeatureFactory.getFactory(appContext)
.getMetricsFeatureProvider();
}
@Override
- public void rankSuggestions(final List<Tile> suggestions, List<String> suggestionIds) {
- mSuggestionRanker.rankSuggestions(suggestions, suggestionIds);
- }
-
- @Override
public void filterExclusiveSuggestions(List<Tile> suggestions) {
if (suggestions == null) {
return;
@@ -166,26 +140,6 @@
}
@Override
- public void dismissSuggestion(Context context, SuggestionParser parser, Tile suggestion) {
- if (parser == null || suggestion == null || context == null) {
- return;
- }
- final Pair<Integer, Object>[] taggedData = getLoggingTaggedData(context);
-
- mMetricsFeatureProvider.action(
- context, MetricsEvent.ACTION_SETTINGS_DISMISS_SUGGESTION,
- getSuggestionIdentifier(context, suggestion),
- taggedData);
- if (!parser.dismissSuggestion(suggestion)) {
- return;
- }
- context.getPackageManager().setComponentEnabledSetting(
- suggestion.intent.getComponent(),
- PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
- PackageManager.DONT_KILL_APP);
- }
-
- @Override
public void dismissSuggestion(Context context, SuggestionControllerMixin mixin,
Suggestion suggestion) {
if (mixin == null || suggestion == null || context == null) {
@@ -198,24 +152,9 @@
}
@Override
- public String getSuggestionIdentifier(Context context, Tile suggestion) {
- if (suggestion.intent == null || suggestion.intent.getComponent() == null
- || context == null) {
- return "unknown_suggestion";
- }
- String packageName = suggestion.intent.getComponent().getPackageName();
- if (packageName.equals(context.getPackageName())) {
- // Since Settings provides several suggestions, fill in the class instead of the
- // package for these.
- packageName = suggestion.intent.getComponent().getClassName();
- }
- return packageName;
- }
-
- @Override
public Pair<Integer, Object>[] getLoggingTaggedData(Context context) {
final boolean isSmartSuggestionEnabled = isSmartSuggestionEnabled(context);
- return new Pair[]{Pair.create(
+ return new Pair[] {Pair.create(
MetricsEvent.FIELD_SETTINGS_SMART_SUGGESTIONS_ENABLED,
isSmartSuggestionEnabled ? 1 : 0)};
}
diff --git a/src/com/android/settings/dashboard/suggestions/SuggestionFeaturizer.java b/src/com/android/settings/dashboard/suggestions/SuggestionFeaturizer.java
deleted file mode 100644
index 18ac50a..0000000
--- a/src/com/android/settings/dashboard/suggestions/SuggestionFeaturizer.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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.dashboard.suggestions;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Creates a set of interaction features (i.e., metrics) to represent each setting suggestion. These
- * features currently include normalized time from previous events (shown, dismissed and clicked)
- * for any particular suggestion and also counts of these events. These features are used as signals
- * to find the best ranking for suggestion items.
- */
-public class SuggestionFeaturizer {
-
- // Key of the features used for ranking.
- public static final String FEATURE_IS_SHOWN = "is_shown";
- public static final String FEATURE_IS_DISMISSED = "is_dismissed";
- public static final String FEATURE_IS_CLICKED = "is_clicked";
- public static final String FEATURE_TIME_FROM_LAST_SHOWN = "time_from_last_shown";
- public static final String FEATURE_TIME_FROM_LAST_DISMISSED = "time_from_last_dismissed";
- public static final String FEATURE_TIME_FROM_LAST_CLICKED = "time_from_last_clicked";
- public static final String FEATURE_SHOWN_COUNT = "shown_count";
- public static final String FEATURE_DISMISSED_COUNT = "dismissed_count";
- public static final String FEATURE_CLICKED_COUNT = "clicked_count";
-
- // The following numbers are estimated from histograms.
- public static final double TIME_NORMALIZATION_FACTOR = 2e10;
- public static final double COUNT_NORMALIZATION_FACTOR = 500;
-
- private final EventStore mEventStore;
-
- /**
- * Constructor
- *
- * @param eventStore An instance of {@code EventStore} which maintains the recorded suggestion
- * events.
- */
- public SuggestionFeaturizer(EventStore eventStore) {
- mEventStore = eventStore;
- }
-
- /**
- * Extracts the features for each package name.
- *
- * @param pkgNames: List of package names for which features are queried.
- * @return A Map containing the features, keyed by the package names. Each map value contains
- * another map with key-value pairs of the features.
- */
- public Map<String, Map<String, Double>> featurize(List<String> pkgNames) {
- Map<String, Map<String, Double>> features = new HashMap<>();
- Long curTimeMs = System.currentTimeMillis();
- for (String pkgName : pkgNames) {
- Map<String, Double> featureMap = new HashMap<>();
- features.put(pkgName, featureMap);
- Long lastShownTime = mEventStore
- .readMetric(pkgName, EventStore.EVENT_SHOWN, EventStore.METRIC_LAST_EVENT_TIME);
- Long lastDismissedTime = mEventStore.readMetric(pkgName, EventStore.EVENT_DISMISSED,
- EventStore.METRIC_LAST_EVENT_TIME);
- Long lastClickedTime = mEventStore.readMetric(pkgName, EventStore.EVENT_CLICKED,
- EventStore.METRIC_LAST_EVENT_TIME);
- featureMap.put(FEATURE_IS_SHOWN, booleanToDouble(lastShownTime > 0));
- featureMap.put(FEATURE_IS_DISMISSED, booleanToDouble(lastDismissedTime > 0));
- featureMap.put(FEATURE_IS_CLICKED, booleanToDouble(lastClickedTime > 0));
- featureMap.put(FEATURE_TIME_FROM_LAST_SHOWN,
- normalizedTimeDiff(curTimeMs, lastShownTime));
- featureMap.put(FEATURE_TIME_FROM_LAST_DISMISSED,
- normalizedTimeDiff(curTimeMs, lastDismissedTime));
- featureMap.put(FEATURE_TIME_FROM_LAST_CLICKED,
- normalizedTimeDiff(curTimeMs, lastClickedTime));
- featureMap.put(FEATURE_SHOWN_COUNT, normalizedCount(mEventStore
- .readMetric(pkgName, EventStore.EVENT_SHOWN, EventStore.METRIC_COUNT)));
- featureMap.put(FEATURE_DISMISSED_COUNT, normalizedCount(mEventStore
- .readMetric(pkgName, EventStore.EVENT_DISMISSED, EventStore.METRIC_COUNT)));
- featureMap.put(FEATURE_CLICKED_COUNT, normalizedCount(mEventStore
- .readMetric(pkgName, EventStore.EVENT_CLICKED, EventStore.METRIC_COUNT)));
- }
- return features;
- }
-
- private static double booleanToDouble(boolean bool) {
- return bool ? 1 : 0;
- }
-
- private static double normalizedTimeDiff(long curTimeMs, long preTimeMs) {
- return Math.min(1, (curTimeMs - preTimeMs) / TIME_NORMALIZATION_FACTOR);
- }
-
- private static double normalizedCount(long count) {
- return Math.min(1, count / COUNT_NORMALIZATION_FACTOR);
- }
-}
diff --git a/src/com/android/settings/dashboard/suggestions/SuggestionRanker.java b/src/com/android/settings/dashboard/suggestions/SuggestionRanker.java
deleted file mode 100644
index 14c4b15..0000000
--- a/src/com/android/settings/dashboard/suggestions/SuggestionRanker.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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.dashboard.suggestions;
-
-import com.android.settingslib.drawer.Tile;
-
-import android.support.annotation.VisibleForTesting;
-
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class SuggestionRanker {
-
- private static final String TAG = "SuggestionRanker";
-
- // The following coefficients form a linear model, which mixes the features to obtain a
- // relevance metric for ranking the suggestion items. This model is learned with off-line data
- // by training a binary classifier to detect the clicked items. The higher the obtained
- // relevance metric, the higher chance of getting clicked.
- private static final Map<String, Double> WEIGHTS = new HashMap<String, Double>() {{
- put(SuggestionFeaturizer.FEATURE_IS_SHOWN, 5.05140842519);
- put(SuggestionFeaturizer.FEATURE_IS_DISMISSED, 2.29641455171);
- put(SuggestionFeaturizer.FEATURE_IS_CLICKED, -2.98812233623);
- put(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_SHOWN, 5.02807250202);
- put(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_DISMISSED, 2.49589700842);
- put(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_CLICKED, -4.3377039948);
- put(SuggestionFeaturizer.FEATURE_SHOWN_COUNT, -2.35993512546);
- }};
-
- private final SuggestionFeaturizer mSuggestionFeaturizer;
-
- private final Map<Tile, Double> relevanceMetrics;
-
- Comparator<Tile> suggestionComparator = new Comparator<Tile>() {
- @Override
- public int compare(Tile suggestion1, Tile suggestion2) {
- return relevanceMetrics.get(suggestion1) < relevanceMetrics.get(suggestion2) ? 1 : -1;
- }
- };
-
- public SuggestionRanker(SuggestionFeaturizer suggestionFeaturizer) {
- mSuggestionFeaturizer = suggestionFeaturizer;
- relevanceMetrics = new HashMap<Tile, Double>();
- }
-
- public void rankSuggestions(final List<Tile> suggestions, List<String> suggestionIds) {
- relevanceMetrics.clear();
- Map<String, Map<String, Double>> features = mSuggestionFeaturizer.featurize(suggestionIds);
- for (int i = 0; i < suggestionIds.size(); i++) {
- relevanceMetrics.put(suggestions.get(i),
- getRelevanceMetric(features.get(suggestionIds.get(i))));
- }
- Collections.sort(suggestions, suggestionComparator);
- }
-
- @VisibleForTesting
- double getRelevanceMetric(Map<String, Double> features) {
- double sum = 0;
- if (features == null) {
- return sum;
- }
- for (String feature : WEIGHTS.keySet()) {
- sum += WEIGHTS.get(feature) * features.get(feature);
- }
- return sum;
- }
-}
diff --git a/src/com/android/settings/development/BluetoothInbandRingingPreferenceController.java b/src/com/android/settings/development/BluetoothInbandRingingPreferenceController.java
index db5a881..809db19 100644
--- a/src/com/android/settings/development/BluetoothInbandRingingPreferenceController.java
+++ b/src/com/android/settings/development/BluetoothInbandRingingPreferenceController.java
@@ -31,11 +31,11 @@
DeveloperOptionsPreferenceController implements Preference.OnPreferenceChangeListener,
PreferenceControllerMixin {
- private static final String BLUETOOTH_ENABLE_INBAND_RINGING_KEY =
- "bluetooth_enable_inband_ringing";
+ private static final String BLUETOOTH_DISABLE_INBAND_RINGING_KEY =
+ "bluetooth_disable_inband_ringing";
@VisibleForTesting
- static final String BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY =
- "persist.bluetooth.enableinbandringing";
+ static final String BLUETOOTH_DISABLE_INBAND_RINGING_PROPERTY =
+ "persist.bluetooth.disableinbandringing";
private SwitchPreference mPreference;
@@ -50,7 +50,7 @@
@Override
public String getPreferenceKey() {
- return BLUETOOTH_ENABLE_INBAND_RINGING_KEY;
+ return BLUETOOTH_DISABLE_INBAND_RINGING_KEY;
}
@Override
@@ -62,16 +62,16 @@
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
- final boolean isEnabled = (Boolean) newValue;
- SystemProperties.set(BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY,
- isEnabled ? "true" : "false");
+ final boolean isChecked = (Boolean) newValue;
+ SystemProperties.set(BLUETOOTH_DISABLE_INBAND_RINGING_PROPERTY,
+ isChecked ? "true" : "false");
return true;
}
@Override
public void updateState(Preference preference) {
final boolean isEnabled = SystemProperties.getBoolean(
- BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY, true /* default */);
+ BLUETOOTH_DISABLE_INBAND_RINGING_PROPERTY, false /* default */);
mPreference.setChecked(isEnabled);
}
@@ -83,9 +83,8 @@
@Override
protected void onDeveloperOptionsSwitchDisabled() {
mPreference.setEnabled(false);
- // the default setting for this preference is the enabled state
- mPreference.setChecked(true);
- SystemProperties.set(BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY, "true");
+ mPreference.setChecked(false);
+ SystemProperties.set(BLUETOOTH_DISABLE_INBAND_RINGING_PROPERTY, "false");
}
@VisibleForTesting
diff --git a/src/com/android/settings/development/BluetoothMaxConnectedAudioDevicesPreferenceController.java b/src/com/android/settings/development/BluetoothMaxConnectedAudioDevicesPreferenceController.java
new file mode 100644
index 0000000..5512685
--- /dev/null
+++ b/src/com/android/settings/development/BluetoothMaxConnectedAudioDevicesPreferenceController.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2018 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.development;
+
+import android.content.Context;
+import android.os.SystemProperties;
+import android.support.annotation.VisibleForTesting;
+import android.support.v7.preference.ListPreference;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+import android.text.TextUtils;
+
+import com.android.settings.R;
+import com.android.settings.core.PreferenceControllerMixin;
+import com.android.settingslib.development.DeveloperOptionsPreferenceController;
+
+public class BluetoothMaxConnectedAudioDevicesPreferenceController extends
+ DeveloperOptionsPreferenceController implements Preference.OnPreferenceChangeListener,
+ PreferenceControllerMixin {
+
+ private static final String BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_KEY =
+ "bluetooth_max_connected_audio_devices";
+
+ @VisibleForTesting
+ static final String BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_PROPERTY =
+ "persist.bluetooth.maxconnectedaudiodevices";
+
+ private final String[] mListValues;
+ private final String[] mListSummaries;
+ private ListPreference mPreference;
+
+ public BluetoothMaxConnectedAudioDevicesPreferenceController(Context context) {
+ super(context);
+
+ mListValues = context.getResources()
+ .getStringArray(R.array.bluetooth_max_connected_audio_devices_values);
+ mListSummaries = context.getResources()
+ .getStringArray(R.array.bluetooth_max_connected_audio_devices);
+ }
+
+ @Override
+ public String getPreferenceKey() {
+ return BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_KEY;
+ }
+
+ @Override
+ public void displayPreference(PreferenceScreen screen) {
+ super.displayPreference(screen);
+
+ mPreference = (ListPreference) screen.findPreference(getPreferenceKey());
+ }
+
+ @Override
+ public boolean onPreferenceChange(Preference preference, Object newValue) {
+ SystemProperties.set(BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_PROPERTY, newValue.toString());
+ updateState(preference);
+ return true;
+ }
+
+ @Override
+ public void updateState(Preference preference) {
+ final String currentValue = SystemProperties.get(
+ BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_PROPERTY);
+ int index = 0; // Defaults to 1 device
+ for (int i = 0; i < mListValues.length; i++) {
+ if (TextUtils.equals(currentValue, mListValues[i])) {
+ index = i;
+ break;
+ }
+ }
+ mPreference.setValue(mListValues[index]);
+ mPreference.setSummary(mListSummaries[index]);
+ }
+
+ @Override
+ protected void onDeveloperOptionsSwitchEnabled() {
+ mPreference.setEnabled(true);
+ updateState(mPreference);
+ }
+
+ @Override
+ protected void onDeveloperOptionsSwitchDisabled() {
+ mPreference.setEnabled(false);
+ SystemProperties.set(BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_PROPERTY, mListValues[0]);
+ mPreference.setValue(mListValues[0]);
+ mPreference.setSummary(mListSummaries[0]);
+ }
+}
+
diff --git a/src/com/android/settings/development/DevelopmentSettingsDashboardFragment.java b/src/com/android/settings/development/DevelopmentSettingsDashboardFragment.java
index e736798..a404bc0 100644
--- a/src/com/android/settings/development/DevelopmentSettingsDashboardFragment.java
+++ b/src/com/android/settings/development/DevelopmentSettingsDashboardFragment.java
@@ -417,6 +417,7 @@
bluetoothA2dpConfigStore));
controllers.add(new BluetoothAudioQualityPreferenceController(context, lifecycle,
bluetoothA2dpConfigStore));
+ controllers.add(new BluetoothMaxConnectedAudioDevicesPreferenceController(context));
controllers.add(new ShowTapsPreferenceController(context));
controllers.add(new PointerLocationPreferenceController(context));
controllers.add(new ShowSurfaceUpdatesPreferenceController(context));
diff --git a/src/com/android/settings/deviceinfo/StorageWizardMigrateConfirm.java b/src/com/android/settings/deviceinfo/StorageWizardMigrateConfirm.java
index d9e42df..8c8b90e 100644
--- a/src/com/android/settings/deviceinfo/StorageWizardMigrateConfirm.java
+++ b/src/com/android/settings/deviceinfo/StorageWizardMigrateConfirm.java
@@ -16,22 +16,28 @@
package com.android.settings.deviceinfo;
+import static com.android.settings.deviceinfo.StorageSettings.TAG;
+
import android.content.Intent;
import android.content.pm.PackageManager;
+import android.content.pm.UserInfo;
import android.os.Bundle;
+import android.os.UserManager;
import android.os.storage.DiskInfo;
import android.os.storage.StorageManager;
import android.os.storage.VolumeInfo;
+import android.text.TextUtils;
import android.util.Log;
-
import android.widget.Toast;
+
import com.android.settings.R;
+import com.android.settings.password.ChooseLockSettingsHelper;
import java.util.Objects;
-import static com.android.settings.deviceinfo.StorageSettings.TAG;
-
public class StorageWizardMigrateConfirm extends StorageWizardBase {
+ private static final int REQUEST_CREDENTIAL = 100;
+
private MigrateEstimateTask mEstimate;
@Override
@@ -75,9 +81,22 @@
@Override
public void onNavigateNext() {
- int moveId;
+ // Ensure that all users are unlocked so that we can move their data
+ if (StorageManager.isFileEncryptedNativeOrEmulated()) {
+ for (UserInfo user : getSystemService(UserManager.class).getUsers()) {
+ if (!StorageManager.isUserKeyUnlocked(user.id)) {
+ Log.d(TAG, "User " + user.id + " is currently locked; requesting unlock");
+ final CharSequence description = TextUtils.expandTemplate(
+ getText(R.string.storage_wizard_move_unlock), user.name);
+ new ChooseLockSettingsHelper(this).launchConfirmationActivityForAnyUser(
+ REQUEST_CREDENTIAL, null, null, description, user.id);
+ return;
+ }
+ }
+ }
// We only expect exceptions from StorageManagerService#setPrimaryStorageUuid
+ int moveId;
try {
moveId = getPackageManager().movePrimaryStorage(mVolume);
} catch (IllegalArgumentException e) {
@@ -108,4 +127,22 @@
startActivity(intent);
finishAffinity();
}
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (requestCode == REQUEST_CREDENTIAL) {
+ if (resultCode == RESULT_OK) {
+ // Credentials confirmed, so storage should be unlocked; let's
+ // go look for the next locked user.
+ onNavigateNext();
+ } else {
+ // User wasn't able to confirm credentials, so we're okay
+ // landing back at the wizard page again, where they read
+ // instructions again and tap "Next" to try again.
+ Log.w(TAG, "Failed to confirm credentials");
+ }
+ } else {
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+ }
}
diff --git a/src/com/android/settings/deviceinfo/StorageWizardMoveConfirm.java b/src/com/android/settings/deviceinfo/StorageWizardMoveConfirm.java
index 65b3d1f..e82612c 100644
--- a/src/com/android/settings/deviceinfo/StorageWizardMoveConfirm.java
+++ b/src/com/android/settings/deviceinfo/StorageWizardMoveConfirm.java
@@ -16,20 +16,30 @@
package com.android.settings.deviceinfo;
-import android.content.Intent;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.os.Bundle;
-
-import com.android.internal.util.Preconditions;
-import com.android.settings.R;
-
import static android.content.Intent.EXTRA_PACKAGE_NAME;
import static android.content.Intent.EXTRA_TITLE;
import static android.content.pm.PackageManager.EXTRA_MOVE_ID;
import static android.os.storage.VolumeInfo.EXTRA_VOLUME_ID;
+import static com.android.settings.deviceinfo.StorageSettings.TAG;
+
+import android.content.Intent;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.UserInfo;
+import android.os.Bundle;
+import android.os.UserManager;
+import android.os.storage.StorageManager;
+import android.text.TextUtils;
+import android.util.Log;
+
+import com.android.internal.util.Preconditions;
+import com.android.settings.R;
+import com.android.settings.password.ChooseLockSettingsHelper;
+
public class StorageWizardMoveConfirm extends StorageWizardBase {
+ private static final int REQUEST_CREDENTIAL = 100;
+
private String mPackageName;
private ApplicationInfo mApp;
@@ -66,6 +76,20 @@
@Override
public void onNavigateNext() {
+ // Ensure that all users are unlocked so that we can move their data
+ if (StorageManager.isFileEncryptedNativeOrEmulated()) {
+ for (UserInfo user : getSystemService(UserManager.class).getUsers()) {
+ if (!StorageManager.isUserKeyUnlocked(user.id)) {
+ Log.d(TAG, "User " + user.id + " is currently locked; requesting unlock");
+ final CharSequence description = TextUtils.expandTemplate(
+ getText(R.string.storage_wizard_move_unlock), user.name);
+ new ChooseLockSettingsHelper(this).launchConfirmationActivityForAnyUser(
+ REQUEST_CREDENTIAL, null, null, description, user.id);
+ return;
+ }
+ }
+ }
+
// Kick off move before we transition
final String appName = getPackageManager().getApplicationLabel(mApp).toString();
final int moveId = getPackageManager().movePackage(mPackageName, mVolume);
@@ -77,4 +101,22 @@
startActivity(intent);
finishAffinity();
}
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (requestCode == REQUEST_CREDENTIAL) {
+ if (resultCode == RESULT_OK) {
+ // Credentials confirmed, so storage should be unlocked; let's
+ // go look for the next locked user.
+ onNavigateNext();
+ } else {
+ // User wasn't able to confirm credentials, so we're okay
+ // landing back at the wizard page again, where they read
+ // instructions again and tap "Next" to try again.
+ Log.w(TAG, "Failed to confirm credentials");
+ }
+ } else {
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+ }
}
diff --git a/src/com/android/settings/deviceinfo/SystemUpdatePreferenceController.java b/src/com/android/settings/deviceinfo/SystemUpdatePreferenceController.java
index 92c33d8..a061f82 100644
--- a/src/com/android/settings/deviceinfo/SystemUpdatePreferenceController.java
+++ b/src/com/android/settings/deviceinfo/SystemUpdatePreferenceController.java
@@ -78,8 +78,12 @@
@Override
public void updateState(Preference preference) {
- preference.setSummary(mContext.getString(R.string.about_summary,
- Build.VERSION.RELEASE));
+ preference.setSummary(getSummary());
+ }
+
+ @Override
+ public String getSummary() {
+ return mContext.getString(R.string.about_summary, Build.VERSION.RELEASE);
}
/**
diff --git a/src/com/android/settings/display/AutoBrightnessPreferenceController.java b/src/com/android/settings/display/AutoBrightnessPreferenceController.java
index d71a1f8..28f9260 100644
--- a/src/com/android/settings/display/AutoBrightnessPreferenceController.java
+++ b/src/com/android/settings/display/AutoBrightnessPreferenceController.java
@@ -45,9 +45,10 @@
}
@Override
- public void setChecked(boolean isChecked) {
+ public boolean setChecked(boolean isChecked) {
Settings.System.putInt(mContext.getContentResolver(), SYSTEM_KEY,
isChecked ? SCREEN_BRIGHTNESS_MODE_AUTOMATIC : DEFAULT_VALUE);
+ return true;
}
@Override
diff --git a/src/com/android/settings/fingerprint/FingerprintProfileStatusPreferenceController.java b/src/com/android/settings/fingerprint/FingerprintProfileStatusPreferenceController.java
new file mode 100644
index 0000000..68d2ade
--- /dev/null
+++ b/src/com/android/settings/fingerprint/FingerprintProfileStatusPreferenceController.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2018 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.fingerprint;
+
+import android.content.Context;
+import android.os.UserHandle;
+
+public class FingerprintProfileStatusPreferenceController
+ extends FingerprintStatusPreferenceController {
+
+ public static final String KEY_FINGERPRINT_SETTINGS = "fingerprint_settings_profile";
+
+ public FingerprintProfileStatusPreferenceController(Context context) {
+ super(context, KEY_FINGERPRINT_SETTINGS);
+ }
+
+ @Override
+ protected boolean isUserSupported() {
+ return mProfileChallengeUserId != UserHandle.USER_NULL
+ && mLockPatternUtils.isSeparateProfileChallengeAllowed(mProfileChallengeUserId);
+ }
+
+ @Override
+ protected int getUserId() {
+ return mProfileChallengeUserId;
+ }
+}
diff --git a/src/com/android/settings/fingerprint/FingerprintSettings.java b/src/com/android/settings/fingerprint/FingerprintSettings.java
index ad7f83a..de7187c 100644
--- a/src/com/android/settings/fingerprint/FingerprintSettings.java
+++ b/src/com/android/settings/fingerprint/FingerprintSettings.java
@@ -25,12 +25,10 @@
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
-import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.hardware.fingerprint.Fingerprint;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Bundle;
-import android.os.CancellationSignal;
import android.os.Handler;
import android.os.UserHandle;
import android.os.UserManager;
@@ -41,12 +39,7 @@
import android.support.v7.preference.PreferenceGroup;
import android.support.v7.preference.PreferenceScreen;
import android.support.v7.preference.PreferenceViewHolder;
-import android.text.Annotation;
-import android.text.SpannableString;
-import android.text.SpannableStringBuilder;
-import android.text.TextPaint;
import android.text.TextUtils;
-import android.text.style.URLSpan;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
@@ -61,6 +54,7 @@
import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
import com.android.settings.password.ChooseLockGeneric;
import com.android.settings.password.ChooseLockSettingsHelper;
+import com.android.settings.utils.AnnotationSpan;
import com.android.settingslib.HelpUtils;
import com.android.settingslib.RestrictedLockUtils;
import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
@@ -103,6 +97,9 @@
private static final long LOCKOUT_DURATION = 30000; // time we have to wait for fp to reset, ms
+ public static final String ANNOTATION_URL = "url";
+ public static final String ANNOTATION_ADMIN_DETAILS = "admin_details";
+
public static final String KEY_FINGERPRINT_SETTINGS = "fingerprint_settings";
@Override
@@ -162,6 +159,20 @@
private FingerprintRemoveSidecar mRemovalSidecar;
private HashMap<Integer, String> mFingerprintsRenaming;
+ final AnnotationSpan.LinkInfo mUrlLinkInfo = new AnnotationSpan.LinkInfo(
+ ANNOTATION_URL, (view) -> {
+ final Context context = view.getContext();
+ Intent intent = HelpUtils.getHelpIntent(context, getString(getHelpResource()),
+ context.getClass().getName());
+ if (intent != null) {
+ try {
+ view.startActivityForResult(intent, 0);
+ } catch (ActivityNotFoundException e) {
+ Log.w(TAG, "Activity was not found for intent, " + intent.toString());
+ }
+ }
+ });
+
FingerprintAuthenticateSidecar.Listener mAuthenticateListener =
new FingerprintAuthenticateSidecar.Listener() {
@Override
@@ -346,10 +357,15 @@
final FooterPreference pref = mFooterPreferenceMixin.createFooterPreference();
final EnforcedAdmin admin = RestrictedLockUtils.checkIfKeyguardFeaturesDisabled(
activity, DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT, mUserId);
- pref.setTitle(LearnMoreSpan.linkify(getText(admin != null
- ? R.string.security_settings_fingerprint_enroll_disclaimer_lockscreen_disabled
+ final AnnotationSpan.LinkInfo adminLinkInfo = new AnnotationSpan.LinkInfo(
+ ANNOTATION_ADMIN_DETAILS, (view) -> {
+ RestrictedLockUtils.sendShowAdminSupportDetailsIntent(activity, admin);
+ });
+ pref.setTitle(AnnotationSpan.linkify(getText(admin != null
+ ? R.string
+ .security_settings_fingerprint_enroll_disclaimer_lockscreen_disabled
: R.string.security_settings_fingerprint_enroll_disclaimer),
- getString(getHelpResource()), admin));
+ mUrlLinkInfo, adminLinkInfo));
}
protected void removeFingerprintPreference(int fingerprintId) {
@@ -906,74 +922,10 @@
}
}
- private static class LearnMoreSpan extends URLSpan {
- private static final String TAG = "LearnMoreSpan";
- private static final Typeface TYPEFACE_MEDIUM =
- Typeface.create("sans-serif-medium", Typeface.NORMAL);
-
- private static final String ANNOTATION_URL = "url";
- private static final String ANNOTATION_ADMIN_DETAILS = "admin_details";
-
- private EnforcedAdmin mEnforcedAdmin = null;
-
- private LearnMoreSpan(String url) {
- super(url);
- }
-
- private LearnMoreSpan(EnforcedAdmin admin) {
- super((String) null);
- mEnforcedAdmin = admin;
- }
-
- @Override
- public void onClick(View widget) {
- Context ctx = widget.getContext();
- if (mEnforcedAdmin != null) {
- RestrictedLockUtils.sendShowAdminSupportDetailsIntent(ctx, mEnforcedAdmin);
- } else {
- Intent intent = HelpUtils.getHelpIntent(ctx, getURL(), ctx.getClass().getName());
- if (intent == null) {
- Log.w(LearnMoreSpan.TAG, "Null help intent.");
- return;
- }
- try {
- widget.startActivityForResult(intent, 0);
- } catch (ActivityNotFoundException e) {
- Log.w(FingerprintSettingsFragment.TAG,
- "Actvity was not found for intent, " + intent.toString());
- }
- }
- }
-
- @Override
- public void updateDrawState(TextPaint ds) {
- super.updateDrawState(ds);
- ds.setUnderlineText(false);
- ds.setTypeface(TYPEFACE_MEDIUM);
- }
-
- public static CharSequence linkify(CharSequence rawText, String uri, EnforcedAdmin admin) {
- SpannableString msg = new SpannableString(rawText);
- Annotation[] spans = msg.getSpans(0, msg.length(), Annotation.class);
- SpannableStringBuilder builder = new SpannableStringBuilder(msg);
- for (Annotation annotation : spans) {
- final String key = annotation.getValue();
- int start = msg.getSpanStart(annotation);
- int end = msg.getSpanEnd(annotation);
- LearnMoreSpan link = null;
- if (ANNOTATION_URL.equals(key)) {
- link = new LearnMoreSpan(uri);
- } else if (ANNOTATION_ADMIN_DETAILS.equals(key)) {
- link = new LearnMoreSpan(admin);
- }
- if (link != null) {
- builder.setSpan(link, start, end, msg.getSpanFlags(link));
- }
- }
- return builder;
- }
- }
-
+ /**
+ * @deprecated in favor of new SecuritySettings.
+ */
+ @Deprecated
public static Preference getFingerprintPreferenceForUser(Context context, final int userId) {
final FingerprintManager fpm = Utils.getFingerprintManagerOrNull(context);
if (fpm == null || !fpm.isHardwareDetected()) {
diff --git a/src/com/android/settings/fingerprint/FingerprintStatusPreferenceController.java b/src/com/android/settings/fingerprint/FingerprintStatusPreferenceController.java
new file mode 100644
index 0000000..19eb4bb
--- /dev/null
+++ b/src/com/android/settings/fingerprint/FingerprintStatusPreferenceController.java
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 2018 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.fingerprint;
+
+import android.content.Context;
+import android.content.Intent;
+import android.hardware.fingerprint.Fingerprint;
+import android.hardware.fingerprint.FingerprintManager;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.support.v7.preference.Preference;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.R;
+import com.android.settings.Utils;
+import com.android.settings.core.BasePreferenceController;
+import com.android.settings.overlay.FeatureFactory;
+
+import java.util.List;
+
+public class FingerprintStatusPreferenceController extends BasePreferenceController {
+
+ private static final String KEY_FINGERPRINT_SETTINGS = "fingerprint_settings";
+
+ protected final FingerprintManager mFingerprintManager;
+ protected final UserManager mUm;
+ protected final LockPatternUtils mLockPatternUtils;
+
+ protected final int mUserId = UserHandle.myUserId();
+ protected final int mProfileChallengeUserId;
+
+ public FingerprintStatusPreferenceController(Context context) {
+ this(context, KEY_FINGERPRINT_SETTINGS);
+ }
+
+ public FingerprintStatusPreferenceController(Context context, String key) {
+ super(context, key);
+ mFingerprintManager = Utils.getFingerprintManagerOrNull(context);
+ mUm = (UserManager) context.getSystemService(Context.USER_SERVICE);
+ mLockPatternUtils = FeatureFactory.getFactory(context)
+ .getSecurityFeatureProvider()
+ .getLockPatternUtils(context);
+ mProfileChallengeUserId = Utils.getManagedProfileId(mUm, mUserId);
+ }
+
+ @Override
+ public int getAvailabilityStatus() {
+ if (mFingerprintManager == null || !mFingerprintManager.isHardwareDetected()) {
+ return DISABLED_UNSUPPORTED;
+ }
+ if (isUserSupported()) {
+ return AVAILABLE;
+ } else {
+ return DISABLED_FOR_USER;
+ }
+ }
+
+ @Override
+ public void updateState(Preference preference) {
+ if (!isAvailable()) {
+ if (preference != null) {
+ preference.setVisible(false);
+ }
+ return;
+ } else {
+ preference.setVisible(true);
+ }
+ final int userId = getUserId();
+ final List<Fingerprint> items = mFingerprintManager.getEnrolledFingerprints(userId);
+ final int fingerprintCount = items != null ? items.size() : 0;
+ final String clazz;
+ if (fingerprintCount > 0) {
+ preference.setSummary(mContext.getResources().getQuantityString(
+ R.plurals.security_settings_fingerprint_preference_summary,
+ fingerprintCount, fingerprintCount));
+ clazz = FingerprintSettings.class.getName();
+ } else {
+ preference.setSummary(
+ R.string.security_settings_fingerprint_preference_summary_none);
+ clazz = FingerprintEnrollIntroduction.class.getName();
+ }
+ preference.setOnPreferenceClickListener(target -> {
+ final Context context = target.getContext();
+ final UserManager userManager = UserManager.get(context);
+ if (Utils.startQuietModeDialogIfNecessary(context, userManager,
+ userId)) {
+ return false;
+ }
+ Intent intent = new Intent();
+ intent.setClassName("com.android.settings", clazz);
+ intent.putExtra(Intent.EXTRA_USER_ID, userId);
+ context.startActivity(intent);
+ return true;
+ });
+ }
+
+ protected int getUserId() {
+ return mUserId;
+ }
+
+ protected boolean isUserSupported() {
+ return true;
+ }
+}
diff --git a/src/com/android/settings/fuelgauge/PowerUsageSummary.java b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
index a5b6c08..0315f03 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageSummary.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
@@ -84,10 +84,6 @@
private static final String KEY_SCREEN_USAGE = "screen_usage";
private static final String KEY_TIME_SINCE_LAST_FULL_CHARGE = "last_full_charge";
-
- private static final String KEY_AUTO_BRIGHTNESS = "auto_brightness_battery";
- private static final String KEY_SCREEN_TIMEOUT = "screen_timeout_battery";
- private static final String KEY_AMBIENT_DISPLAY = "ambient_display_battery";
private static final String KEY_BATTERY_SAVER_SUMMARY = "battery_saver_summary";
@VisibleForTesting
@@ -272,14 +268,9 @@
mBatteryTipPreferenceController = new BatteryTipPreferenceController(context,
KEY_BATTERY_TIP, this);
controllers.add(mBatteryTipPreferenceController);
- controllers.add(new AutoBrightnessPreferenceController(context, KEY_AUTO_BRIGHTNESS));
- controllers.add(new TimeoutPreferenceController(context, KEY_SCREEN_TIMEOUT));
controllers.add(new BatterySaverController(context, getLifecycle()));
controllers.add(new BatteryPercentagePreferenceController(context));
- controllers.add(new AmbientDisplayPreferenceController(
- context,
- new AmbientDisplayConfiguration(context),
- KEY_AMBIENT_DISPLAY));
+
return controllers;
}
@@ -544,10 +535,6 @@
public List<String> getNonIndexableKeys(Context context) {
List<String> niks = super.getNonIndexableKeys(context);
niks.add(KEY_BATTERY_SAVER_SUMMARY);
- // Duplicates in display
- niks.add(KEY_AUTO_BRIGHTNESS);
- niks.add(KEY_SCREEN_TIMEOUT);
- niks.add(KEY_AMBIENT_DISPLAY);
return niks;
}
};
diff --git a/src/com/android/settings/gestures/GesturesSettingPreferenceController.java b/src/com/android/settings/gestures/GesturesSettingPreferenceController.java
index 819b128..8b2fcc0 100644
--- a/src/com/android/settings/gestures/GesturesSettingPreferenceController.java
+++ b/src/com/android/settings/gestures/GesturesSettingPreferenceController.java
@@ -24,7 +24,6 @@
import com.android.internal.hardware.AmbientDisplayConfiguration;
import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
-import com.android.settings.core.PreferenceControllerMixin;
import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.core.AbstractPreferenceController;
@@ -58,25 +57,28 @@
@Override
public void updateState(Preference preference) {
+ preference.setSummary(getSummary());
+ }
+
+ @Override
+ public String getSummary() {
if (!mFeatureProvider.isSensorAvailable(mContext)) {
- preference.setSummary("");
- return;
+ return "";
}
final ContentResolver contentResolver = mContext.getContentResolver();
final boolean assistGestureEnabled = Settings.Secure.getInt(
contentResolver, Settings.Secure.ASSIST_GESTURE_ENABLED, 1) != 0;
final boolean assistGestureSilenceEnabled = Settings.Secure.getInt(
contentResolver, Settings.Secure.ASSIST_GESTURE_SILENCE_ALERTS_ENABLED, 1) != 0;
- final String summary;
+
if (mFeatureProvider.isSupported(mContext) && assistGestureEnabled) {
- summary = mContext.getString(
+ return mContext.getString(
R.string.language_input_gesture_summary_on_with_assist);
- } else if (assistGestureSilenceEnabled) {
- summary = mContext.getString(
- R.string.language_input_gesture_summary_on_non_assist);
- } else {
- summary = mContext.getString(R.string.language_input_gesture_summary_off);
}
- preference.setSummary(summary);
+ if (assistGestureSilenceEnabled) {
+ return mContext.getString(
+ R.string.language_input_gesture_summary_on_non_assist);
+ }
+ return mContext.getString(R.string.language_input_gesture_summary_off);
}
}
\ No newline at end of file
diff --git a/src/com/android/settings/network/PrivateDnsModeDialogFragment.java b/src/com/android/settings/network/PrivateDnsModeDialogFragment.java
index 5704fb9..8b7ccce 100644
--- a/src/com/android/settings/network/PrivateDnsModeDialogFragment.java
+++ b/src/com/android/settings/network/PrivateDnsModeDialogFragment.java
@@ -22,22 +22,30 @@
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.FragmentManager;
+import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
+import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.VisibleForTesting;
import android.text.Editable;
import android.text.TextWatcher;
+import android.text.method.LinkMovementMethod;
+import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
+import android.widget.TextView;
+import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.R;
import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
+import com.android.settings.utils.AnnotationSpan;
+import com.android.settingslib.HelpUtils;
import java.util.HashMap;
import java.util.Map;
@@ -48,6 +56,8 @@
public class PrivateDnsModeDialogFragment extends InstrumentedDialogFragment implements
DialogInterface.OnClickListener, RadioGroup.OnCheckedChangeListener, TextWatcher {
+ public static final String ANNOTATION_URL = "url";
+
private static final String TAG = "PrivateDnsModeDialogFragment";
// DNS_MODE -> RadioButton id
private static final Map<String, Integer> PRIVATE_DNS_MAP;
@@ -73,6 +83,21 @@
@VisibleForTesting
String mMode;
+ private final AnnotationSpan.LinkInfo mUrlLinkInfo = new AnnotationSpan.LinkInfo(
+ ANNOTATION_URL, (widget) -> {
+ final Context context = widget.getContext();
+ final Intent intent = HelpUtils.getHelpIntent(context,
+ getString(R.string.help_uri_private_dns),
+ context.getClass().getName());
+ if (intent != null) {
+ try {
+ widget.startActivityForResult(intent, 0);
+ } catch (ActivityNotFoundException e) {
+ Log.w(TAG, "Activity was not found for intent, " + intent.toString());
+ }
+ }
+ });
+
public static void show(FragmentManager fragmentManager) {
if (fragmentManager.findFragmentByTag(TAG) == null) {
final PrivateDnsModeDialogFragment fragment = new PrivateDnsModeDialogFragment();
@@ -112,25 +137,30 @@
mRadioGroup.setOnCheckedChangeListener(this);
mRadioGroup.check(PRIVATE_DNS_MAP.getOrDefault(mMode, R.id.private_dns_mode_opportunistic));
+ final TextView helpTextView = view.findViewById(R.id.private_dns_help_info);
+ helpTextView.setMovementMethod(LinkMovementMethod.getInstance());
+ helpTextView.setText(AnnotationSpan.linkify(
+ context.getText(R.string.private_dns_help_message), mUrlLinkInfo));
+
return view;
}
@Override
public void onClick(DialogInterface dialog, int which) {
- //TODO(b/34953048): add metric action
if (mMode.equals(PRIVATE_DNS_MODE_PROVIDER_HOSTNAME)) {
// Only clickable if hostname is valid, so we could save it safely
Settings.Global.putString(getContext().getContentResolver(), HOSTNAME_KEY,
mEditText.getText().toString());
}
+ mMetricsFeatureProvider.action(getContext(),
+ MetricsProto.MetricsEvent.ACTION_PRIVATE_DNS_MODE, mMode);
Settings.Global.putString(getContext().getContentResolver(), MODE_KEY, mMode);
}
@Override
public int getMetricsCategory() {
- //TODO(b/68030013): add metric id
- return 0;
+ return MetricsProto.MetricsEvent.DIALOG_PRIVATE_DNS;
}
@Override
diff --git a/src/com/android/settings/notification/AppNotificationSettings.java b/src/com/android/settings/notification/AppNotificationSettings.java
index af168d6..ef0f40b 100644
--- a/src/com/android/settings/notification/AppNotificationSettings.java
+++ b/src/com/android/settings/notification/AppNotificationSettings.java
@@ -135,7 +135,6 @@
return new ArrayList<>(mControllers);
}
-
private void populateList() {
if (!mDynamicPreferences.isEmpty()) {
// If there's anything in mChannelGroups, we've called populateChannelList twice.
@@ -164,61 +163,41 @@
}
private void populateGroupList() {
- PreferenceCategory groupCategory = new PreferenceCategory(getPrefContext());
- groupCategory.setTitle(R.string.notification_channels);
- groupCategory.setKey(KEY_GENERAL_CATEGORY);
- groupCategory.setOrderingAsAdded(true);
- getPreferenceScreen().addPreference(groupCategory);
- mDynamicPreferences.add(groupCategory);
for (NotificationChannelGroup group : mChannelGroupList) {
- final List<NotificationChannel> channels = group.getChannels();
- int N = channels.size();
- // app defined groups with one channel and channels with no group display the channel
- // name and no summary and link directly to the channel page unless the group is blocked
- if ((group.getId() == null || N < 2) && !group.isBlocked()) {
- Collections.sort(channels, mChannelComparator);
- for (int i = 0; i < N; i++) {
- final NotificationChannel channel = channels.get(i);
- populateSingleChannelPrefs(groupCategory, channel, "");
- }
+ PreferenceCategory groupCategory = new PreferenceCategory(getPrefContext());
+ groupCategory.setOrderingAsAdded(true);
+ getPreferenceScreen().addPreference(groupCategory);
+ mDynamicPreferences.add(groupCategory);
+ if (group.getId() == null) {
+ groupCategory.setTitle(mChannelGroupList.size() > 1
+ ? R.string.notification_channels_other
+ : R.string.notification_channels);
+ groupCategory.setKey(KEY_GENERAL_CATEGORY);
} else {
- populateGroupPreference(groupCategory, group, N);
+ groupCategory.setTitle(group.getName());
+ groupCategory.setKey(group.getId());
+ Bundle groupArgs = new Bundle();
+ groupArgs.putInt(AppInfoBase.ARG_PACKAGE_UID, mUid);
+ groupArgs.putString(AppInfoBase.ARG_PACKAGE_NAME, mPkg);
+ groupArgs.putString(Settings.EXTRA_CHANNEL_GROUP_ID, group.getId());
+ Intent channelIntent = Utils.onBuildStartFragmentIntent(getActivity(),
+ ChannelGroupNotificationSettings.class.getName(),
+ groupArgs, null, R.string.notification_group_title,
+ null, false, getMetricsCategory());
+ groupCategory.setIntent(channelIntent);
+ populateGroupToggle(groupCategory, group);
+ }
+
+ final List<NotificationChannel> channels = group.getChannels();
+ Collections.sort(channels, mChannelComparator);
+ int N = channels.size();
+ for (int i = 0; i < N; i++) {
+ final NotificationChannel channel = channels.get(i);
+ populateSingleChannelPrefs(groupCategory, channel, group.isBlocked());
}
}
}
- void populateGroupPreference(PreferenceGroup parent,
- final NotificationChannelGroup group, int channelCount) {
- MasterSwitchPreference groupPref = new MasterSwitchPreference(
- getPrefContext());
- groupPref.setSwitchEnabled(mSuspendedAppsAdmin == null
- && isChannelGroupBlockable(group));
- groupPref.setKey(group.getId());
- groupPref.setTitle(group.getName());
- groupPref.setChecked(!group.isBlocked());
- groupPref.setSummary(getResources().getQuantityString(
- R.plurals.notification_group_summary, channelCount, channelCount));
- Bundle groupArgs = new Bundle();
- groupArgs.putInt(AppInfoBase.ARG_PACKAGE_UID, mUid);
- groupArgs.putString(AppInfoBase.ARG_PACKAGE_NAME, mPkg);
- groupArgs.putString(Settings.EXTRA_CHANNEL_GROUP_ID, group.getId());
- Intent groupIntent = Utils.onBuildStartFragmentIntent(getActivity(),
- ChannelGroupNotificationSettings.class.getName(),
- groupArgs, null, R.string.notification_group_title, null, false,
- getMetricsCategory());
- groupPref.setIntent(groupIntent);
-
- groupPref.setOnPreferenceChangeListener(
- (preference, o) -> {
- boolean value = (Boolean) o;
- group.setBlocked(!value);
- mBackend.updateChannelGroup(mPkg, mUid, group);
-
- return true;
- });
- parent.addPreference(groupPref);
- }
-
private Comparator<NotificationChannelGroup> mChannelGroupComparator =
new Comparator<NotificationChannelGroup>() {
diff --git a/src/com/android/settings/notification/BlockPreferenceController.java b/src/com/android/settings/notification/BlockPreferenceController.java
index 5c366ea..6b65b0f 100644
--- a/src/com/android/settings/notification/BlockPreferenceController.java
+++ b/src/com/android/settings/notification/BlockPreferenceController.java
@@ -67,6 +67,8 @@
LayoutPreference pref = (LayoutPreference) preference;
SwitchBar bar = pref.findViewById(R.id.switch_bar);
if (bar != null) {
+ bar.setSwitchBarText(R.string.notification_switch_label,
+ R.string.notification_switch_label);
bar.show();
try {
bar.addOnSwitchChangeListener(this);
diff --git a/src/com/android/settings/notification/ChannelGroupNotificationSettings.java b/src/com/android/settings/notification/ChannelGroupNotificationSettings.java
index 68dd91b..707a559 100644
--- a/src/com/android/settings/notification/ChannelGroupNotificationSettings.java
+++ b/src/com/android/settings/notification/ChannelGroupNotificationSettings.java
@@ -19,7 +19,6 @@
import android.app.NotificationChannel;
import android.content.Context;
import android.support.v7.preference.Preference;
-import android.text.TextUtils;
import android.util.Log;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
@@ -98,9 +97,7 @@
Collections.sort(channels, mChannelComparator);
for (NotificationChannel channel : channels) {
mDynamicPreferences.add(populateSingleChannelPrefs(
- getPreferenceScreen(), channel,
- ImportancePreferenceController.getImportanceSummary(
- getPrefContext(), channel)));
+ getPreferenceScreen(), channel, mChannelGroup.isBlocked()));
}
}
diff --git a/src/com/android/settings/notification/HeaderPreferenceController.java b/src/com/android/settings/notification/HeaderPreferenceController.java
index 3d51b25..5ec60c2 100644
--- a/src/com/android/settings/notification/HeaderPreferenceController.java
+++ b/src/com/android/settings/notification/HeaderPreferenceController.java
@@ -77,7 +77,8 @@
: mAppRow.label;
}
- CharSequence getSummary() {
+ @Override
+ public String getSummary() {
if (mChannel != null) {
if (mChannelGroup != null && mChannelGroup.getGroup() != null
&& !TextUtils.isEmpty(mChannelGroup.getGroup().getName())) {
@@ -87,12 +88,12 @@
summary.append(bidi.unicodeWrap(mContext.getText(
R.string.notification_header_divider_symbol_with_spaces)));
summary.append(bidi.unicodeWrap(mChannelGroup.getGroup().getName().toString()));
- return summary;
+ return summary.toString();
} else {
- return mAppRow.label;
+ return mAppRow.label.toString();
}
} else if (mChannelGroup != null && mChannelGroup.getGroup() != null) {
- return mAppRow.label;
+ return mAppRow.label.toString();
} else {
return "";
}
diff --git a/src/com/android/settings/notification/ImportancePreferenceController.java b/src/com/android/settings/notification/ImportancePreferenceController.java
index ba47c54..977cd9a 100644
--- a/src/com/android/settings/notification/ImportancePreferenceController.java
+++ b/src/com/android/settings/notification/ImportancePreferenceController.java
@@ -73,7 +73,8 @@
if (preference.isEnabled()) {
Intent channelIntent = Utils.onBuildStartFragmentIntent(mContext,
ChannelImportanceSettings.class.getName(),
- channelArgs, null, R.string.notification_importance_title, null,
+ channelArgs, null,
+ R.string.notification_importance_title, null,
false, getMetricsCategory());
preference.setIntent(channelIntent);
preference.setSummary(getImportanceSummary(mContext, mChannel));
@@ -82,23 +83,19 @@
}
protected static String getImportanceSummary(Context context, NotificationChannel channel) {
- String title;
- String summary = null;
+ String summary = "";
int importance = channel.getImportance();
switch (importance) {
case IMPORTANCE_UNSPECIFIED:
- title = context.getString(R.string.notification_importance_unspecified);
+ summary = context.getString(R.string.notification_importance_unspecified);
break;
case NotificationManager.IMPORTANCE_MIN:
- title = context.getString(R.string.notification_importance_min_title);
summary = context.getString(R.string.notification_importance_min);
break;
case NotificationManager.IMPORTANCE_LOW:
- title = context.getString(R.string.notification_importance_low_title);
summary = context.getString(R.string.notification_importance_low);
break;
case NotificationManager.IMPORTANCE_DEFAULT:
- title = context.getString(R.string.notification_importance_default_title);
if (SoundPreferenceController.hasValidSound(channel)) {
summary = context.getString(R.string.notification_importance_default);
} else {
@@ -107,7 +104,6 @@
break;
case NotificationManager.IMPORTANCE_HIGH:
case NotificationManager.IMPORTANCE_MAX:
- title = context.getString(R.string.notification_importance_high_title);
if (SoundPreferenceController.hasValidSound(channel)) {
summary = context.getString(R.string.notification_importance_high);
} else {
@@ -118,10 +114,6 @@
return "";
}
- if (summary != null) {
- return context.getString(R.string.notification_importance_divider, title, summary);
- } else {
- return title;
- }
+ return summary;
}
}
diff --git a/src/com/android/settings/notification/LockScreenNotificationPreferenceController.java b/src/com/android/settings/notification/LockScreenNotificationPreferenceController.java
index dd7b0fb..d56febb 100644
--- a/src/com/android/settings/notification/LockScreenNotificationPreferenceController.java
+++ b/src/com/android/settings/notification/LockScreenNotificationPreferenceController.java
@@ -36,6 +36,7 @@
import com.android.settings.R;
import com.android.settings.Utils;
import com.android.settings.core.PreferenceControllerMixin;
+import com.android.settings.overlay.FeatureFactory;
import com.android.settingslib.RestrictedLockUtils;
import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.core.lifecycle.LifecycleObserver;
@@ -78,7 +79,9 @@
mProfileChallengeUserId = Utils.getManagedProfileId(
UserManager.get(context), UserHandle.myUserId());
- final LockPatternUtils utils = new LockPatternUtils(context);
+ final LockPatternUtils utils = FeatureFactory.getFactory(context)
+ .getSecurityFeatureProvider()
+ .getLockPatternUtils(context);
mSecure = utils.isSecure(UserHandle.myUserId());
mSecureProfile = (mProfileChallengeUserId != UserHandle.USER_NULL)
&& (utils.isSecure(mProfileChallengeUserId)
@@ -278,10 +281,14 @@
}
}
- public int getSummaryResource() {
- final boolean enabled = getLockscreenNotificationsEnabled(UserHandle.myUserId());
- final boolean allowPrivate = !mSecure
- || getLockscreenAllowPrivateNotifications(UserHandle.myUserId());
+ public static int getSummaryResource(Context context) {
+ final boolean enabled = getLockscreenNotificationsEnabled(context, UserHandle.myUserId());
+ final boolean secure = FeatureFactory.getFactory(context)
+ .getSecurityFeatureProvider()
+ .getLockPatternUtils(context)
+ .isSecure(UserHandle.myUserId());
+ final boolean allowPrivate = !secure
+ || getLockscreenAllowPrivateNotifications(context, UserHandle.myUserId());
return !enabled ? R.string.lock_screen_notifications_summary_disable :
allowPrivate ? R.string.lock_screen_notifications_summary_show :
R.string.lock_screen_notifications_summary_hide;
@@ -291,7 +298,7 @@
if (mLockscreen == null) {
return;
}
- mLockscreenSelectedValue = getSummaryResource();
+ mLockscreenSelectedValue = getSummaryResource(mContext);
mLockscreen.setSummary("%s");
mLockscreen.setValue(Integer.toString(mLockscreenSelectedValue));
}
@@ -303,9 +310,9 @@
if (mLockscreenProfile == null) {
return;
}
- final boolean enabled = getLockscreenNotificationsEnabled(mProfileChallengeUserId);
+ final boolean enabled = getLockscreenNotificationsEnabled(mContext,mProfileChallengeUserId);
final boolean allowPrivate = !mSecureProfile
- || getLockscreenAllowPrivateNotifications(mProfileChallengeUserId);
+ || getLockscreenAllowPrivateNotifications(mContext, mProfileChallengeUserId);
mLockscreenProfile.setSummary("%s");
mLockscreenSelectedValueProfile = !enabled
? R.string.lock_screen_notifications_summary_disable_profile
@@ -314,13 +321,13 @@
mLockscreenProfile.setValue(Integer.toString(mLockscreenSelectedValueProfile));
}
- private boolean getLockscreenNotificationsEnabled(int userId) {
- return Settings.Secure.getIntForUser(mContext.getContentResolver(),
+ private static boolean getLockscreenNotificationsEnabled(Context context, int userId) {
+ return Settings.Secure.getIntForUser(context.getContentResolver(),
Settings.Secure.LOCK_SCREEN_SHOW_NOTIFICATIONS, 0, userId) != 0;
}
- private boolean getLockscreenAllowPrivateNotifications(int userId) {
- return Settings.Secure.getIntForUser(mContext.getContentResolver(),
+ private static boolean getLockscreenAllowPrivateNotifications(Context context, int userId) {
+ return Settings.Secure.getIntForUser(context.getContentResolver(),
Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, 0, userId) != 0;
}
diff --git a/src/com/android/settings/notification/NotificationSettingsBase.java b/src/com/android/settings/notification/NotificationSettingsBase.java
index 9afb618..2a7e7d5 100644
--- a/src/com/android/settings/notification/NotificationSettingsBase.java
+++ b/src/com/android/settings/notification/NotificationSettingsBase.java
@@ -61,6 +61,7 @@
import android.provider.SearchIndexableResource;
import android.provider.Settings;
import android.service.notification.NotificationListenerService;
+import android.support.v14.preference.SwitchPreference;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceGroup;
import android.support.v7.preference.PreferenceScreen;
@@ -214,7 +215,6 @@
}
for (ResolveInfo ri : resolveInfos) {
final ActivityInfo activityInfo = ri.activityInfo;
- final ApplicationInfo appInfo = activityInfo.applicationInfo;
if (mAppRow.settingsIntent != null) {
if (DEBUG) {
Log.d(TAG, "Ignoring duplicate notification preference activity ("
@@ -225,7 +225,8 @@
}
mAppRow.settingsIntent = intent
.setPackage(null)
- .setClassName(activityInfo.packageName, activityInfo.name);
+ .setClassName(activityInfo.packageName, activityInfo.name)
+ .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (mChannel != null) {
mAppRow.settingsIntent.putExtra(Notification.EXTRA_CHANNEL_ID, mChannel.getId());
}
@@ -257,17 +258,41 @@
return null;
}
+ protected void populateGroupToggle(final PreferenceGroup parent,
+ NotificationChannelGroup group) {
+ RestrictedSwitchPreference preference = new RestrictedSwitchPreference(getPrefContext());
+ preference.setTitle(R.string.notification_switch_label);
+ preference.setEnabled(mSuspendedAppsAdmin == null
+ && isChannelGroupBlockable(group));
+ preference.setChecked(!group.isBlocked());
+ preference.setOnPreferenceClickListener(preference1 -> {
+ final boolean allowGroup = ((SwitchPreference) preference1).isChecked();
+ group.setBlocked(!allowGroup);
+ mBackend.updateChannelGroup(mAppRow.pkg, mAppRow.uid, group);
+
+ for (int i = 0; i < parent.getPreferenceCount(); i++) {
+ Preference pref = parent.getPreference(i);
+ if (pref instanceof MasterSwitchPreference) {
+ ((MasterSwitchPreference) pref).setSwitchEnabled(allowGroup);
+ }
+ }
+ return true;
+ });
+
+ parent.addPreference(preference);
+ }
+
protected Preference populateSingleChannelPrefs(PreferenceGroup parent,
- final NotificationChannel channel, String summary) {
+ final NotificationChannel channel, final boolean groupBlocked) {
MasterSwitchPreference channelPref = new MasterSwitchPreference(
getPrefContext());
channelPref.setSwitchEnabled(mSuspendedAppsAdmin == null
&& isChannelBlockable(channel)
- && isChannelConfigurable(channel));
+ && isChannelConfigurable(channel)
+ && !groupBlocked);
channelPref.setKey(channel.getId());
channelPref.setTitle(channel.getName());
channelPref.setChecked(channel.getImportance() != IMPORTANCE_NONE);
- channelPref.setSummary(summary);
Bundle channelArgs = new Bundle();
channelArgs.putInt(AppInfoBase.ARG_PACKAGE_UID, mUid);
channelArgs.putString(AppInfoBase.ARG_PACKAGE_NAME, mPkg);
@@ -288,7 +313,6 @@
channel.setImportance(importance);
channel.lockFields(
NotificationChannel.USER_LOCKED_IMPORTANCE);
- channelPref.setSummary(summary);
mBackend.updateChannel(mPkg, mUid, channel);
return true;
diff --git a/src/com/android/settings/password/ChooseLockPassword.java b/src/com/android/settings/password/ChooseLockPassword.java
index 4e54f3c..11efec3 100644
--- a/src/com/android/settings/password/ChooseLockPassword.java
+++ b/src/com/android/settings/password/ChooseLockPassword.java
@@ -210,7 +210,7 @@
private String mFirstPin;
private RecyclerView mPasswordRestrictionView;
protected boolean mIsAlphaMode;
- protected Button mCancelButton;
+ protected Button mSkipButton;
private Button mClearButton;
private Button mNextButton;
private TextView mMessage;
@@ -377,8 +377,8 @@
ViewGroup container = view.findViewById(R.id.password_container);
container.setOpticalInsets(Insets.NONE);
- mCancelButton = (Button) view.findViewById(R.id.cancel_button);
- mCancelButton.setOnClickListener(this);
+ mSkipButton = (Button) view.findViewById(R.id.skip_button);
+ mSkipButton.setOnClickListener(this);
mNextButton = (Button) view.findViewById(R.id.next_button);
mNextButton.setOnClickListener(this);
mClearButton = view.findViewById(R.id.clear_button);
@@ -774,10 +774,6 @@
handleNext();
break;
- case R.id.cancel_button:
- getActivity().finish();
- break;
-
case R.id.clear_button:
mPasswordEntry.setText("");
break;
@@ -901,7 +897,6 @@
}
mClearButton.setVisibility(toVisibility(mUiStage != Stage.Introduction));
- mCancelButton.setVisibility(toVisibility(mUiStage == Stage.Introduction));
setNextText(mUiStage.buttonText);
mPasswordEntryInputDisabler.setInputEnabled(canInput);
diff --git a/src/com/android/settings/password/ChooseLockPattern.java b/src/com/android/settings/password/ChooseLockPattern.java
index 7cd9db8..746a977 100644
--- a/src/com/android/settings/password/ChooseLockPattern.java
+++ b/src/com/android/settings/password/ChooseLockPattern.java
@@ -290,8 +290,6 @@
* The states of the left footer button.
*/
enum LeftButtonMode {
- Cancel(R.string.cancel, true),
- CancelDisabled(R.string.cancel, false),
Retry(R.string.lockpattern_retry_button_text, true),
RetryDisabled(R.string.lockpattern_retry_button_text, false),
Gone(ID_EMPTY_MESSAGE, false);
@@ -342,7 +340,7 @@
R.string.lock_settings_picker_fingerprint_added_security_message,
R.string.lockpassword_choose_your_pattern_message,
R.string.lockpattern_recording_intro_header,
- LeftButtonMode.Cancel, RightButtonMode.ContinueDisabled,
+ LeftButtonMode.Gone, RightButtonMode.ContinueDisabled,
ID_EMPTY_MESSAGE, true),
HelpScreen(
ID_EMPTY_MESSAGE, ID_EMPTY_MESSAGE, R.string.lockpattern_settings_help_how_to_record,
@@ -360,15 +358,15 @@
LeftButtonMode.Retry, RightButtonMode.Continue, ID_EMPTY_MESSAGE, false),
NeedToConfirm(
ID_EMPTY_MESSAGE, ID_EMPTY_MESSAGE, R.string.lockpattern_need_to_confirm,
- LeftButtonMode.Cancel, RightButtonMode.ConfirmDisabled,
+ LeftButtonMode.Gone, RightButtonMode.ConfirmDisabled,
ID_EMPTY_MESSAGE, true),
ConfirmWrong(
ID_EMPTY_MESSAGE, ID_EMPTY_MESSAGE, R.string.lockpattern_need_to_unlock_wrong,
- LeftButtonMode.Cancel, RightButtonMode.ConfirmDisabled,
+ LeftButtonMode.Gone, RightButtonMode.ConfirmDisabled,
ID_EMPTY_MESSAGE, true),
ChoiceConfirmed(
ID_EMPTY_MESSAGE, ID_EMPTY_MESSAGE, R.string.lockpattern_pattern_confirmed_header,
- LeftButtonMode.Cancel, RightButtonMode.Confirm, ID_EMPTY_MESSAGE, false);
+ LeftButtonMode.Gone, RightButtonMode.Confirm, ID_EMPTY_MESSAGE, false);
/**
@@ -413,7 +411,7 @@
private ChooseLockSettingsHelper mChooseLockSettingsHelper;
private SaveAndFinishWorker mSaveAndFinishWorker;
- private int mUserId;
+ protected int mUserId;
private boolean mForFingerprint;
private static final String KEY_UI_STAGE = "uiStage";
@@ -558,8 +556,6 @@
mChosenPattern = null;
mLockPatternView.clearPattern();
updateStage(Stage.Introduction);
- } else if (mUiStage.leftMode == LeftButtonMode.Cancel) {
- getActivity().finish();
} else {
throw new IllegalStateException("left footer button pressed, but stage of " +
mUiStage + " doesn't make sense");
diff --git a/src/com/android/settings/password/ChooseLockSettingsHelper.java b/src/com/android/settings/password/ChooseLockSettingsHelper.java
index 806ee67..11d40a3 100644
--- a/src/com/android/settings/password/ChooseLockSettingsHelper.java
+++ b/src/com/android/settings/password/ChooseLockSettingsHelper.java
@@ -23,6 +23,7 @@
import android.app.admin.DevicePolicyManager;
import android.content.Intent;
import android.content.IntentSender;
+import android.os.Bundle;
import android.os.UserManager;
import com.android.internal.annotations.VisibleForTesting;
@@ -42,6 +43,12 @@
public static final String EXTRA_KEY_FOR_FINGERPRINT = "for_fingerprint";
public static final String EXTRA_KEY_FOR_CHANGE_CRED_REQUIRED_FOR_BOOT = "for_cred_req_boot";
+ /**
+ * When invoked via {@link ConfirmLockPassword.InternalActivity}, this flag
+ * controls if we relax the enforcement of
+ * {@link Utils#enforceSameOwner(android.content.Context, int)}.
+ */
+ public static final String EXTRA_ALLOW_ANY_USER = "allow_any_user";
@VisibleForTesting LockPatternUtils mLockPatternUtils;
private Activity mActivity;
@@ -200,25 +207,47 @@
external, true, challenge, Utils.enforceSameOwner(mActivity, userId));
}
+ /**
+ * Variant that allows you to prompt for credentials of any user, including
+ * those which aren't associated with the current user. As an example, this
+ * is useful when unlocking the storage for secondary users.
+ */
+ public boolean launchConfirmationActivityForAnyUser(int request,
+ @Nullable CharSequence title, @Nullable CharSequence header,
+ @Nullable CharSequence description, int userId) {
+ final Bundle extras = new Bundle();
+ extras.putBoolean(EXTRA_ALLOW_ANY_USER, true);
+ return launchConfirmationActivity(request, title, header, description, false,
+ false, true, 0, userId, extras);
+ }
+
private boolean launchConfirmationActivity(int request, @Nullable CharSequence title,
@Nullable CharSequence header, @Nullable CharSequence description,
boolean returnCredentials, boolean external, boolean hasChallenge,
long challenge, int userId) {
return launchConfirmationActivity(request, title, header, description, returnCredentials,
- external, hasChallenge, challenge, userId, null /* alternateButton */);
+ external, hasChallenge, challenge, userId, null /* alternateButton */, null);
+ }
+
+ private boolean launchConfirmationActivity(int request, @Nullable CharSequence title,
+ @Nullable CharSequence header, @Nullable CharSequence description,
+ boolean returnCredentials, boolean external, boolean hasChallenge,
+ long challenge, int userId, Bundle extras) {
+ return launchConfirmationActivity(request, title, header, description, returnCredentials,
+ external, hasChallenge, challenge, userId, null /* alternateButton */, extras);
}
public boolean launchFrpConfirmationActivity(int request, @Nullable CharSequence header,
@Nullable CharSequence description, @Nullable CharSequence alternateButton) {
return launchConfirmationActivity(request, null /* title */, header, description,
false /* returnCredentials */, true /* external */, false /* hasChallenge */,
- 0 /* challenge */, LockPatternUtils.USER_FRP, alternateButton);
+ 0 /* challenge */, LockPatternUtils.USER_FRP, alternateButton, null);
}
private boolean launchConfirmationActivity(int request, @Nullable CharSequence title,
@Nullable CharSequence header, @Nullable CharSequence description,
boolean returnCredentials, boolean external, boolean hasChallenge,
- long challenge, int userId, @Nullable CharSequence alternateButton) {
+ long challenge, int userId, @Nullable CharSequence alternateButton, Bundle extras) {
final int effectiveUserId = UserManager.get(mActivity).getCredentialOwnerProfile(userId);
boolean launched = false;
@@ -228,7 +257,7 @@
returnCredentials || hasChallenge
? ConfirmLockPattern.InternalActivity.class
: ConfirmLockPattern.class, returnCredentials, external,
- hasChallenge, challenge, userId, alternateButton);
+ hasChallenge, challenge, userId, alternateButton, extras);
break;
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
@@ -240,7 +269,7 @@
returnCredentials || hasChallenge
? ConfirmLockPassword.InternalActivity.class
: ConfirmLockPassword.class, returnCredentials, external,
- hasChallenge, challenge, userId, alternateButton);
+ hasChallenge, challenge, userId, alternateButton, extras);
break;
}
return launched;
@@ -249,7 +278,7 @@
private boolean launchConfirmationActivity(int request, CharSequence title, CharSequence header,
CharSequence message, Class<?> activityClass, boolean returnCredentials,
boolean external, boolean hasChallenge, long challenge,
- int userId, @Nullable CharSequence alternateButton) {
+ int userId, @Nullable CharSequence alternateButton, Bundle extras) {
final boolean frp = (userId == LockPatternUtils.USER_FRP);
final Intent intent = new Intent();
intent.putExtra(ConfirmDeviceCredentialBaseFragment.TITLE_TEXT, title);
@@ -266,6 +295,9 @@
intent.putExtra(SettingsActivity.EXTRA_HIDE_DRAWER, true);
intent.putExtra(Intent.EXTRA_USER_ID, userId);
intent.putExtra(KeyguardManager.EXTRA_ALTERNATE_BUTTON_LABEL, alternateButton);
+ if (extras != null) {
+ intent.putExtras(extras);
+ }
intent.setClassName(ConfirmDeviceCredentialBaseFragment.PACKAGE, activityClass.getName());
if (external) {
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
diff --git a/src/com/android/settings/password/ChooseLockTypeDialogFragment.java b/src/com/android/settings/password/ChooseLockTypeDialogFragment.java
index 13dc996..6a66ffb 100644
--- a/src/com/android/settings/password/ChooseLockTypeDialogFragment.java
+++ b/src/com/android/settings/password/ChooseLockTypeDialogFragment.java
@@ -16,6 +16,7 @@
package com.android.settings.password;
+import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
@@ -24,6 +25,7 @@
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
+import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
@@ -33,8 +35,11 @@
import android.widget.TextView;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.internal.widget.LockPatternUtils;
import com.android.settings.R;
import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
+import com.android.settings.password.ChooseLockGeneric.ChooseLockGenericFragment;
+import com.android.setupwizardlib.util.WizardManagerHelper;
import java.util.List;
@@ -60,6 +65,36 @@
public interface OnLockTypeSelectedListener {
void onLockTypeSelected(ScreenLockType lock);
+
+ default void startChooseLockActivity(ScreenLockType selectedLockType, Activity activity) {
+ Intent activityIntent = activity.getIntent();
+ Intent intent = new Intent(activity, SetupChooseLockGeneric.class);
+ intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
+
+ // Copy the original extras into the new intent
+ if (activityIntent.hasExtra(
+ ChooseLockGenericFragment.EXTRA_CHOOSE_LOCK_GENERIC_EXTRAS)) {
+ intent.putExtras(activityIntent.getBundleExtra(
+ ChooseLockGenericFragment.EXTRA_CHOOSE_LOCK_GENERIC_EXTRAS));
+ }
+ intent.putExtra(LockPatternUtils.PASSWORD_TYPE_KEY, selectedLockType.defaultQuality);
+
+ // Propagate the fingerprint challenge
+ intent.putExtra(ChooseLockSettingsHelper.EXTRA_KEY_HAS_CHALLENGE,
+ activityIntent.getBooleanExtra(
+ ChooseLockSettingsHelper.EXTRA_KEY_HAS_CHALLENGE, false));
+ intent.putExtra(ChooseLockSettingsHelper.EXTRA_KEY_CHALLENGE,
+ activityIntent.getLongExtra(ChooseLockSettingsHelper.EXTRA_KEY_CHALLENGE, 0));
+
+ // The user is already given the choice of the what screen lock to set up. No need to
+ // show this button again.
+ intent.putExtra(ChooseLockGenericFragment.EXTRA_SHOW_OPTIONS_BUTTON, false);
+
+ WizardManagerHelper.copyWizardManagerExtras(activityIntent, intent);
+
+ activity.startActivity(intent);
+ activity.finish();
+ }
}
@Override
diff --git a/src/com/android/settings/password/ConfirmDeviceCredentialBaseActivity.java b/src/com/android/settings/password/ConfirmDeviceCredentialBaseActivity.java
index d2bd934..ab8c3dc 100644
--- a/src/com/android/settings/password/ConfirmDeviceCredentialBaseActivity.java
+++ b/src/com/android/settings/password/ConfirmDeviceCredentialBaseActivity.java
@@ -45,10 +45,15 @@
private boolean mIsKeyguardLocked = false;
private ConfirmCredentialTheme mConfirmCredentialTheme;
+ private boolean isInternalActivity() {
+ return (this instanceof ConfirmLockPassword.InternalActivity)
+ || (this instanceof ConfirmLockPattern.InternalActivity);
+ }
+
@Override
protected void onCreate(Bundle savedState) {
int credentialOwnerUserId = Utils.getCredentialOwnerUserId(this,
- Utils.getUserIdFromBundle(this, getIntent().getExtras()));
+ Utils.getUserIdFromBundle(this, getIntent().getExtras(), isInternalActivity()));
if (UserManager.get(this).isManagedProfile(credentialOwnerUserId)) {
setTheme(R.style.Theme_ConfirmDeviceCredentialsWork);
mConfirmCredentialTheme = ConfirmCredentialTheme.WORK;
diff --git a/src/com/android/settings/password/ConfirmDeviceCredentialBaseFragment.java b/src/com/android/settings/password/ConfirmDeviceCredentialBaseFragment.java
index 350fc76..5b18925 100644
--- a/src/com/android/settings/password/ConfirmDeviceCredentialBaseFragment.java
+++ b/src/com/android/settings/password/ConfirmDeviceCredentialBaseFragment.java
@@ -94,6 +94,11 @@
protected boolean mFrp;
private CharSequence mFrpAlternateButtonText;
+ private boolean isInternalActivity() {
+ return (getActivity() instanceof ConfirmLockPassword.InternalActivity)
+ || (getActivity() instanceof ConfirmLockPattern.InternalActivity);
+ }
+
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -103,7 +108,8 @@
ChooseLockSettingsHelper.EXTRA_KEY_RETURN_CREDENTIALS, false);
// Only take this argument into account if it belongs to the current profile.
Intent intent = getActivity().getIntent();
- mUserId = Utils.getUserIdFromBundle(getActivity(), intent.getExtras());
+ mUserId = Utils.getUserIdFromBundle(getActivity(), intent.getExtras(),
+ isInternalActivity());
mFrp = (mUserId == LockPatternUtils.USER_FRP);
mUserManager = UserManager.get(getActivity());
mEffectiveUserId = mUserManager.getCredentialOwnerProfile(mUserId);
@@ -141,7 +147,7 @@
getActivity(),
Utils.getUserIdFromBundle(
getActivity(),
- getActivity().getIntent().getExtras()));
+ getActivity().getIntent().getExtras(), isInternalActivity()));
if (mUserManager.isManagedProfile(credentialOwnerUserId)) {
setWorkChallengeBackground(view, credentialOwnerUserId);
}
diff --git a/src/com/android/settings/password/SetupChooseLockPassword.java b/src/com/android/settings/password/SetupChooseLockPassword.java
index 79cfef3..5c70736 100644
--- a/src/com/android/settings/password/SetupChooseLockPassword.java
+++ b/src/com/android/settings/password/SetupChooseLockPassword.java
@@ -28,13 +28,9 @@
import android.widget.Button;
import android.widget.LinearLayout;
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.widget.LockPatternUtils;
import com.android.settings.R;
import com.android.settings.SetupRedactionInterstitial;
-import com.android.settings.password.ChooseLockGeneric.ChooseLockGenericFragment;
import com.android.settings.password.ChooseLockTypeDialogFragment.OnLockTypeSelectedListener;
-import com.android.setupwizardlib.util.WizardManagerHelper;
/**
* Setup Wizard's version of ChooseLockPassword screen. It inherits the logic and basic structure
@@ -75,9 +71,6 @@
public static class SetupChooseLockPasswordFragment extends ChooseLockPasswordFragment
implements OnLockTypeSelectedListener {
- @VisibleForTesting
- static final int REQUEST_SCREEN_LOCK_OPTIONS = 1;
-
@Nullable
private Button mOptionsButton;
@@ -90,8 +83,7 @@
boolean anyOptionsShown = chooseLockGenericController.getVisibleScreenLockTypes(
DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, false).size() > 0;
boolean showOptionsButton = activity.getIntent().getBooleanExtra(
- ChooseLockGenericFragment.EXTRA_SHOW_OPTIONS_BUTTON, false);
-
+ ChooseLockGeneric.ChooseLockGenericFragment.EXTRA_SHOW_OPTIONS_BUTTON, false);
if (!anyOptionsShown) {
Log.w(TAG, "Visible screen lock types is empty!");
}
@@ -107,9 +99,10 @@
public void onClick(View v) {
switch (v.getId()) {
case R.id.screen_lock_options:
- launchChooseLockGeneric();
+ ChooseLockTypeDialogFragment.newInstance(mUserId)
+ .show(getChildFragmentManager(), null);
break;
- case R.id.cancel_button:
+ case R.id.skip_button:
SetupSkipDialog dialog = SetupSkipDialog.newInstance(
getActivity().getIntent()
.getBooleanExtra(SetupSkipDialog.EXTRA_FRP_SUPPORTED, false));
@@ -120,11 +113,6 @@
}
}
- private void launchChooseLockGeneric() {
- ChooseLockTypeDialogFragment.newInstance(mUserId)
- .show(getChildFragmentManager(), null);
- }
-
@Override
protected Intent getRedactionInterstitialIntent(Context context) {
// Setup wizard's redaction interstitial is deferred to optional step. Enable that
@@ -137,57 +125,16 @@
public void onLockTypeSelected(ScreenLockType lock) {
ScreenLockType currentLockType = mIsAlphaMode ?
ScreenLockType.PASSWORD : ScreenLockType.PIN;
- if (currentLockType.equals(lock)) {
- // ignore same lock type.
+ if (lock == currentLockType) {
return;
}
- Intent activityIntent = getActivity().getIntent();
- Intent intent = new Intent(getContext(), SetupChooseLockGeneric.class);
-
- // Copy the original extras into the new intent
- if (activityIntent
- .hasExtra(ChooseLockGenericFragment.EXTRA_CHOOSE_LOCK_GENERIC_EXTRAS)) {
- intent.putExtras(activityIntent.getBundleExtra(
- ChooseLockGenericFragment.EXTRA_CHOOSE_LOCK_GENERIC_EXTRAS));
- }
- intent.putExtra(LockPatternUtils.PASSWORD_TYPE_KEY, lock.defaultQuality);
-
- // Propagate the fingerprint challenge
- intent.putExtra(ChooseLockSettingsHelper.EXTRA_KEY_HAS_CHALLENGE,
- activityIntent.getBooleanExtra(ChooseLockSettingsHelper.EXTRA_KEY_HAS_CHALLENGE,
- false));
- intent.putExtra(ChooseLockSettingsHelper.EXTRA_KEY_CHALLENGE,
- activityIntent.getLongExtra(ChooseLockSettingsHelper.EXTRA_KEY_CHALLENGE, 0));
-
- // The user is already given the choice of the what screen lock to set up. No need to
- // show this button again.
- intent.putExtra(ChooseLockGenericFragment.EXTRA_SHOW_OPTIONS_BUTTON, false);
-
- WizardManagerHelper.copyWizardManagerExtras(activityIntent, intent);
-
- startActivityForResult(intent, REQUEST_SCREEN_LOCK_OPTIONS);
- }
-
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if (requestCode == REQUEST_SCREEN_LOCK_OPTIONS) {
- if (resultCode != Activity.RESULT_CANCELED) {
- Activity activity = getActivity();
- activity.setResult(resultCode, data);
- activity.finish();
- }
- }
+ startChooseLockActivity(lock, getActivity());
}
@Override
protected void updateUi() {
super.updateUi();
- if (mForFingerprint) {
- mCancelButton.setVisibility(View.GONE);
- } else {
- mCancelButton.setText(R.string.skip_label);
- }
+ mSkipButton.setVisibility(mForFingerprint ? View.GONE : View.VISIBLE);
if (mOptionsButton != null) {
mOptionsButton.setVisibility(
diff --git a/src/com/android/settings/password/SetupChooseLockPattern.java b/src/com/android/settings/password/SetupChooseLockPattern.java
index b1e3d0d..b1c9fac 100644
--- a/src/com/android/settings/password/SetupChooseLockPattern.java
+++ b/src/com/android/settings/password/SetupChooseLockPattern.java
@@ -19,7 +19,11 @@
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
+import android.os.Bundle;
+import android.view.View;
+import android.widget.Button;
+import com.android.settings.R;
import com.android.settings.SetupRedactionInterstitial;
/**
@@ -46,7 +50,26 @@
return SetupChooseLockPatternFragment.class;
}
- public static class SetupChooseLockPatternFragment extends ChooseLockPatternFragment {
+ public static class SetupChooseLockPatternFragment extends ChooseLockPatternFragment
+ implements ChooseLockTypeDialogFragment.OnLockTypeSelectedListener {
+
+ @Override
+ public void onViewCreated(View view, Bundle savedInstanceState) {
+ super.onViewCreated(view, savedInstanceState);
+ Button optionsButton = (Button) view.findViewById(R.id.screen_lock_options);
+ optionsButton.setVisibility(View.VISIBLE);
+ optionsButton.setOnClickListener((btn) ->
+ ChooseLockTypeDialogFragment.newInstance(mUserId)
+ .show(getChildFragmentManager(), null));
+ }
+
+ @Override
+ public void onLockTypeSelected(ScreenLockType lock) {
+ if (ScreenLockType.PATTERN == lock) {
+ return;
+ }
+ startChooseLockActivity(lock, getActivity());
+ }
@Override
protected Intent getRedactionInterstitialIntent(Context context) {
diff --git a/src/com/android/settings/search/SearchIndexableResources.java b/src/com/android/settings/search/SearchIndexableResources.java
index c4e178f..0207c94 100644
--- a/src/com/android/settings/search/SearchIndexableResources.java
+++ b/src/com/android/settings/search/SearchIndexableResources.java
@@ -75,7 +75,7 @@
import com.android.settings.security.EncryptionAndCredential;
import com.android.settings.security.LockscreenDashboardFragment;
import com.android.settings.security.ScreenPinningSettings;
-import com.android.settings.security.SecuritySettings;
+import com.android.settings.security.SecuritySettingsV2;
import com.android.settings.security.screenlock.ScreenLockSettings;
import com.android.settings.sim.SimSettings;
import com.android.settings.support.SupportDashboardActivity;
@@ -135,7 +135,7 @@
addIndex(LocationSettings.class);
addIndex(LocationMode.class);
addIndex(ScanningSettings.class);
- addIndex(SecuritySettings.class);
+ addIndex(SecuritySettingsV2.class);
addIndex(ScreenLockSettings.class);
addIndex(EncryptionAndCredential.class);
addIndex(ScreenPinningSettings.class);
@@ -179,5 +179,7 @@
private SearchIndexableResources() {
}
- public static Collection<Class> providerValues() { return sProviders;}
+ public static Collection<Class> providerValues() {
+ return sProviders;
+ }
}
\ No newline at end of file
diff --git a/src/com/android/settings/security/ChangeProfileScreenLockPreferenceController.java b/src/com/android/settings/security/ChangeProfileScreenLockPreferenceController.java
new file mode 100644
index 0000000..9a33ec3
--- /dev/null
+++ b/src/com/android/settings/security/ChangeProfileScreenLockPreferenceController.java
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+import static com.android.settings.security
+ .SecuritySettingsV2.SET_OR_CHANGE_LOCK_METHOD_REQUEST_PROFILE;
+
+import android.app.admin.DevicePolicyManager;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.UserHandle;
+import android.support.v7.preference.Preference;
+import android.text.TextUtils;
+
+import com.android.settings.R;
+import com.android.settings.Utils;
+import com.android.settings.password.ChooseLockGeneric;
+
+public class ChangeProfileScreenLockPreferenceController extends
+ ChangeScreenLockPreferenceController {
+
+ private static final String KEY_UNLOCK_SET_OR_CHANGE_PROFILE = "unlock_set_or_change_profile";
+
+ public ChangeProfileScreenLockPreferenceController(Context context,
+ SecuritySettingsV2 host) {
+ super(context, host);
+ }
+
+ public boolean isAvailable() {
+ if (mProfileChallengeUserId == UserHandle.USER_NULL ||
+ !mLockPatternUtils.isSeparateProfileChallengeAllowed(mProfileChallengeUserId)) {
+ return false;
+ }
+ if (!mLockPatternUtils.isSecure(mProfileChallengeUserId)) {
+ return true;
+ }
+ switch (mLockPatternUtils.getKeyguardStoredPasswordQuality(mProfileChallengeUserId)) {
+ case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
+ case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
+ case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
+ case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
+ case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
+ case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
+ case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public String getPreferenceKey() {
+ return KEY_UNLOCK_SET_OR_CHANGE_PROFILE;
+ }
+
+ @Override
+ public boolean handlePreferenceTreeClick(Preference preference) {
+ if (!TextUtils.equals(preference.getKey(), getPreferenceKey())) {
+ return false;
+ }
+ if (Utils.startQuietModeDialogIfNecessary(mContext, mUm, mProfileChallengeUserId)) {
+ return false;
+ }
+ final Bundle extras = new Bundle();
+ extras.putInt(Intent.EXTRA_USER_ID, mProfileChallengeUserId);
+ mHost.startFragment(mHost, ChooseLockGeneric.ChooseLockGenericFragment.class.getName(),
+ R.string.lock_settings_picker_title_profile,
+ SET_OR_CHANGE_LOCK_METHOD_REQUEST_PROFILE, extras);
+ return true;
+ }
+
+ @Override
+ public void updateState(Preference preference) {
+ updateSummary(preference, mProfileChallengeUserId);
+
+ if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(mProfileChallengeUserId)) {
+ final String summary = mContext.getString(
+ R.string.lock_settings_profile_unified_summary);
+ mPreference.setSummary(summary);
+ mPreference.setEnabled(false);
+ } else {
+ // PO may disallow to change profile password, and the profile's password is
+ // separated from screen lock password. Disable profile specific "Screen lock" menu.
+ disableIfPasswordQualityManaged(mProfileChallengeUserId);
+ }
+ }
+}
diff --git a/src/com/android/settings/security/ChangeScreenLockPreferenceController.java b/src/com/android/settings/security/ChangeScreenLockPreferenceController.java
new file mode 100644
index 0000000..67b78fc
--- /dev/null
+++ b/src/com/android/settings/security/ChangeScreenLockPreferenceController.java
@@ -0,0 +1,176 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+import static com.android.settings.security.SecuritySettingsV2.SET_OR_CHANGE_LOCK_METHOD_REQUEST;
+
+import android.app.admin.DevicePolicyManager;
+import android.content.Context;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.os.storage.StorageManager;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+import android.text.TextUtils;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.R;
+import com.android.settings.Utils;
+import com.android.settings.core.PreferenceControllerMixin;
+import com.android.settings.overlay.FeatureFactory;
+import com.android.settings.password.ChooseLockGeneric;
+import com.android.settings.security.screenlock.ScreenLockSettings;
+import com.android.settings.widget.GearPreference;
+import com.android.settingslib.RestrictedLockUtils;
+import com.android.settingslib.RestrictedPreference;
+import com.android.settingslib.core.AbstractPreferenceController;
+
+public class ChangeScreenLockPreferenceController extends AbstractPreferenceController implements
+ PreferenceControllerMixin, GearPreference.OnGearClickListener {
+
+ private static final String KEY_UNLOCK_SET_OR_CHANGE = "unlock_set_or_change";
+
+ protected final DevicePolicyManager mDPM;
+ protected final SecuritySettingsV2 mHost;
+ protected final UserManager mUm;
+ protected final LockPatternUtils mLockPatternUtils;
+
+ protected final int mUserId = UserHandle.myUserId();
+ protected final int mProfileChallengeUserId;
+
+ protected RestrictedPreference mPreference;
+
+ public ChangeScreenLockPreferenceController(Context context, SecuritySettingsV2 host) {
+ super(context);
+ mUm = (UserManager) context.getSystemService(Context.USER_SERVICE);
+ mDPM = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
+ mLockPatternUtils = FeatureFactory.getFactory(context)
+ .getSecurityFeatureProvider()
+ .getLockPatternUtils(context);
+ mHost = host;
+ mProfileChallengeUserId = Utils.getManagedProfileId(mUm, mUserId);
+ }
+
+ @Override
+ public boolean isAvailable() {
+ return true;
+ }
+
+ @Override
+ public String getPreferenceKey() {
+ return KEY_UNLOCK_SET_OR_CHANGE;
+ }
+
+ @Override
+ public void displayPreference(PreferenceScreen screen) {
+ super.displayPreference(screen);
+ mPreference = (RestrictedPreference) screen.findPreference(getPreferenceKey());
+ }
+
+ @Override
+ public void updateState(Preference preference) {
+ if (mPreference != null && mPreference instanceof GearPreference) {
+ if (mLockPatternUtils.isSecure(mUserId)
+ || !mLockPatternUtils.isLockScreenDisabled(mUserId)) {
+ ((GearPreference) mPreference).setOnGearClickListener(this);
+ } else {
+ ((GearPreference) mPreference).setOnGearClickListener(null);
+ }
+ }
+
+ updateSummary(preference, mUserId);
+ disableIfPasswordQualityManaged(mUserId);
+ if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(mProfileChallengeUserId)) {
+ // PO may disallow to change password for the profile, but screen lock and managed
+ // profile's lock is the same. Disable main "Screen lock" menu.
+ disableIfPasswordQualityManaged(mProfileChallengeUserId);
+ }
+ }
+
+ @Override
+ public void onGearClick(GearPreference p) {
+ if (TextUtils.equals(p.getKey(), getPreferenceKey())) {
+ mHost.startFragment(mHost, ScreenLockSettings.class.getName(), 0, 0, null);
+ }
+ }
+
+ @Override
+ public boolean handlePreferenceTreeClick(Preference preference) {
+ if (!TextUtils.equals(preference.getKey(), getPreferenceKey())) {
+ return super.handlePreferenceTreeClick(preference);
+ }
+ // TODO(b/35930129): Remove once existing password can be passed into vold directly.
+ // Currently we need this logic to ensure that the QUIET_MODE is off for any work
+ // profile with unified challenge on FBE-enabled devices. Otherwise, vold would not be
+ // able to complete the operation due to the lack of (old) encryption key.
+ if (mProfileChallengeUserId != UserHandle.USER_NULL
+ && !mLockPatternUtils.isSeparateProfileChallengeEnabled(mProfileChallengeUserId)
+ && StorageManager.isFileEncryptedNativeOnly()) {
+ if (Utils.startQuietModeDialogIfNecessary(mContext, mUm, mProfileChallengeUserId)) {
+ return false;
+ }
+ }
+ mHost.startFragment(mHost, ChooseLockGeneric.ChooseLockGenericFragment.class.getName(),
+ R.string.lock_settings_picker_title, SET_OR_CHANGE_LOCK_METHOD_REQUEST, null);
+ return true;
+ }
+
+ protected void updateSummary(Preference preference, int userId) {
+ if (!mLockPatternUtils.isSecure(userId)) {
+ if (userId == mProfileChallengeUserId
+ || mLockPatternUtils.isLockScreenDisabled(userId)) {
+ preference.setSummary(R.string.unlock_set_unlock_mode_off);
+ } else {
+ preference.setSummary(R.string.unlock_set_unlock_mode_none);
+ }
+ } else {
+ switch (mLockPatternUtils.getKeyguardStoredPasswordQuality(userId)) {
+ case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
+ preference.setSummary(R.string.unlock_set_unlock_mode_pattern);
+ break;
+ case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
+ case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
+ preference.setSummary(R.string.unlock_set_unlock_mode_pin);
+ break;
+ case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
+ case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
+ case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
+ case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
+ preference.setSummary(R.string.unlock_set_unlock_mode_password);
+ break;
+ }
+ }
+ mPreference.setEnabled(true);
+ }
+
+ /**
+ * Sets the preference as disabled by admin if PASSWORD_QUALITY_MANAGED is set.
+ * The preference must be a RestrictedPreference.
+ * <p/>
+ * DO or PO installed in the user may disallow to change password.
+ */
+ void disableIfPasswordQualityManaged(int userId) {
+ final RestrictedLockUtils.EnforcedAdmin admin = RestrictedLockUtils
+ .checkIfPasswordQualityIsSet(mContext, userId);
+ final DevicePolicyManager dpm = (DevicePolicyManager) mContext
+ .getSystemService(Context.DEVICE_POLICY_SERVICE);
+ if (admin != null && dpm.getPasswordQuality(admin.component, userId)
+ == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
+ mPreference.setDisabledByAdmin(admin);
+ }
+ }
+}
diff --git a/src/com/android/settings/security/EncryptionAndCredential.java b/src/com/android/settings/security/EncryptionAndCredential.java
index 62f5a0c..627cf3e 100644
--- a/src/com/android/settings/security/EncryptionAndCredential.java
+++ b/src/com/android/settings/security/EncryptionAndCredential.java
@@ -16,6 +16,9 @@
package com.android.settings.security;
+import static com.android.settings.security.EncryptionStatusPreferenceController
+ .PREF_KEY_ENCRYPTION_DETAIL_PAGE;
+
import android.content.Context;
import android.os.UserManager;
import android.provider.SearchIndexableResource;
@@ -63,7 +66,8 @@
Lifecycle lifecycle) {
final List<AbstractPreferenceController> controllers = new ArrayList<>();
final EncryptionStatusPreferenceController encryptStatusController =
- new EncryptionStatusPreferenceController(context);
+ new EncryptionStatusPreferenceController(context,
+ PREF_KEY_ENCRYPTION_DETAIL_PAGE);
controllers.add(encryptStatusController);
controllers.add(new PreferenceCategoryController(context,
"encryption_and_credentials_status_category",
diff --git a/src/com/android/settings/security/EncryptionStatusPreferenceController.java b/src/com/android/settings/security/EncryptionStatusPreferenceController.java
index 7d84421..0978935 100644
--- a/src/com/android/settings/security/EncryptionStatusPreferenceController.java
+++ b/src/com/android/settings/security/EncryptionStatusPreferenceController.java
@@ -19,43 +19,45 @@
import android.content.Context;
import android.os.UserManager;
import android.support.v7.preference.Preference;
+import android.text.TextUtils;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.R;
-import com.android.settings.core.PreferenceControllerMixin;
-import com.android.settingslib.core.AbstractPreferenceController;
+import com.android.settings.core.BasePreferenceController;
-public class EncryptionStatusPreferenceController extends AbstractPreferenceController
- implements PreferenceControllerMixin {
+public class EncryptionStatusPreferenceController extends BasePreferenceController {
- private static final String PREF_KEY = "encryption_and_credentials_encryption_status";
+
+ static final String PREF_KEY_ENCRYPTION_DETAIL_PAGE =
+ "encryption_and_credentials_encryption_status";
+ static final String PREF_KEY_ENCRYPTION_SECURITY_PAGE = "encryption_and_credential";
private final UserManager mUserManager;
- public EncryptionStatusPreferenceController(Context context) {
- super(context);
+ public EncryptionStatusPreferenceController(Context context, String key) {
+ super(context, key);
mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
}
@Override
- public boolean isAvailable() {
- return mUserManager.isAdminUser();
- }
-
- @Override
- public String getPreferenceKey() {
- return PREF_KEY;
+ public int getAvailabilityStatus() {
+ return mUserManager.isAdminUser() ? AVAILABLE : DISABLED_FOR_USER;
}
@Override
public void updateState(Preference preference) {
final boolean encryptionEnabled = LockPatternUtils.isDeviceEncryptionEnabled();
if (encryptionEnabled) {
- preference.setFragment(null);
+ if (TextUtils.equals(getPreferenceKey(), PREF_KEY_ENCRYPTION_DETAIL_PAGE)) {
+ preference.setFragment(null);
+ }
preference.setSummary(R.string.crypt_keeper_encrypted_summary);
} else {
- preference.setFragment(CryptKeeperSettings.class.getName());
+ if (TextUtils.equals(getPreferenceKey(), PREF_KEY_ENCRYPTION_DETAIL_PAGE)) {
+ preference.setFragment(CryptKeeperSettings.class.getName());
+ }
preference.setSummary(R.string.summary_placeholder);
}
+
}
}
diff --git a/src/com/android/settings/security/LockUnificationPreferenceController.java b/src/com/android/settings/security/LockUnificationPreferenceController.java
new file mode 100644
index 0000000..5486e29
--- /dev/null
+++ b/src/com/android/settings/security/LockUnificationPreferenceController.java
@@ -0,0 +1,218 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+import static com.android.settings.security
+ .SecuritySettingsV2.SET_OR_CHANGE_LOCK_METHOD_REQUEST_PROFILE;
+import static com.android.settings.security.SecuritySettingsV2.UNIFY_LOCK_CONFIRM_DEVICE_REQUEST;
+import static com.android.settings.security.SecuritySettingsV2.UNIFY_LOCK_CONFIRM_PROFILE_REQUEST;
+import static com.android.settings.security.SecuritySettingsV2.UNUNIFY_LOCK_CONFIRM_DEVICE_REQUEST;
+
+import android.app.Activity;
+import android.app.admin.DevicePolicyManager;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.R;
+import com.android.settings.Utils;
+import com.android.settings.core.PreferenceControllerMixin;
+import com.android.settings.overlay.FeatureFactory;
+import com.android.settings.password.ChooseLockGeneric;
+import com.android.settings.password.ChooseLockSettingsHelper;
+import com.android.settingslib.RestrictedLockUtils;
+import com.android.settingslib.RestrictedSwitchPreference;
+import com.android.settingslib.core.AbstractPreferenceController;
+
+public class LockUnificationPreferenceController extends AbstractPreferenceController
+ implements PreferenceControllerMixin, Preference.OnPreferenceChangeListener {
+
+ private static final String KEY_UNIFICATION = "unification";
+
+ private static final int MY_USER_ID = UserHandle.myUserId();
+
+ private final UserManager mUm;
+ private final LockPatternUtils mLockPatternUtils;
+ private final int mProfileChallengeUserId;
+ private final SecuritySettingsV2 mHost;
+
+ private RestrictedSwitchPreference mUnifyProfile;
+
+
+ private String mCurrentDevicePassword;
+ private String mCurrentProfilePassword;
+
+ @Override
+ public void displayPreference(PreferenceScreen screen) {
+ super.displayPreference(screen);
+ mUnifyProfile = (RestrictedSwitchPreference) screen.findPreference(KEY_UNIFICATION);
+ }
+
+ public LockUnificationPreferenceController(Context context, SecuritySettingsV2 host) {
+ super(context);
+ mHost = host;
+ mUm = (UserManager) context.getSystemService(Context.USER_SERVICE);
+ mLockPatternUtils = FeatureFactory.getFactory(context)
+ .getSecurityFeatureProvider()
+ .getLockPatternUtils(context);
+ mProfileChallengeUserId = Utils.getManagedProfileId(mUm, MY_USER_ID);
+ }
+
+ @Override
+ public boolean isAvailable() {
+ final boolean allowSeparateProfileChallenge =
+ mProfileChallengeUserId != UserHandle.USER_NULL
+ && mLockPatternUtils.isSeparateProfileChallengeAllowed(
+ mProfileChallengeUserId);
+ return allowSeparateProfileChallenge;
+ }
+
+ @Override
+ public String getPreferenceKey() {
+ return KEY_UNIFICATION;
+ }
+
+ @Override
+ public boolean onPreferenceChange(Preference preference, Object value) {
+ if (Utils.startQuietModeDialogIfNecessary(mContext, mUm, mProfileChallengeUserId)) {
+ return false;
+ }
+ if ((Boolean) value) {
+ final boolean compliantForDevice =
+ (mLockPatternUtils.getKeyguardStoredPasswordQuality(mProfileChallengeUserId)
+ >= DevicePolicyManager.PASSWORD_QUALITY_SOMETHING
+ && mLockPatternUtils.isSeparateProfileChallengeAllowedToUnify(
+ mProfileChallengeUserId));
+ UnificationConfirmationDialog dialog =
+ UnificationConfirmationDialog.newInstance(compliantForDevice);
+ dialog.show(mHost);
+ } else {
+ final String title = mContext.getString(R.string.unlock_set_unlock_launch_picker_title);
+ final ChooseLockSettingsHelper helper =
+ new ChooseLockSettingsHelper(mHost.getActivity(), mHost);
+ if (!helper.launchConfirmationActivity(
+ UNUNIFY_LOCK_CONFIRM_DEVICE_REQUEST,
+ title, true /* returnCredentials */, MY_USER_ID)) {
+ ununifyLocks();
+ }
+ }
+ return true;
+ }
+
+ @Override
+ public void updateState(Preference preference) {
+ if (mUnifyProfile != null) {
+ final boolean separate =
+ mLockPatternUtils.isSeparateProfileChallengeEnabled(mProfileChallengeUserId);
+ mUnifyProfile.setChecked(!separate);
+ if (separate) {
+ mUnifyProfile.setDisabledByAdmin(RestrictedLockUtils.checkIfRestrictionEnforced(
+ mContext, UserManager.DISALLOW_UNIFIED_PASSWORD,
+ mProfileChallengeUserId));
+ }
+ }
+ }
+
+ public boolean handleActivityResult(int requestCode, int resultCode, Intent data) {
+ if (requestCode == UNUNIFY_LOCK_CONFIRM_DEVICE_REQUEST
+ && resultCode == Activity.RESULT_OK) {
+ ununifyLocks();
+ return true;
+ } else if (requestCode == UNIFY_LOCK_CONFIRM_DEVICE_REQUEST
+ && resultCode == Activity.RESULT_OK) {
+ mCurrentDevicePassword =
+ data.getStringExtra(ChooseLockSettingsHelper.EXTRA_KEY_PASSWORD);
+ launchConfirmProfileLockForUnification();
+ return true;
+ } else if (requestCode == UNIFY_LOCK_CONFIRM_PROFILE_REQUEST
+ && resultCode == Activity.RESULT_OK) {
+ mCurrentProfilePassword =
+ data.getStringExtra(ChooseLockSettingsHelper.EXTRA_KEY_PASSWORD);
+ unifyLocks();
+ return true;
+ }
+ return false;
+ }
+
+ private void ununifyLocks() {
+ Bundle extras = new Bundle();
+ extras.putInt(Intent.EXTRA_USER_ID, mProfileChallengeUserId);
+ mHost.startFragment(mHost,
+ ChooseLockGeneric.ChooseLockGenericFragment.class.getName(),
+ R.string.lock_settings_picker_title_profile,
+ SET_OR_CHANGE_LOCK_METHOD_REQUEST_PROFILE, extras);
+ }
+
+ void launchConfirmDeviceLockForUnification() {
+ final String title = mContext.getString(
+ R.string.unlock_set_unlock_launch_picker_title);
+ final ChooseLockSettingsHelper helper =
+ new ChooseLockSettingsHelper(mHost.getActivity(), mHost);
+ if (!helper.launchConfirmationActivity(
+ UNIFY_LOCK_CONFIRM_DEVICE_REQUEST, title, true, MY_USER_ID)) {
+ launchConfirmProfileLockForUnification();
+ }
+ }
+
+ private void launchConfirmProfileLockForUnification() {
+ final String title = mContext.getString(
+ R.string.unlock_set_unlock_launch_picker_title_profile);
+ final ChooseLockSettingsHelper helper =
+ new ChooseLockSettingsHelper(mHost.getActivity(), mHost);
+ if (!helper.launchConfirmationActivity(
+ UNIFY_LOCK_CONFIRM_PROFILE_REQUEST, title, true, mProfileChallengeUserId)) {
+ unifyLocks();
+ // TODO: update relevant prefs.
+ // createPreferenceHierarchy();
+ }
+ }
+
+ private void unifyLocks() {
+ int profileQuality =
+ mLockPatternUtils.getKeyguardStoredPasswordQuality(mProfileChallengeUserId);
+ if (profileQuality == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
+ mLockPatternUtils.saveLockPattern(
+ LockPatternUtils.stringToPattern(mCurrentProfilePassword),
+ mCurrentDevicePassword, MY_USER_ID);
+ } else {
+ mLockPatternUtils.saveLockPassword(
+ mCurrentProfilePassword, mCurrentDevicePassword,
+ profileQuality, MY_USER_ID);
+ }
+ mLockPatternUtils.setSeparateProfileChallengeEnabled(mProfileChallengeUserId, false,
+ mCurrentProfilePassword);
+ final boolean profilePatternVisibility =
+ mLockPatternUtils.isVisiblePatternEnabled(mProfileChallengeUserId);
+ mLockPatternUtils.setVisiblePatternEnabled(profilePatternVisibility, MY_USER_ID);
+ mCurrentDevicePassword = null;
+ mCurrentProfilePassword = null;
+ }
+
+ void unifyUncompliantLocks() {
+ mLockPatternUtils.setSeparateProfileChallengeEnabled(mProfileChallengeUserId, false,
+ mCurrentProfilePassword);
+ mHost.startFragment(mHost, ChooseLockGeneric.ChooseLockGenericFragment.class.getName(),
+ R.string.lock_settings_picker_title,
+ SecuritySettingsV2.SET_OR_CHANGE_LOCK_METHOD_REQUEST, null);
+ }
+
+}
diff --git a/src/com/android/settings/security/ScreenPinningPreferenceController.java b/src/com/android/settings/security/ScreenPinningPreferenceController.java
new file mode 100644
index 0000000..60279c7
--- /dev/null
+++ b/src/com/android/settings/security/ScreenPinningPreferenceController.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+import android.content.Context;
+import android.provider.Settings;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.settings.R;
+import com.android.settings.core.BasePreferenceController;
+
+public class ScreenPinningPreferenceController extends BasePreferenceController {
+
+ private static final String KEY_SCREEN_PINNING = "screen_pinning_settings";
+
+ public ScreenPinningPreferenceController(Context context) {
+ super(context, KEY_SCREEN_PINNING);
+ }
+
+ @Override
+ public int getAvailabilityStatus() {
+ return AVAILABLE;
+ }
+
+ @Override
+ public void displayPreference(PreferenceScreen screen) {
+ super.displayPreference(screen);
+ final Preference preference = screen.findPreference(getPreferenceKey());
+ if (preference == null) {
+ return;
+ }
+ if (Settings.System.getInt(mContext.getContentResolver(),
+ Settings.System.LOCK_TO_APP_ENABLED, 0) != 0) {
+ preference.setSummary(
+ mContext.getString(R.string.switch_on_text));
+ } else {
+ preference.setSummary(
+ mContext.getString(R.string.switch_off_text));
+ }
+ }
+}
diff --git a/src/com/android/settings/security/SecurityFeatureProvider.java b/src/com/android/settings/security/SecurityFeatureProvider.java
index 509446d..35ff586 100644
--- a/src/com/android/settings/security/SecurityFeatureProvider.java
+++ b/src/com/android/settings/security/SecurityFeatureProvider.java
@@ -18,7 +18,10 @@
import android.content.Context;
import android.support.v7.preference.PreferenceScreen;
+import android.util.FeatureFlagUtils;
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.core.FeatureFlags;
import com.android.settings.security.trustagent.TrustAgentManager;
import com.android.settingslib.drawer.DashboardCategory;
@@ -26,10 +29,19 @@
/** FeatureProvider for security. */
public interface SecurityFeatureProvider {
+ default boolean isSecuritySettingsV2Enabled(Context context) {
+ return FeatureFlagUtils.isEnabled(context, FeatureFlags.SECURITY_SETTINGS_V2);
+ }
+
/** Update preferences with data from associated tiles. */
void updatePreferences(Context context, PreferenceScreen preferenceScreen,
DashboardCategory dashboardCategory);
/** Returns the {@link TrustAgentManager} bound to this {@link SecurityFeatureProvider}. */
TrustAgentManager getTrustAgentManager();
+
+ /**
+ * Returns a {@link LockPatternUtils} instance bound to application context.
+ */
+ LockPatternUtils getLockPatternUtils(Context context);
}
diff --git a/src/com/android/settings/security/SecurityFeatureProviderImpl.java b/src/com/android/settings/security/SecurityFeatureProviderImpl.java
index 29aaefe..70b1ec1 100644
--- a/src/com/android/settings/security/SecurityFeatureProviderImpl.java
+++ b/src/com/android/settings/security/SecurityFeatureProviderImpl.java
@@ -29,6 +29,7 @@
import android.util.ArrayMap;
import android.util.Pair;
+import com.android.internal.widget.LockPatternUtils;
import com.android.settings.R;
import com.android.settings.security.trustagent.TrustAgentManager;
import com.android.settingslib.drawer.DashboardCategory;
@@ -43,6 +44,7 @@
public class SecurityFeatureProviderImpl implements SecurityFeatureProvider {
private TrustAgentManager mTrustAgentManager;
+ private LockPatternUtils mLockPatternUtils;
@VisibleForTesting
static final Drawable DEFAULT_ICON = null;
@@ -195,4 +197,12 @@
}
return mTrustAgentManager;
}
+
+ @Override
+ public LockPatternUtils getLockPatternUtils(Context context) {
+ if (mLockPatternUtils == null) {
+ mLockPatternUtils = new LockPatternUtils(context.getApplicationContext());
+ }
+ return mLockPatternUtils;
+ }
}
diff --git a/src/com/android/settings/security/SecuritySettings.java b/src/com/android/settings/security/SecuritySettings.java
index fc47b5c..f099b44 100644
--- a/src/com/android/settings/security/SecuritySettings.java
+++ b/src/com/android/settings/security/SecuritySettings.java
@@ -161,7 +161,6 @@
private LocationPreferenceController mLocationcontroller;
private ManageDeviceAdminPreferenceController mManageDeviceAdminPreferenceController;
private EnterprisePrivacyPreferenceController mEnterprisePrivacyPreferenceController;
- private LockScreenNotificationPreferenceController mLockScreenNotificationPreferenceController;
@Override
public int getMetricsCategory() {
@@ -208,8 +207,6 @@
= new ManageDeviceAdminPreferenceController(activity);
mEnterprisePrivacyPreferenceController
= new EnterprisePrivacyPreferenceController(activity);
- mLockScreenNotificationPreferenceController
- = new LockScreenNotificationPreferenceController(activity);
}
private static int getResIdForLockUnlockScreen(LockPatternUtils lockPatternUtils,
@@ -430,7 +427,7 @@
final Preference lockscreenPreferences = group.findPreference(KEY_LOCKSCREEN_PREFERENCES);
if (lockscreenPreferences != null) {
lockscreenPreferences.setSummary(
- mLockScreenNotificationPreferenceController.getSummaryResource());
+ LockScreenNotificationPreferenceController.getSummaryResource(getContext()));
}
}
diff --git a/src/com/android/settings/security/SecuritySettingsV2.java b/src/com/android/settings/security/SecuritySettingsV2.java
new file mode 100644
index 0000000..323c0f4
--- /dev/null
+++ b/src/com/android/settings/security/SecuritySettingsV2.java
@@ -0,0 +1,188 @@
+package com.android.settings.security;
+
+import static com.android.settings.security.EncryptionStatusPreferenceController
+ .PREF_KEY_ENCRYPTION_SECURITY_PAGE;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.hardware.fingerprint.FingerprintManager;
+import android.provider.SearchIndexableResource;
+
+import com.android.internal.logging.nano.MetricsProto;
+import com.android.settings.R;
+import com.android.settings.Utils;
+import com.android.settings.dashboard.DashboardFragment;
+import com.android.settings.dashboard.SummaryLoader;
+import com.android.settings.enterprise.EnterprisePrivacyPreferenceController;
+import com.android.settings.enterprise.ManageDeviceAdminPreferenceController;
+import com.android.settings.fingerprint.FingerprintProfileStatusPreferenceController;
+import com.android.settings.fingerprint.FingerprintStatusPreferenceController;
+import com.android.settings.location.LocationPreferenceController;
+import com.android.settings.search.BaseSearchIndexProvider;
+import com.android.settings.security.screenlock.LockScreenPreferenceController;
+import com.android.settings.security.trustagent.ManageTrustAgentsPreferenceController;
+import com.android.settings.security.trustagent.TrustAgentListPreferenceController;
+import com.android.settings.widget.PreferenceCategoryController;
+import com.android.settingslib.core.AbstractPreferenceController;
+import com.android.settingslib.core.lifecycle.Lifecycle;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class SecuritySettingsV2 extends DashboardFragment {
+
+ private static final String TAG = "SecuritySettingsV2";
+
+ public static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST = 123;
+ public static final int CHANGE_TRUST_AGENT_SETTINGS = 126;
+ public static final int SET_OR_CHANGE_LOCK_METHOD_REQUEST_PROFILE = 127;
+ public static final int UNIFY_LOCK_CONFIRM_DEVICE_REQUEST = 128;
+ public static final int UNIFY_LOCK_CONFIRM_PROFILE_REQUEST = 129;
+ public static final int UNUNIFY_LOCK_CONFIRM_DEVICE_REQUEST = 130;
+
+ @Override
+ public int getMetricsCategory() {
+ return MetricsProto.MetricsEvent.SECURITY;
+ }
+
+ @Override
+ protected int getPreferenceScreenResId() {
+ return R.xml.security_settings_v2;
+ }
+
+ @Override
+ protected String getLogTag() {
+ return TAG;
+ }
+
+ @Override
+ public int getHelpResource() {
+ return R.string.help_url_security;
+ }
+
+ @Override
+ protected List<AbstractPreferenceController> getPreferenceControllers(Context context) {
+ return buildPreferenceControllers(context, getLifecycle(), this /* host*/);
+ }
+
+ /**
+ * see confirmPatternThenDisableAndClear
+ */
+ @Override
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {
+ if (getPreferenceController(TrustAgentListPreferenceController.class)
+ .handleActivityResult(requestCode, resultCode)) {
+ return;
+ }
+ if (getPreferenceController(LockUnificationPreferenceController.class)
+ .handleActivityResult(requestCode, resultCode, data)) {
+ return;
+ }
+ super.onActivityResult(requestCode, resultCode, data);
+ }
+
+ void launchConfirmDeviceLockForUnification() {
+ getPreferenceController(LockUnificationPreferenceController.class)
+ .launchConfirmDeviceLockForUnification();
+ }
+
+ void unifyUncompliantLocks() {
+ getPreferenceController(LockUnificationPreferenceController.class).unifyUncompliantLocks();
+ }
+
+ void updateUnificationPreference() {
+ getPreferenceController(LockUnificationPreferenceController.class).updateState(null);
+ }
+
+ private static List<AbstractPreferenceController> buildPreferenceControllers(Context context,
+ Lifecycle lifecycle, SecuritySettingsV2 host) {
+ final List<AbstractPreferenceController> controllers = new ArrayList<>();
+ controllers.add(new LocationPreferenceController(context, lifecycle));
+ controllers.add(new ManageDeviceAdminPreferenceController(context));
+ controllers.add(new EnterprisePrivacyPreferenceController(context));
+ controllers.add(new ManageTrustAgentsPreferenceController(context));
+ controllers.add(new ScreenPinningPreferenceController(context));
+ controllers.add(new SimLockPreferenceController(context));
+ controllers.add(new ShowPasswordPreferenceController(context));
+ controllers.add(new FingerprintStatusPreferenceController(context));
+ controllers.add(new EncryptionStatusPreferenceController(context,
+ PREF_KEY_ENCRYPTION_SECURITY_PAGE));
+ controllers.add(new TrustAgentListPreferenceController(context, host, lifecycle));
+ controllers.add(new LockScreenPreferenceController(context, lifecycle));
+ controllers.add(new ChangeScreenLockPreferenceController(context, host));
+
+ final List<AbstractPreferenceController> profileSecurityControllers = new ArrayList<>();
+ profileSecurityControllers.add(new ChangeProfileScreenLockPreferenceController(
+ context, host));
+ profileSecurityControllers.add(new LockUnificationPreferenceController(context, host));
+ profileSecurityControllers.add(new VisiblePatternProfilePreferenceController(
+ context, lifecycle));
+ profileSecurityControllers.add(new FingerprintProfileStatusPreferenceController(context));
+ controllers.add(new PreferenceCategoryController(context, "security_category_profile",
+ profileSecurityControllers));
+ controllers.addAll(profileSecurityControllers);
+
+ return controllers;
+ }
+
+ /**
+ * For Search. Please keep it in sync when updating "createPreferenceHierarchy()"
+ */
+ public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+ new BaseSearchIndexProvider() {
+
+ @Override
+ public List<SearchIndexableResource> getXmlResourcesToIndex(
+ Context context, boolean enabled) {
+ final List<SearchIndexableResource> index = new ArrayList<>();
+ // Append the rest of the settings
+ final SearchIndexableResource sir = new SearchIndexableResource(context);
+ sir.xmlResId = R.xml.security_settings_v2;
+ index.add(sir);
+ return index;
+ }
+
+ @Override
+ public List<AbstractPreferenceController> getPreferenceControllers(Context
+ context) {
+ return buildPreferenceControllers(context, null /* lifecycle */,
+ null /* host*/);
+ }
+ };
+
+ static class SummaryProvider implements SummaryLoader.SummaryProvider {
+
+ private final Context mContext;
+ private final SummaryLoader mSummaryLoader;
+
+ public SummaryProvider(Context context, SummaryLoader summaryLoader) {
+ mContext = context;
+ mSummaryLoader = summaryLoader;
+ }
+
+ @Override
+ public void setListening(boolean listening) {
+ if (listening) {
+ final FingerprintManager fpm =
+ Utils.getFingerprintManagerOrNull(mContext);
+ if (fpm != null && fpm.isHardwareDetected()) {
+ mSummaryLoader.setSummary(this,
+ mContext.getString(R.string.security_dashboard_summary));
+ } else {
+ mSummaryLoader.setSummary(this, mContext.getString(
+ R.string.security_dashboard_summary_no_fingerprint));
+ }
+ }
+ }
+ }
+
+ public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY =
+ new SummaryLoader.SummaryProviderFactory() {
+ @Override
+ public SummaryLoader.SummaryProvider createSummaryProvider(Activity activity,
+ SummaryLoader summaryLoader) {
+ return new SummaryProvider(activity, summaryLoader);
+ }
+ };
+}
diff --git a/src/com/android/settings/security/ShowPasswordPreferenceController.java b/src/com/android/settings/security/ShowPasswordPreferenceController.java
new file mode 100644
index 0000000..d0216e8
--- /dev/null
+++ b/src/com/android/settings/security/ShowPasswordPreferenceController.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+import android.content.Context;
+import android.os.UserHandle;
+import android.provider.Settings;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.core.TogglePreferenceController;
+import com.android.settings.overlay.FeatureFactory;
+
+public class ShowPasswordPreferenceController extends TogglePreferenceController {
+
+ private static final String KEY_SHOW_PASSWORD = "show_password";
+ private static final int MY_USER_ID = UserHandle.myUserId();
+ private final LockPatternUtils mLockPatternUtils;
+
+ public ShowPasswordPreferenceController(Context context) {
+ super(context, KEY_SHOW_PASSWORD);
+ mLockPatternUtils = FeatureFactory.getFactory(context)
+ .getSecurityFeatureProvider()
+ .getLockPatternUtils(context);
+ }
+
+ @Override
+ public boolean isChecked() {
+ return Settings.System.getInt(mContext.getContentResolver(),
+ Settings.System.TEXT_SHOW_PASSWORD, 1) != 0;
+ }
+
+ @Override
+ public boolean setChecked(boolean isChecked) {
+ Settings.System.putInt(mContext.getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,
+ isChecked ? 1 : 0);
+ mLockPatternUtils.setVisiblePasswordEnabled(isChecked, MY_USER_ID);
+ return true;
+ }
+
+ @Override
+ public int getAvailabilityStatus() {
+ return AVAILABLE;
+ }
+}
+
diff --git a/src/com/android/settings/security/SimLockPreferenceController.java b/src/com/android/settings/security/SimLockPreferenceController.java
new file mode 100644
index 0000000..797f098
--- /dev/null
+++ b/src/com/android/settings/security/SimLockPreferenceController.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+import android.content.Context;
+import android.os.PersistableBundle;
+import android.os.UserManager;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionInfo;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
+
+import com.android.settings.core.BasePreferenceController;
+
+import java.util.List;
+
+public class SimLockPreferenceController extends BasePreferenceController {
+
+ private static final String KEY_SIM_LOCK = "sim_lock_settings";
+
+ private final CarrierConfigManager mCarrierConfigManager;
+ private final UserManager mUserManager;
+ private final SubscriptionManager mSubscriptionManager;
+ private final TelephonyManager mTelephonyManager;
+
+ public SimLockPreferenceController(Context context) {
+ super(context, KEY_SIM_LOCK);
+ mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
+ mCarrierConfigManager = (CarrierConfigManager)
+ mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
+ mSubscriptionManager = (SubscriptionManager) context
+ .getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
+ mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
+ }
+
+ @Override
+ public int getAvailabilityStatus() {
+ final PersistableBundle b = mCarrierConfigManager.getConfig();
+ final boolean IsAdmin = mUserManager.isAdminUser();
+ if (!IsAdmin || !isSimIccReady() ||
+ b.getBoolean(CarrierConfigManager.KEY_HIDE_SIM_LOCK_SETTINGS_BOOL)) {
+ return DISABLED_FOR_USER;
+ }
+ return AVAILABLE;
+ }
+
+ @Override
+ public void displayPreference(PreferenceScreen screen) {
+ super.displayPreference(screen);
+ final Preference preference = screen.findPreference(getPreferenceKey());
+ if (preference == null) {
+ return;
+ }
+ // Disable SIM lock if there is no ready SIM card.
+ preference.setEnabled(isSimReady());
+ }
+
+ /* Return true if a SIM is ready for locking.
+ * TODO: consider adding to TelephonyManager or SubscritpionManasger.
+ */
+ private boolean isSimReady() {
+ final List<SubscriptionInfo> subInfoList =
+ mSubscriptionManager.getActiveSubscriptionInfoList();
+ if (subInfoList != null) {
+ for (SubscriptionInfo subInfo : subInfoList) {
+ final int simState = mTelephonyManager.getSimState(subInfo.getSimSlotIndex());
+ if ((simState != TelephonyManager.SIM_STATE_ABSENT) &&
+ (simState != TelephonyManager.SIM_STATE_UNKNOWN)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Return true if a there is a Slot that has Icc
+ */
+ private boolean isSimIccReady() {
+ final List<SubscriptionInfo> subInfoList =
+ mSubscriptionManager.getActiveSubscriptionInfoList();
+
+ if (subInfoList != null) {
+ for (SubscriptionInfo subInfo : subInfoList) {
+ if (mTelephonyManager.hasIccCard(subInfo.getSimSlotIndex())) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+}
diff --git a/src/com/android/settings/security/UnificationConfirmationDialog.java b/src/com/android/settings/security/UnificationConfirmationDialog.java
new file mode 100644
index 0000000..482e268
--- /dev/null
+++ b/src/com/android/settings/security/UnificationConfirmationDialog.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.FragmentManager;
+import android.content.DialogInterface;
+import android.os.Bundle;
+
+import com.android.internal.logging.nano.MetricsProto;
+import com.android.settings.R;
+import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
+
+public class UnificationConfirmationDialog extends InstrumentedDialogFragment {
+
+ static final String TAG_UNIFICATION_DIALOG = "unification_dialog";
+ private static final String EXTRA_COMPLIANT = "compliant";
+
+ public static UnificationConfirmationDialog newInstance(boolean compliant) {
+ UnificationConfirmationDialog
+ dialog = new UnificationConfirmationDialog();
+ Bundle args = new Bundle();
+ args.putBoolean(EXTRA_COMPLIANT, compliant);
+ dialog.setArguments(args);
+ return dialog;
+ }
+
+ public void show(SecuritySettingsV2 host) {
+ final FragmentManager manager = host.getChildFragmentManager();
+ if (manager.findFragmentByTag(TAG_UNIFICATION_DIALOG) == null) {
+ // Prevent opening multiple dialogs if tapped on button quickly
+ show(manager, TAG_UNIFICATION_DIALOG);
+ }
+ }
+
+ @Override
+ public Dialog onCreateDialog(Bundle savedInstanceState) {
+ final SecuritySettingsV2 parentFragment = ((SecuritySettingsV2) getParentFragment());
+ final boolean compliant = getArguments().getBoolean(EXTRA_COMPLIANT);
+ return new AlertDialog.Builder(getActivity())
+ .setTitle(R.string.lock_settings_profile_unification_dialog_title)
+ .setMessage(compliant ? R.string.lock_settings_profile_unification_dialog_body
+ : R.string.lock_settings_profile_unification_dialog_uncompliant_body)
+ .setPositiveButton(
+ compliant ? R.string.lock_settings_profile_unification_dialog_confirm
+ : R.string
+ .lock_settings_profile_unification_dialog_uncompliant_confirm,
+ (dialog, whichButton) -> {
+ if (compliant) {
+ parentFragment.launchConfirmDeviceLockForUnification();
+ } else {
+ parentFragment.unifyUncompliantLocks();
+ }
+ }
+ )
+ .setNegativeButton(R.string.cancel, null)
+ .create();
+ }
+
+ @Override
+ public void onDismiss(DialogInterface dialog) {
+ super.onDismiss(dialog);
+ ((SecuritySettingsV2) getParentFragment()).updateUnificationPreference();
+ }
+
+ @Override
+ public int getMetricsCategory() {
+ return MetricsProto.MetricsEvent.DIALOG_UNIFICATION_CONFIRMATION;
+ }
+}
diff --git a/src/com/android/settings/security/VisiblePatternProfilePreferenceController.java b/src/com/android/settings/security/VisiblePatternProfilePreferenceController.java
new file mode 100644
index 0000000..a9e56f4
--- /dev/null
+++ b/src/com/android/settings/security/VisiblePatternProfilePreferenceController.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
+
+import android.content.Context;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.Utils;
+import com.android.settings.core.TogglePreferenceController;
+import com.android.settings.overlay.FeatureFactory;
+import com.android.settingslib.core.lifecycle.Lifecycle;
+import com.android.settingslib.core.lifecycle.LifecycleObserver;
+import com.android.settingslib.core.lifecycle.events.OnResume;
+
+public class VisiblePatternProfilePreferenceController extends TogglePreferenceController
+ implements LifecycleObserver, OnResume {
+
+ private static final String KEY_VISIBLE_PATTERN_PROFILE = "visiblepattern_profile";
+
+ private final LockPatternUtils mLockPatternUtils;
+ private final UserManager mUm;
+ private final int mUserId = UserHandle.myUserId();
+ private final int mProfileChallengeUserId;
+
+ private Preference mPreference;
+
+ public VisiblePatternProfilePreferenceController(Context context, Lifecycle lifecycle) {
+ super(context, KEY_VISIBLE_PATTERN_PROFILE);
+ mUm = (UserManager) context.getSystemService(Context.USER_SERVICE);
+ mLockPatternUtils = FeatureFactory.getFactory(context)
+ .getSecurityFeatureProvider()
+ .getLockPatternUtils(context);
+ mProfileChallengeUserId = Utils.getManagedProfileId(mUm, mUserId);
+ if (lifecycle != null) {
+ lifecycle.addObserver(this);
+ }
+ }
+
+ @Override
+ public int getAvailabilityStatus() {
+ if (mLockPatternUtils.isSecure(mProfileChallengeUserId)
+ && mLockPatternUtils.getKeyguardStoredPasswordQuality(mProfileChallengeUserId)
+ == PASSWORD_QUALITY_SOMETHING) {
+ return AVAILABLE;
+ }
+ return DISABLED_FOR_USER;
+ }
+
+ @Override
+ public boolean isChecked() {
+ return mLockPatternUtils.isVisiblePatternEnabled(
+ mProfileChallengeUserId);
+ }
+
+ @Override
+ public boolean setChecked(boolean isChecked) {
+ if (Utils.startQuietModeDialogIfNecessary(mContext, mUm, mProfileChallengeUserId)) {
+ return false;
+ }
+ mLockPatternUtils.setVisiblePatternEnabled(isChecked, mProfileChallengeUserId);
+ return true;
+ }
+
+ @Override
+ public void displayPreference(PreferenceScreen screen) {
+ super.displayPreference(screen);
+ mPreference = screen.findPreference(getPreferenceKey());
+ }
+
+ @Override
+ public void onResume() {
+ mPreference.setVisible(isAvailable());
+ }
+}
diff --git a/src/com/android/settings/security/screenlock/LockScreenPreferenceController.java b/src/com/android/settings/security/screenlock/LockScreenPreferenceController.java
new file mode 100644
index 0000000..d42af2d
--- /dev/null
+++ b/src/com/android/settings/security/screenlock/LockScreenPreferenceController.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2018 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.security.screenlock;
+
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
+
+import android.content.Context;
+import android.os.UserHandle;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.core.BasePreferenceController;
+import com.android.settings.notification.LockScreenNotificationPreferenceController;
+import com.android.settings.overlay.FeatureFactory;
+import com.android.settingslib.core.lifecycle.Lifecycle;
+import com.android.settingslib.core.lifecycle.LifecycleObserver;
+import com.android.settingslib.core.lifecycle.events.OnResume;
+
+public class LockScreenPreferenceController extends BasePreferenceController implements
+ LifecycleObserver, OnResume {
+
+ static final String KEY_LOCKSCREEN_PREFERENCES = "lockscreen_preferences";
+
+ private static final int MY_USER_ID = UserHandle.myUserId();
+ private final LockPatternUtils mLockPatternUtils;
+ private Preference mPreference;
+
+ public LockScreenPreferenceController(Context context, Lifecycle lifecycle) {
+ super(context, KEY_LOCKSCREEN_PREFERENCES);
+ mLockPatternUtils = FeatureFactory.getFactory(context)
+ .getSecurityFeatureProvider().getLockPatternUtils(context);
+ if (lifecycle != null) {
+ lifecycle.addObserver(this);
+ }
+ }
+
+ @Override
+ public void displayPreference(PreferenceScreen screen) {
+ super.displayPreference(screen);
+ mPreference = screen.findPreference(getPreferenceKey());
+ }
+
+ @Override
+ public int getAvailabilityStatus() {
+ if (!mLockPatternUtils.isSecure(MY_USER_ID)) {
+ return mLockPatternUtils.isLockScreenDisabled(MY_USER_ID)
+ ? DISABLED_FOR_USER : AVAILABLE;
+ } else {
+ return mLockPatternUtils.getKeyguardStoredPasswordQuality(MY_USER_ID)
+ == PASSWORD_QUALITY_UNSPECIFIED
+ ? DISABLED_FOR_USER : AVAILABLE;
+ }
+ }
+
+ @Override
+ public void updateState(Preference preference) {
+ preference.setSummary(
+ LockScreenNotificationPreferenceController.getSummaryResource(mContext));
+ }
+
+ @Override
+ public void onResume() {
+ mPreference.setVisible(isAvailable());
+ }
+}
diff --git a/src/com/android/settings/security/trustagent/ManageTrustAgentsPreferenceController.java b/src/com/android/settings/security/trustagent/ManageTrustAgentsPreferenceController.java
new file mode 100644
index 0000000..c615eff
--- /dev/null
+++ b/src/com/android/settings/security/trustagent/ManageTrustAgentsPreferenceController.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2018 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.security.trustagent;
+
+import android.content.Context;
+import android.os.UserHandle;
+import android.support.annotation.VisibleForTesting;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.R;
+import com.android.settings.core.BasePreferenceController;
+import com.android.settings.overlay.FeatureFactory;
+import com.android.settings.security.SecurityFeatureProvider;
+
+public class ManageTrustAgentsPreferenceController extends BasePreferenceController {
+
+ @VisibleForTesting
+ static final String KEY_MANAGE_TRUST_AGENTS = "manage_trust_agents";
+ private static final int MY_USER_ID = UserHandle.myUserId();
+
+ private final LockPatternUtils mLockPatternUtils;
+ private TrustAgentManager mTrustAgentManager;
+
+ public ManageTrustAgentsPreferenceController(Context context) {
+ super(context, KEY_MANAGE_TRUST_AGENTS);
+ final SecurityFeatureProvider securityFeatureProvider = FeatureFactory.getFactory(context)
+ .getSecurityFeatureProvider();
+ mLockPatternUtils = securityFeatureProvider.getLockPatternUtils(context);
+ mTrustAgentManager = securityFeatureProvider.getTrustAgentManager();
+ }
+
+ @Override
+ public int getAvailabilityStatus() {
+ return AVAILABLE;
+ }
+
+ @Override
+ public void displayPreference(PreferenceScreen screen) {
+ super.displayPreference(screen);
+ final Preference preference = screen.findPreference(getPreferenceKey());
+ if (preference == null) {
+ return;
+ }
+ final int numberOfTrustAgent = getTrustAgentCount();
+ if (!mLockPatternUtils.isSecure(MY_USER_ID)) {
+ preference.setEnabled(false);
+ preference.setSummary(R.string.disabled_because_no_backup_security);
+ } else if (numberOfTrustAgent > 0) {
+ preference.setSummary(mContext.getResources().getQuantityString(
+ R.plurals.manage_trust_agents_summary_on,
+ numberOfTrustAgent, numberOfTrustAgent));
+ } else {
+ preference.setSummary(R.string.manage_trust_agents_summary);
+ }
+ }
+
+ private int getTrustAgentCount() {
+ return mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils).size();
+ }
+}
diff --git a/src/com/android/settings/security/trustagent/TrustAgentListPreferenceController.java b/src/com/android/settings/security/trustagent/TrustAgentListPreferenceController.java
new file mode 100644
index 0000000..99aa6a4
--- /dev/null
+++ b/src/com/android/settings/security/trustagent/TrustAgentListPreferenceController.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright (C) 2018 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.security.trustagent;
+
+import static com.android.settings.security.SecuritySettingsV2.CHANGE_TRUST_AGENT_SETTINGS;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.UserHandle;
+import android.support.annotation.VisibleForTesting;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceCategory;
+import android.support.v7.preference.PreferenceScreen;
+import android.text.TextUtils;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.R;
+import com.android.settings.overlay.FeatureFactory;
+import com.android.settings.password.ChooseLockSettingsHelper;
+import com.android.settings.security.SecurityFeatureProvider;
+import com.android.settings.security.SecuritySettingsV2;
+import com.android.settingslib.RestrictedPreference;
+import com.android.settingslib.core.AbstractPreferenceController;
+import com.android.settingslib.core.lifecycle.Lifecycle;
+import com.android.settingslib.core.lifecycle.LifecycleObserver;
+import com.android.settingslib.core.lifecycle.events.OnCreate;
+import com.android.settingslib.core.lifecycle.events.OnResume;
+import com.android.settingslib.core.lifecycle.events.OnSaveInstanceState;
+
+import java.util.List;
+
+public class TrustAgentListPreferenceController extends AbstractPreferenceController
+ implements LifecycleObserver, OnSaveInstanceState, OnCreate, OnResume {
+
+ private static final String TRUST_AGENT_CLICK_INTENT = "trust_agent_click_intent";
+ @VisibleForTesting
+ static final String PREF_KEY_TRUST_AGENT = "trust_agent";
+ @VisibleForTesting
+ static final String PREF_KEY_SECURITY_CATEGORY = "security_category";
+ private static final int MY_USER_ID = UserHandle.myUserId();
+
+ private final LockPatternUtils mLockPatternUtils;
+ private final TrustAgentManager mTrustAgentManager;
+ private final SecuritySettingsV2 mHost;
+
+ private Intent mTrustAgentClickIntent;
+ private PreferenceCategory mSecurityCategory;
+
+ public TrustAgentListPreferenceController(Context context, SecuritySettingsV2 host,
+ Lifecycle lifecycle) {
+ super(context);
+ final SecurityFeatureProvider provider = FeatureFactory.getFactory(context)
+ .getSecurityFeatureProvider();
+ mHost = host;
+ mLockPatternUtils = provider.getLockPatternUtils(context);
+ mTrustAgentManager = provider.getTrustAgentManager();
+ if (lifecycle != null) {
+ lifecycle.addObserver(this);
+ }
+ }
+
+ @Override
+ public boolean isAvailable() {
+ return true;
+ }
+
+ @Override
+ public String getPreferenceKey() {
+ return PREF_KEY_TRUST_AGENT;
+ }
+
+ @Override
+ public void displayPreference(PreferenceScreen screen) {
+ super.displayPreference(screen);
+ mSecurityCategory = (PreferenceCategory) screen.findPreference(PREF_KEY_SECURITY_CATEGORY);
+ updateTrustAgents();
+ }
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ if (savedInstanceState != null
+ && savedInstanceState.containsKey(TRUST_AGENT_CLICK_INTENT)) {
+ mTrustAgentClickIntent = savedInstanceState.getParcelable(TRUST_AGENT_CLICK_INTENT);
+ }
+ }
+
+ @Override
+ public void onSaveInstanceState(Bundle outState) {
+ if (mTrustAgentClickIntent != null) {
+ outState.putParcelable(TRUST_AGENT_CLICK_INTENT, mTrustAgentClickIntent);
+ }
+ }
+
+ @Override
+ public boolean handlePreferenceTreeClick(Preference preference) {
+ if (!TextUtils.equals(preference.getKey(), getPreferenceKey())) {
+ return super.handlePreferenceTreeClick(preference);
+ }
+ final ChooseLockSettingsHelper helper = new ChooseLockSettingsHelper(
+ mHost.getActivity(), mHost);
+ mTrustAgentClickIntent = preference.getIntent();
+ boolean confirmationLaunched = helper.launchConfirmationActivity(
+ CHANGE_TRUST_AGENT_SETTINGS, preference.getTitle());
+
+ if (!confirmationLaunched && mTrustAgentClickIntent != null) {
+ // If this returns false, it means no password confirmation is required.
+ mHost.startActivity(mTrustAgentClickIntent);
+ mTrustAgentClickIntent = null;
+ }
+ return true;
+ }
+
+ @Override
+ public void onResume() {
+ updateTrustAgents();
+ }
+
+ private void updateTrustAgents() {
+ if (mSecurityCategory == null) {
+ return;
+ }
+ // First remove all old trust agents.
+ while (true) {
+ final Preference oldAgent = mSecurityCategory.findPreference(PREF_KEY_TRUST_AGENT);
+ if (oldAgent == null) {
+ break;
+ } else {
+ mSecurityCategory.removePreference(oldAgent);
+ }
+ }
+ // Then add new ones.
+ final boolean hasSecurity = mLockPatternUtils.isSecure(MY_USER_ID);
+ final List<TrustAgentManager.TrustAgentComponentInfo> agents =
+ mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils);
+ if (agents == null) {
+ return;
+ }
+ for (TrustAgentManager.TrustAgentComponentInfo agent : agents) {
+ final RestrictedPreference trustAgentPreference =
+ new RestrictedPreference(mSecurityCategory.getContext());
+ trustAgentPreference.setKey(PREF_KEY_TRUST_AGENT);
+ trustAgentPreference.setTitle(agent.title);
+ trustAgentPreference.setSummary(agent.summary);
+ // Create intent for this preference.
+ trustAgentPreference.setIntent(new Intent(Intent.ACTION_MAIN)
+ .setComponent(agent.componentName));
+ trustAgentPreference.setDisabledByAdmin(agent.admin);
+ if (!trustAgentPreference.isDisabledByAdmin() && !hasSecurity) {
+ trustAgentPreference.setEnabled(false);
+ trustAgentPreference.setSummary(R.string.disabled_because_no_backup_security);
+ }
+ // Add preference to the settings menu.
+ mSecurityCategory.addPreference(trustAgentPreference);
+ }
+ }
+
+ public boolean handleActivityResult(int requestCode, int resultCode) {
+ if (requestCode == CHANGE_TRUST_AGENT_SETTINGS && resultCode == Activity.RESULT_OK) {
+ if (mTrustAgentClickIntent != null) {
+ mHost.startActivity(mTrustAgentClickIntent);
+ mTrustAgentClickIntent = null;
+ }
+ return true;
+ }
+ return false;
+ }
+}
diff --git a/src/com/android/settings/utils/AnnotationSpan.java b/src/com/android/settings/utils/AnnotationSpan.java
new file mode 100644
index 0000000..645351d
--- /dev/null
+++ b/src/com/android/settings/utils/AnnotationSpan.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2018 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.utils;
+
+import android.text.Annotation;
+import android.text.SpannableString;
+import android.text.SpannableStringBuilder;
+import android.text.TextPaint;
+import android.text.style.URLSpan;
+import android.view.View;
+
+/**
+ * This class is used to add {@link View.OnClickListener} for the text been wrapped by
+ * annotation.
+ */
+public class AnnotationSpan extends URLSpan {
+ private final View.OnClickListener mClickListener;
+
+ private AnnotationSpan(View.OnClickListener lsn) {
+ super((String) null);
+ mClickListener = lsn;
+ }
+
+ @Override
+ public void onClick(View widget) {
+ if (mClickListener != null) {
+ mClickListener.onClick(widget);
+ }
+ }
+
+ @Override
+ public void updateDrawState(TextPaint ds) {
+ super.updateDrawState(ds);
+ ds.setUnderlineText(false);
+ }
+
+ public static CharSequence linkify(CharSequence rawText, LinkInfo... linkInfos) {
+ SpannableString msg = new SpannableString(rawText);
+ Annotation[] spans = msg.getSpans(0, msg.length(), Annotation.class);
+ SpannableStringBuilder builder = new SpannableStringBuilder(msg);
+ for (Annotation annotation : spans) {
+ final String key = annotation.getValue();
+ int start = msg.getSpanStart(annotation);
+ int end = msg.getSpanEnd(annotation);
+ AnnotationSpan link = null;
+ for (LinkInfo linkInfo : linkInfos) {
+ if (linkInfo.annotation.equals(key)) {
+ link = new AnnotationSpan(linkInfo.listener);
+ break;
+ }
+ }
+ if (link != null) {
+ builder.setSpan(link, start, end, msg.getSpanFlags(link));
+ }
+ }
+ return builder;
+ }
+
+ /**
+ * Data class to store the annotation and the click action
+ */
+ public static class LinkInfo {
+ public final String annotation;
+ public final View.OnClickListener listener;
+
+ public LinkInfo(String annotation, View.OnClickListener listener) {
+ this.annotation = annotation;
+ this.listener = listener;
+ }
+ }
+}
diff --git a/src/com/android/settings/widget/MasterCheckBoxPreference.java b/src/com/android/settings/widget/MasterCheckBoxPreference.java
new file mode 100644
index 0000000..333c9aa
--- /dev/null
+++ b/src/com/android/settings/widget/MasterCheckBoxPreference.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2018 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.widget;
+
+import android.content.Context;
+import android.support.v7.preference.PreferenceViewHolder;
+import android.util.AttributeSet;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.CheckBox;
+
+import com.android.settings.R;
+import com.android.settingslib.TwoTargetPreference;
+
+/**
+ * A custom preference that provides inline checkbox. It has a mandatory field for title, and
+ * optional fields for icon and sub-text.
+ */
+public class MasterCheckBoxPreference extends TwoTargetPreference {
+
+ private CheckBox mCheckBox;
+ private boolean mChecked;
+
+ public MasterCheckBoxPreference(Context context, AttributeSet attrs,
+ int defStyleAttr, int defStyleRes) {
+ super(context, attrs, defStyleAttr, defStyleRes);
+ }
+
+ public MasterCheckBoxPreference(Context context, AttributeSet attrs, int defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+ }
+
+ public MasterCheckBoxPreference(Context context, AttributeSet attrs) {
+ super(context, attrs);
+ }
+
+ public MasterCheckBoxPreference(Context context) {
+ super(context);
+ }
+
+ @Override
+ protected int getSecondTargetResId() {
+ return R.layout.preference_widget_master_checkbox;
+ }
+
+ @Override
+ public void onBindViewHolder(PreferenceViewHolder holder) {
+ super.onBindViewHolder(holder);
+ final View widgetView = holder.findViewById(android.R.id.widget_frame);
+ if (widgetView != null) {
+ widgetView.setOnClickListener(new OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ if (mCheckBox != null && !mCheckBox.isEnabled()) {
+ return;
+ }
+ setChecked(!mChecked);
+ if (!callChangeListener(mChecked)) {
+ setChecked(!mChecked);
+ } else {
+ persistBoolean(mChecked);
+ }
+ }
+ });
+ }
+
+ mCheckBox = (CheckBox) holder.findViewById(R.id.checkboxWidget);
+ if (mCheckBox != null) {
+ mCheckBox.setContentDescription(getTitle());
+ mCheckBox.setChecked(mChecked);
+ }
+ }
+
+ @Override
+ public void setEnabled(boolean enabled) {
+ super.setEnabled(enabled);
+ if (mCheckBox != null) {
+ mCheckBox.setEnabled(enabled);
+ }
+ }
+
+ public boolean isChecked() {
+ return mCheckBox != null && mChecked;
+ }
+
+ public void setChecked(boolean checked) {
+ mChecked = checked;
+ if (mCheckBox != null) {
+ mCheckBox.setChecked(checked);
+ }
+ }
+
+ public CheckBox getCheckBox() {
+ return mCheckBox;
+ }
+}
diff --git a/src/com/android/settings/widget/MasterSwitchPreference.java b/src/com/android/settings/widget/MasterSwitchPreference.java
index d47de88..73774be 100644
--- a/src/com/android/settings/widget/MasterSwitchPreference.java
+++ b/src/com/android/settings/widget/MasterSwitchPreference.java
@@ -22,7 +22,6 @@
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Switch;
-import android.widget.TextView;
import com.android.settings.R;
import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
diff --git a/src/com/android/settings/widget/SwitchBar.java b/src/com/android/settings/widget/SwitchBar.java
index 3d30638..3c1e7c1 100644
--- a/src/com/android/settings/widget/SwitchBar.java
+++ b/src/com/android/settings/widget/SwitchBar.java
@@ -64,6 +64,8 @@
private TextView mTextView;
private String mLabel;
private String mSummary;
+ private int mOnTextId;
+ private int mOffTextId;
private boolean mLoggingIntialized;
private boolean mDisabledByAdmin;
@@ -102,9 +104,7 @@
mTextView = (TextView) findViewById(R.id.switch_text);
mTextView.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
- mLabel = getResources().getString(R.string.switch_off_text);
mSummarySpan = new TextAppearanceSpan(mContext, R.style.TextAppearance_Small_SwitchBar);
- updateText();
ViewGroup.MarginLayoutParams lp = (MarginLayoutParams) mTextView.getLayoutParams();
lp.setMarginStart(switchBarMarginStart);
@@ -117,6 +117,8 @@
lp.setMarginEnd(switchBarMarginEnd);
setBackgroundColor(switchBarBackgroundColor);
+ setSwitchBarText(R.string.switch_on_text, R.string.switch_off_text);
+
addOnSwitchChangeListener(new OnSwitchChangeListener() {
@Override
public void onSwitchChanged(Switch switchView, boolean isChecked) {
@@ -139,11 +141,16 @@
}
public void setTextViewLabel(boolean isChecked) {
- mLabel = getResources()
- .getString(isChecked ? R.string.switch_on_text : R.string.switch_off_text);
+ mLabel = getResources().getString(isChecked ? mOnTextId : mOffTextId);
updateText();
}
+ public void setSwitchBarText(int onText, int offText) {
+ mOnTextId = onText;
+ mOffTextId = offText;
+ setTextViewLabel(isChecked());
+ }
+
public void setSummary(String summary) {
mSummary = summary;
updateText();
diff --git a/src/com/android/settings/wifi/ConfigureWifiSettings.java b/src/com/android/settings/wifi/ConfigureWifiSettings.java
index 4cb87e5..3cd925e 100644
--- a/src/com/android/settings/wifi/ConfigureWifiSettings.java
+++ b/src/com/android/settings/wifi/ConfigureWifiSettings.java
@@ -44,6 +44,7 @@
private static final String TAG = "ConfigureWifiSettings";
+ public static final String KEY_WIFI_CONFIGURE = "wifi_configure_settings_screen";
public static final String KEY_IP_ADDRESS = "current_ip_address";
private WifiWakeupPreferenceController mWifiWakeupPreferenceController;
@@ -134,5 +135,10 @@
return keys;
}
+
+ protected boolean isPageSearchEnabled(Context context) {
+ return context.getResources()
+ .getBoolean(R.bool.config_show_wifi_settings);
+ }
};
}
diff --git a/src/com/android/settings/wifi/WifiMasterSwitchPreferenceController.java b/src/com/android/settings/wifi/WifiMasterSwitchPreferenceController.java
index 2fadede..de1b030 100644
--- a/src/com/android/settings/wifi/WifiMasterSwitchPreferenceController.java
+++ b/src/com/android/settings/wifi/WifiMasterSwitchPreferenceController.java
@@ -20,6 +20,7 @@
import com.android.settings.core.PreferenceControllerMixin;
import com.android.settings.core.instrumentation.MetricsFeatureProvider;
+import com.android.settings.R;
import com.android.settings.widget.SummaryUpdater;
import com.android.settings.widget.MasterSwitchPreference;
import com.android.settings.widget.MasterSwitchController;
@@ -56,7 +57,7 @@
@Override
public boolean isAvailable() {
- return true;
+ return mContext.getResources().getBoolean(R.bool.config_show_wifi_settings);
}
@Override
diff --git a/src/com/android/settings/wifi/WifiSettings.java b/src/com/android/settings/wifi/WifiSettings.java
index 863bf6b..73f17f7 100644
--- a/src/com/android/settings/wifi/WifiSettings.java
+++ b/src/com/android/settings/wifi/WifiSettings.java
@@ -167,7 +167,7 @@
private LinkablePreference mStatusMessagePreference;
// For Search
- private static final String DATA_KEY_REFERENCE = "main_toggle_wifi";
+ public static final String DATA_KEY_REFERENCE = "main_toggle_wifi";
/**
* Tracks whether the user initiated a connection via clicking in order to autoscroll to the
@@ -1104,13 +1104,15 @@
final List<SearchIndexableRaw> result = new ArrayList<>();
final Resources res = context.getResources();
- // Add fragment title
- SearchIndexableRaw data = new SearchIndexableRaw(context);
- data.title = res.getString(R.string.wifi_settings);
- data.screenTitle = res.getString(R.string.wifi_settings);
- data.keywords = res.getString(R.string.keywords_wifi);
- data.key = DATA_KEY_REFERENCE;
- result.add(data);
+ // Add fragment title if we are showing this fragment
+ if (res.getBoolean(R.bool.config_show_wifi_settings)) {
+ SearchIndexableRaw data = new SearchIndexableRaw(context);
+ data.title = res.getString(R.string.wifi_settings);
+ data.screenTitle = res.getString(R.string.wifi_settings);
+ data.keywords = res.getString(R.string.keywords_wifi);
+ data.key = DATA_KEY_REFERENCE;
+ result.add(data);
+ }
return result;
}
diff --git a/tests/robotests/assets/grandfather_not_in_search_index_provider_registry b/tests/robotests/assets/grandfather_not_in_search_index_provider_registry
index 666b224..6a831b0 100644
--- a/tests/robotests/assets/grandfather_not_in_search_index_provider_registry
+++ b/tests/robotests/assets/grandfather_not_in_search_index_provider_registry
@@ -1,2 +1,3 @@
com.android.settings.display.ScreenZoomPreferenceFragmentForSetupWizard
-com.android.settings.search.indexing.FakeSettingsFragment
\ No newline at end of file
+com.android.settings.search.indexing.FakeSettingsFragment
+com.android.settings.security.SecuritySettings
\ No newline at end of file
diff --git a/tests/robotests/res/values-mcc999/config.xml b/tests/robotests/res/values-mcc999/config.xml
index f8f59f1..e10fee1 100644
--- a/tests/robotests/res/values-mcc999/config.xml
+++ b/tests/robotests/res/values-mcc999/config.xml
@@ -20,7 +20,15 @@
<bool name="config_show_camera_laser_sensor">false</bool>
<bool name="config_show_connectivity_monitor">false</bool>
<bool name="config_display_recent_apps">false</bool>
+ <bool name="config_show_wifi_settings">false</bool>
+ <bool name="config_show_high_power_apps">false</bool>
+ <bool name="config_show_device_administrators">false</bool>
+ <bool name="config_show_premium_sms">false</bool>
+ <bool name="config_show_data_saver">false</bool>
+ <bool name="config_show_enabled_vr_listeners">false</bool>
<bool name="config_location_mode_available">false</bool>
<bool name="config_show_wallpaper_attribution">false</bool>
<bool name="config_show_default_home">false</bool>
+ <bool name="config_show_accessibility_shortcut_preference">false</bool>
+ <bool name="config_show_assist_and_voice_input">false</bool>
</resources>
diff --git a/tests/robotests/src/com/android/internal/accessibility/AccessibilityShortcutController.java b/tests/robotests/src/com/android/internal/accessibility/AccessibilityShortcutController.java
new file mode 100644
index 0000000..aae2f8d
--- /dev/null
+++ b/tests/robotests/src/com/android/internal/accessibility/AccessibilityShortcutController.java
@@ -0,0 +1,42 @@
+/*
+ * 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.internal.accessibility;
+
+import android.content.ComponentName;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Fake controller to make robolectric test compile. Should be removed when Robolectric supports
+ * API 25.
+ */
+public class AccessibilityShortcutController {
+
+ public static Map<ComponentName, AccessibilityShortcutController.ToggleableFrameworkFeatureInfo>
+ getFrameworkShortcutFeaturesMap() {
+ return new HashMap<>();
+ }
+
+ public static class ToggleableFrameworkFeatureInfo {
+ private String mSettingKey;
+
+ public String getSettingKey() {
+ return mSettingKey;
+ }
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/SetupChooseLockPatternTest.java b/tests/robotests/src/com/android/settings/SetupChooseLockPatternTest.java
index 60972ee..1f701c2 100644
--- a/tests/robotests/src/com/android/settings/SetupChooseLockPatternTest.java
+++ b/tests/robotests/src/com/android/settings/SetupChooseLockPatternTest.java
@@ -21,9 +21,12 @@
import static org.robolectric.RuntimeEnvironment.application;
import android.app.Activity;
+import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.os.UserHandle;
+import android.view.View;
+import android.widget.Button;
import com.android.settings.password.ChooseLockPattern.ChooseLockPatternFragment;
import com.android.settings.password.ChooseLockPattern.IntentBuilder;
@@ -40,6 +43,7 @@
import org.robolectric.Robolectric;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
+import org.robolectric.shadows.ShadowAlertDialog;
import org.robolectric.shadows.ShadowPackageManager.ComponentState;
@RunWith(SettingsRobolectricTestRunner.class)
@@ -85,6 +89,19 @@
.isEqualTo(PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
}
+ @Test
+ public void screenLockOptions_shouldBeVisible() {
+ Button button = mActivity.findViewById(R.id.screen_lock_options);
+ assertThat(button).isNotNull();
+ assertThat(button.getVisibility()).isEqualTo(View.VISIBLE);
+
+ button.performClick();
+ AlertDialog chooserDialog = ShadowAlertDialog.getLatestAlertDialog();
+ assertThat(chooserDialog).isNotNull();
+ int count = Shadows.shadowOf(chooserDialog).getAdapter().getCount();
+ assertThat(count).named("List items shown").isEqualTo(3);
+ }
+
private ChooseLockPatternFragment findFragment(Activity activity) {
return (ChooseLockPatternFragment)
activity.getFragmentManager().findFragmentById(R.id.main_content);
diff --git a/tests/robotests/src/com/android/settings/accessibility/AccessibilitySettingsTest.java b/tests/robotests/src/com/android/settings/accessibility/AccessibilitySettingsTest.java
index fb32da1..c721fc9 100644
--- a/tests/robotests/src/com/android/settings/accessibility/AccessibilitySettingsTest.java
+++ b/tests/robotests/src/com/android/settings/accessibility/AccessibilitySettingsTest.java
@@ -16,35 +16,92 @@
package com.android.settings.accessibility;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+
import android.content.Context;
+import android.support.v7.preference.Preference;
import com.android.settings.R;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.TestConfig;
import com.android.settings.testutils.XmlTestUtils;
+
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import java.util.ArrayList;
import java.util.List;
-import static com.google.common.truth.Truth.assertThat;
-
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class AccessibilitySettingsTest {
+ private Context mContext;
+ private AccessibilitySettings mFragment;
+ private boolean mAccessibilityShortcutPreferenceRemoved;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application);
+ mFragment = new AccessibilitySettings() {
+ @Override
+ public Context getContext() {
+ return mContext;
+ }
+
+ @Override
+ protected boolean removePreference(String key) {
+ if (AccessibilitySettings.ACCESSIBILITY_SHORTCUT_PREFERENCE.equals(key)) {
+ mAccessibilityShortcutPreferenceRemoved = true;
+
+ return true;
+ }
+ return false;
+ }
+ };
+ }
+
@Test
public void testNonIndexableKeys_existInXmlLayout() {
- final Context context = RuntimeEnvironment.application;
final List<String> niks = AccessibilitySettings.SEARCH_INDEX_DATA_PROVIDER
- .getNonIndexableKeys(context);
+ .getNonIndexableKeys(mContext);
final List<String> keys = new ArrayList<>();
- keys.addAll(XmlTestUtils.getKeysFromPreferenceXml(context, R.xml.accessibility_settings));
+ keys.addAll(XmlTestUtils.getKeysFromPreferenceXml(mContext, R.xml.accessibility_settings));
assertThat(keys).containsAllIn(niks);
}
+
+ @Test
+ public void testAccessibilityShortcutPreference_byDefault_shouldBeShown() {
+ final Preference preference = new Preference(mContext);
+ mFragment.checkAccessibilityShortcutVisibility(preference);
+
+ assertThat(mAccessibilityShortcutPreferenceRemoved).isFalse();
+ }
+
+ @Test
+ @Config(qualifiers = "mcc999")
+ public void testAccessibilityShortcutPreference_ifDisabled_shouldNotBeShown() {
+ final Preference preference = new Preference(mContext);
+ mFragment.checkAccessibilityShortcutVisibility(preference);
+
+ assertThat(mAccessibilityShortcutPreferenceRemoved).isTrue();
+ }
+
+ @Test
+ @Config(qualifiers = "mcc999")
+ public void testNonIndexableKeys_ifAccessibilityShortcutNotVisible_containsKey() {
+ final List<String> niks = AccessibilitySettings.SEARCH_INDEX_DATA_PROVIDER
+ .getNonIndexableKeys(mContext);
+
+ assertThat(niks).contains(AccessibilitySettings.ACCESSIBILITY_SHORTCUT_PREFERENCE);
+ }
}
diff --git a/tests/robotests/src/com/android/settings/applications/DataSaverControllerTest.java b/tests/robotests/src/com/android/settings/applications/DataSaverControllerTest.java
new file mode 100644
index 0000000..237aa71
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/applications/DataSaverControllerTest.java
@@ -0,0 +1,60 @@
+/*
+ * 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.applications;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.spy;
+
+import android.content.Context;
+
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class DataSaverControllerTest {
+
+ private Context mContext;
+ private DataSaverController mController;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application.getApplicationContext());
+ mController = new DataSaverController(mContext);
+ }
+
+ @Test
+ public void testDataSaver_byDefault_shouldBeShown() {
+ assertThat(mController.isAvailable()).isTrue();
+ }
+
+ @Test
+ @Config(qualifiers = "mcc999")
+ public void testDataSaver_ifDisabled_shouldNotBeShown() {
+ assertThat(mController.isAvailable()).isFalse();
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/applications/DeviceAdministratorsControllerTest.java b/tests/robotests/src/com/android/settings/applications/DeviceAdministratorsControllerTest.java
new file mode 100644
index 0000000..5482cd1
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/applications/DeviceAdministratorsControllerTest.java
@@ -0,0 +1,60 @@
+/*
+ * 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.applications;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.spy;
+
+import android.content.Context;
+
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class DeviceAdministratorsControllerTest {
+
+ private Context mContext;
+ private DeviceAdministratorsController mController;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application.getApplicationContext());
+ mController = new DeviceAdministratorsController(mContext);
+ }
+
+ @Test
+ public void testDeviceAdministrators_byDefault_shouldBeShown() {
+ assertThat(mController.isAvailable()).isTrue();
+ }
+
+ @Test
+ @Config(qualifiers = "mcc999")
+ public void testDeviceAdministrators_ifDisabled_shouldNotBeShown() {
+ assertThat(mController.isAvailable()).isFalse();
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/applications/EnabledVrListenersControllerTest.java b/tests/robotests/src/com/android/settings/applications/EnabledVrListenersControllerTest.java
new file mode 100644
index 0000000..5be2296
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/applications/EnabledVrListenersControllerTest.java
@@ -0,0 +1,60 @@
+/*
+ * 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.applications;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.spy;
+
+import android.content.Context;
+
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class EnabledVrListenersControllerTest {
+
+ private Context mContext;
+ private EnabledVrListenersController mController;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application.getApplicationContext());
+ mController = new EnabledVrListenersController(mContext);
+ }
+
+ @Test
+ public void testEnabledVrListeners_byDefault_shouldBeShown() {
+ assertThat(mController.isAvailable()).isTrue();
+ }
+
+ @Test
+ @Config(qualifiers = "mcc999")
+ public void testEnabledVrListeners_ifDisabled_shouldNotBeShown() {
+ assertThat(mController.isAvailable()).isFalse();
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/applications/HighPowerAppsControllerTest.java b/tests/robotests/src/com/android/settings/applications/HighPowerAppsControllerTest.java
new file mode 100644
index 0000000..d84d9bf
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/applications/HighPowerAppsControllerTest.java
@@ -0,0 +1,60 @@
+/*
+ * 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.applications;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.spy;
+
+import android.content.Context;
+
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class HighPowerAppsControllerTest {
+
+ private Context mContext;
+ private HighPowerAppsController mController;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application.getApplicationContext());
+ mController = new HighPowerAppsController(mContext);
+ }
+
+ @Test
+ public void testHighPowerApps_byDefault_shouldBeShown() {
+ assertThat(mController.isAvailable()).isTrue();
+ }
+
+ @Test
+ @Config(qualifiers = "mcc999")
+ public void testHighPowerApps_ifDisabled_shouldNotBeShown() {
+ assertThat(mController.isAvailable()).isFalse();
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/applications/PremiumSmsControllerTest.java b/tests/robotests/src/com/android/settings/applications/PremiumSmsControllerTest.java
new file mode 100644
index 0000000..0f454fc
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/applications/PremiumSmsControllerTest.java
@@ -0,0 +1,60 @@
+/*
+ * 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.applications;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.spy;
+
+import android.content.Context;
+
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class PremiumSmsControllerTest {
+
+ private Context mContext;
+ private PremiumSmsController mController;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application.getApplicationContext());
+ mController = new PremiumSmsController(mContext);
+ }
+
+ @Test
+ public void testPremiumSms_byDefault_shouldBeShown() {
+ assertThat(mController.isAvailable()).isTrue();
+ }
+
+ @Test
+ @Config(qualifiers = "mcc999")
+ public void testPremiumSms_ifDisabled_shouldNotBeShown() {
+ assertThat(mController.isAvailable()).isFalse();
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/applications/SpecialAccessSettingsTest.java b/tests/robotests/src/com/android/settings/applications/SpecialAccessSettingsTest.java
new file mode 100644
index 0000000..b0cf2f6
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/applications/SpecialAccessSettingsTest.java
@@ -0,0 +1,82 @@
+/*
+ * 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.applications;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.spy;
+
+import android.content.Context;
+import android.provider.SearchIndexableResource;
+
+import com.android.settings.R;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+import java.util.List;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class SpecialAccessSettingsTest {
+
+ private Context mContext;
+ private SpecialAccessSettings mFragment;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application);
+ mFragment = new SpecialAccessSettings() {
+ @Override
+ public Context getContext() {
+ return mContext;
+ }
+ };
+ }
+
+ @Test
+ public void testSearchIndexProvider_shouldIndexResource() {
+ final List<SearchIndexableResource> indexRes =
+ SpecialAccessSettings.SEARCH_INDEX_DATA_PROVIDER.getXmlResourcesToIndex(mContext,
+ true /* enabled */);
+ final List<String> niks =
+ SpecialAccessSettings.SEARCH_INDEX_DATA_PROVIDER.getNonIndexableKeys(mContext);
+
+ assertThat(indexRes).isNotNull();
+ assertThat(indexRes.get(0).xmlResId).isEqualTo(R.xml.special_access);
+ assertThat(niks).isEmpty();
+ }
+
+ @Test
+ @Config(qualifiers = "mcc999")
+ public void testSearchIndexProvider_ifElementsAreNotShown_shouldNotBeIndexed() {
+ final List<String> niks =
+ SpecialAccessSettings.SEARCH_INDEX_DATA_PROVIDER.getNonIndexableKeys(mContext);
+
+ assertThat(niks).contains(HighPowerAppsController.KEY_HIGH_POWER_APPS);
+ assertThat(niks).contains(DeviceAdministratorsController.KEY_DEVICE_ADMIN);
+ assertThat(niks).contains(PremiumSmsController.KEY_PREMIUM_SMS);
+ assertThat(niks).contains(DataSaverController.KEY_DATA_SAVER);
+ assertThat(niks).contains(EnabledVrListenersController.KEY_ENABLED_VR_LISTENERS);
+ }
+}
\ No newline at end of file
diff --git a/tests/robotests/src/com/android/settings/applications/appinfo/DefaultAppShortcutPreferenceControllerBaseTest.java b/tests/robotests/src/com/android/settings/applications/appinfo/DefaultAppShortcutPreferenceControllerBaseTest.java
index e44fdfb..8667f74 100644
--- a/tests/robotests/src/com/android/settings/applications/appinfo/DefaultAppShortcutPreferenceControllerBaseTest.java
+++ b/tests/robotests/src/com/android/settings/applications/appinfo/DefaultAppShortcutPreferenceControllerBaseTest.java
@@ -96,8 +96,8 @@
mController.isDefault = true;
mController.updateState(mPreference);
-
- verify(mPreference).setSummary(R.string.yes);
+ String yesString = mContext.getString(R.string.yes);
+ verify(mPreference).setSummary(yesString);
}
@Test
@@ -106,7 +106,8 @@
mController.updateState(mPreference);
- verify(mPreference).setSummary(R.string.no);
+ String noString = mContext.getString(R.string.no);
+ verify(mPreference).setSummary(noString);
}
@Test
diff --git a/tests/robotests/src/com/android/settings/applications/assist/DefaultAssistPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/applications/assist/DefaultAssistPreferenceControllerTest.java
index 180abbb..eeaba21 100644
--- a/tests/robotests/src/com/android/settings/applications/assist/DefaultAssistPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/assist/DefaultAssistPreferenceControllerTest.java
@@ -50,6 +50,7 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.annotation.Config;
+import org.robolectric.RuntimeEnvironment;
import org.robolectric.util.ReflectionHelpers;
import java.util.ArrayList;
@@ -62,26 +63,33 @@
private static final String TEST_KEY = "test_pref_key";
@Mock
- private Context mContext;
- @Mock
private SearchManager mSearchManager;
@Mock
private PackageManager mPackageManager;
+
+ private Context mContext;
private DefaultAssistPreferenceController mController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application);
mController = new DefaultAssistPreferenceController(mContext, TEST_KEY,
true /* showSetting */);
}
@Test
- public void isAlwaysAvailable() {
+ public void testAssistAndVoiceInput_byDefault_shouldBeShown() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
+ @Config(qualifiers = "mcc999")
+ public void testAssistAndVoiceInput_ifDisabled_shouldNotBeShown() {
+ assertThat(mController.isAvailable()).isFalse();
+ }
+
+ @Test
public void getPrefKey_shouldReturnKey() {
assertThat(mController.getPreferenceKey())
.isEqualTo(TEST_KEY);
@@ -91,7 +99,8 @@
@Config(shadows = {ShadowSecureSettings.class})
public void getDefaultAppInfo_hasDefaultAssist_shouldReturnKey() {
final String flattenKey = "com.android.settings/assist";
- Settings.Secure.putString(null, Settings.Secure.ASSISTANT, flattenKey);
+ Settings.Secure.putString(mContext.getContentResolver(), Settings.Secure.ASSISTANT,
+ flattenKey);
DefaultAppInfo appInfo = mController.getDefaultAppInfo();
assertThat(appInfo.getKey()).isEqualTo(flattenKey);
diff --git a/tests/robotests/src/com/android/settings/backup/BackupSettingsActivityPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/backup/BackupSettingsActivityPreferenceControllerTest.java
index 5fc3ebc..0c98ddc 100644
--- a/tests/robotests/src/com/android/settings/backup/BackupSettingsActivityPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/backup/BackupSettingsActivityPreferenceControllerTest.java
@@ -77,8 +77,8 @@
mBackupEnabled = true;
mController.updateState(mBackupPreference);
-
- verify(mBackupPreference).setSummary(R.string.accessibility_feature_state_on);
+ String summaryString = mContext.getString(R.string.accessibility_feature_state_on);
+ verify(mBackupPreference).setSummary(summaryString);
}
@Test
@@ -86,8 +86,8 @@
mBackupEnabled = false;
mController.updateState(mBackupPreference);
-
- verify(mBackupPreference).setSummary(R.string.accessibility_feature_state_off);
+ String summaryString = mContext.getString(R.string.accessibility_feature_state_off);
+ verify(mBackupPreference).setSummary(summaryString);
}
@Test
diff --git a/tests/robotests/src/com/android/settings/bluetooth/BluetoothDeviceNamePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/bluetooth/BluetoothDeviceNamePreferenceControllerTest.java
index 2e094e2..c3515df 100644
--- a/tests/robotests/src/com/android/settings/bluetooth/BluetoothDeviceNamePreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/bluetooth/BluetoothDeviceNamePreferenceControllerTest.java
@@ -63,13 +63,14 @@
doReturn(mContext).when(mPreferenceScreen).getContext();
mPreference = new Preference(mContext);
mPreference.setKey(BluetoothDeviceNamePreferenceController.KEY_DEVICE_NAME);
- mController = new BluetoothDeviceNamePreferenceController(
- mContext, mLocalAdapter);
+ mController = spy(new BluetoothDeviceNamePreferenceController(
+ mContext, mLocalAdapter));
+ doReturn(DEVICE_NAME).when(mController).getDeviceName();
}
@Test
public void testUpdateDeviceName_showSummaryWithDeviceName() {
- mController.updateDeviceName(mPreference, DEVICE_NAME);
+ mController.updateDeviceName(mPreference);
final CharSequence summary = mPreference.getSummary();
diff --git a/tests/robotests/src/com/android/settings/bluetooth/BluetoothDeviceRenamePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/bluetooth/BluetoothDeviceRenamePreferenceControllerTest.java
index 62a0d42..faf9069 100644
--- a/tests/robotests/src/com/android/settings/bluetooth/BluetoothDeviceRenamePreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/bluetooth/BluetoothDeviceRenamePreferenceControllerTest.java
@@ -19,6 +19,7 @@
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -69,13 +70,14 @@
mPreference = new Preference(mContext);
mPreference.setKey(PREF_KEY);
- mController = new BluetoothDeviceRenamePreferenceController(
- mContext, PREF_KEY, mFragment, mLocalAdapter);
+ mController = spy(new BluetoothDeviceRenamePreferenceController(
+ mContext, PREF_KEY, mFragment, mLocalAdapter));
+ doReturn(DEVICE_NAME).when(mController).getDeviceName();
}
@Test
public void testUpdateDeviceName_showSummaryWithDeviceName() {
- mController.updateDeviceName(mPreference, DEVICE_NAME);
+ mController.updateDeviceName(mPreference);
final CharSequence summary = mPreference.getSummary();
diff --git a/tests/robotests/src/com/android/settings/core/XmlControllerAttributeTest.java b/tests/robotests/src/com/android/settings/core/XmlControllerAttributeTest.java
index ed4e815..c561d0d 100644
--- a/tests/robotests/src/com/android/settings/core/XmlControllerAttributeTest.java
+++ b/tests/robotests/src/com/android/settings/core/XmlControllerAttributeTest.java
@@ -16,6 +16,7 @@
import com.android.settings.search.SearchIndexableResources;
import com.android.settings.search.XmlParserUtils;
import com.android.settings.security.SecuritySettings;
+import com.android.settings.security.SecuritySettingsV2;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import org.junit.After;
@@ -42,7 +43,8 @@
// List of classes that are too hard to mock in order to retrieve xml information.
private final List<Class> illegalClasses = new ArrayList<>(
Arrays.asList(
- SecuritySettings.class
+ SecuritySettings.class,
+ SecuritySettingsV2.class
));
// List of XML that could be retrieved from the illegalClasses list.
diff --git a/tests/robotests/src/com/android/settings/dashboard/DashboardAdapterTest.java b/tests/robotests/src/com/android/settings/dashboard/DashboardAdapterTest.java
index e2359e3..f9ef424 100644
--- a/tests/robotests/src/com/android/settings/dashboard/DashboardAdapterTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/DashboardAdapterTest.java
@@ -28,13 +28,10 @@
import static org.mockito.Mockito.when;
import android.app.PendingIntent;
-import android.content.ComponentName;
import android.content.Context;
-import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Icon;
-import android.os.Bundle;
import android.service.settings.suggestions.Suggestion;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
@@ -46,7 +43,6 @@
import com.android.settings.SettingsActivity;
import com.android.settings.TestConfig;
import com.android.settings.dashboard.conditional.Condition;
-import com.android.settings.dashboard.conditional.ConditionAdapter;
import com.android.settings.dashboard.suggestions.SuggestionAdapter;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
@@ -94,12 +90,6 @@
MockitoAnnotations.initMocks(this);
mFactory = FakeFeatureFactory.setupForTest();
when(mFactory.dashboardFeatureProvider.shouldTintIcon()).thenReturn(true);
- when(mFactory.suggestionsFeatureProvider
- .getSuggestionIdentifier(any(Context.class), any(Tile.class)))
- .thenAnswer(invocation -> {
- final Object[] args = invocation.getArguments();
- return ((Tile) args[1]).intent.getComponent().getPackageName();
- });
when(mContext.getResources()).thenReturn(mResources);
when(mResources.getQuantityString(any(int.class), any(int.class), any()))
@@ -108,14 +98,14 @@
mConditionList = new ArrayList<>();
mConditionList.add(mCondition);
when(mCondition.shouldShow()).thenReturn(true);
- mDashboardAdapter = new DashboardAdapter(mContext, null, mConditionList, null, null, null);
+ mDashboardAdapter = new DashboardAdapter(mContext, null, mConditionList, null, null);
mSuggestionHeaderData = new DashboardData.SuggestionConditionHeaderData(mConditionList, 1);
when(mView.getTag()).thenReturn(mCondition);
}
@Test
public void testSuggestionsLogs_nullSuggestionsList_shouldNotCrash() {
- setupSuggestions(makeSuggestions("pkg1", "pkg2", "pkg3", "pkg4", "pkg5"));
+ setupSuggestions(makeSuggestionsV2("pkg1", "pkg2", "pkg3", "pkg4", "pkg5"));
mDashboardAdapter.onBindSuggestionConditionHeader(mSuggestionHolder, mSuggestionHeaderData);
// set suggestions to null
@@ -131,9 +121,9 @@
@Test
public void testSuggestionDismissed_notOnlySuggestion_updateSuggestionOnly() {
final DashboardAdapter adapter =
- spy(new DashboardAdapter(mContext, null, null, null, null, null));
- final List<Tile> suggestions = makeSuggestions("pkg1", "pkg2", "pkg3");
- adapter.setCategoriesAndSuggestions(null /* category */, suggestions);
+ spy(new DashboardAdapter(mContext, null, null, null, null));
+ final List<Suggestion> suggestions = makeSuggestionsV2("pkg1", "pkg2", "pkg3");
+ adapter.setSuggestions(suggestions);
final RecyclerView data = mock(RecyclerView.class);
when(data.getResources()).thenReturn(mResources);
@@ -150,7 +140,7 @@
final DashboardData dashboardData = adapter.mDashboardData;
reset(adapter); // clear interactions tracking
- final Tile suggestionToRemove = suggestions.get(1);
+ final Suggestion suggestionToRemove = suggestions.get(1);
adapter.onSuggestionDismissed(suggestionToRemove);
assertThat(adapter.mDashboardData).isEqualTo(dashboardData);
@@ -166,12 +156,11 @@
when(itemView.findViewById(R.id.data)).thenReturn(data);
final DashboardAdapter.SuggestionAndConditionContainerHolder holder =
new DashboardAdapter.SuggestionAndConditionContainerHolder(itemView);
- final List<Tile> suggestions =
- makeSuggestions("pkg1", "pkg2", "pkg3", "pkg4");
+ final List<Suggestion> suggestions = makeSuggestionsV2("pkg1", "pkg2", "pkg3", "pkg4");
final DashboardAdapter adapter = spy(new DashboardAdapter(mContext, null /*savedInstance */,
- null /* conditions */, null /* suggestionParser */,
+ null /* conditions */,
null /* suggestionControllerMixin */, null /* callback */));
- adapter.setCategoriesAndSuggestions(null /* category */, suggestions);
+ adapter.setSuggestions(suggestions);
adapter.onBindConditionAndSuggestion(
holder, DashboardAdapter.SUGGESTION_CONDITION_HEADER_POSITION);
// default mode, only displaying 2 suggestions
@@ -180,16 +169,16 @@
// verify operations that access the lists will not cause ConcurrentModificationException
assertThat(holder.data.getAdapter().getItemCount()).isEqualTo(1);
- adapter.setCategoriesAndSuggestions(null /* category */, suggestions);
+ adapter.setSuggestions(suggestions);
// should not crash
}
@Test
public void testSuggestionDismissed_onlySuggestion_updateDashboardData() {
DashboardAdapter adapter =
- spy(new DashboardAdapter(mContext, null, null, null, null, null));
- final List<Tile> suggestions = makeSuggestions("pkg1");
- adapter.setCategoriesAndSuggestions(null /* category */, suggestions);
+ spy(new DashboardAdapter(mContext, null, null, null, null));
+ final List<Suggestion> suggestions = makeSuggestionsV2("pkg1");
+ adapter.setSuggestions(suggestions);
final DashboardData dashboardData = adapter.mDashboardData;
reset(adapter); // clear interactions tracking
@@ -200,22 +189,6 @@
}
@Test
- public void testSetCategoriesAndSuggestions_iconTinted() {
- TypedArray mockTypedArray = mock(TypedArray.class);
- doReturn(mockTypedArray).when(mContext).obtainStyledAttributes(any(int[].class));
- doReturn(0x89000000).when(mockTypedArray).getColor(anyInt(), anyInt());
-
- List<Tile> packages = makeSuggestions("pkg1");
- Icon mockIcon = mock(Icon.class);
- packages.get(0).isIconTintable = true;
- packages.get(0).icon = mockIcon;
-
- mDashboardAdapter.setCategoriesAndSuggestions(null /* category */, packages);
-
- verify(mockIcon).setTint(eq(0x89000000));
- }
-
- @Test
public void testSetCategories_iconTinted() {
TypedArray mockTypedArray = mock(TypedArray.class);
doReturn(mockTypedArray).when(mContext).obtainStyledAttributes(any(int[].class));
@@ -234,48 +207,13 @@
}
@Test
- public void testSetCategoriesAndSuggestions_limitSuggestionSize() {
- List<Tile> packages =
- makeSuggestions("pkg1", "pkg2", "pkg3", "pkg4", "pkg5", "pkg6", "pkg7");
- mDashboardAdapter.setCategoriesAndSuggestions(null /* category */, packages);
-
- assertThat(mDashboardAdapter.mDashboardData.getSuggestions().size())
- .isEqualTo(DashboardAdapter.MAX_SUGGESTION_TO_SHOW);
- }
-
- @Test
- public void testBindConditionAndSuggestion_shouldSetSuggestionAdapterAndNoCrash() {
- mDashboardAdapter = new DashboardAdapter(mContext, null, null, null, null, null);
- final List<Tile> suggestions = makeSuggestions("pkg1");
- final DashboardCategory category = new DashboardCategory();
- category.addTile(mock(Tile.class));
-
- mDashboardAdapter.setCategoriesAndSuggestions(category, suggestions);
-
- final RecyclerView data = mock(RecyclerView.class);
- when(data.getResources()).thenReturn(mResources);
- when(data.getContext()).thenReturn(mContext);
- when(mResources.getDisplayMetrics()).thenReturn(mock(DisplayMetrics.class));
- final View itemView = mock(View.class);
- when(itemView.findViewById(R.id.data)).thenReturn(data);
- final DashboardAdapter.SuggestionAndConditionContainerHolder holder =
- new DashboardAdapter.SuggestionAndConditionContainerHolder(itemView);
-
- mDashboardAdapter.onBindConditionAndSuggestion(
- holder, DashboardAdapter.SUGGESTION_CONDITION_HEADER_POSITION);
-
- verify(data).setAdapter(any(SuggestionAdapter.class));
- // should not crash
- }
-
- @Test
public void testBindConditionAndSuggestion_v2_shouldSetSuggestionAdapterAndNoCrash() {
- mDashboardAdapter = new DashboardAdapter(mContext, null, null, null, null, null);
+ mDashboardAdapter = new DashboardAdapter(mContext, null, null, null, null);
final List<Suggestion> suggestions = makeSuggestionsV2("pkg1");
final DashboardCategory category = new DashboardCategory();
category.addTile(mock(Tile.class));
- mDashboardAdapter.setSuggestionsV2(suggestions);
+ mDashboardAdapter.setSuggestions(suggestions);
final RecyclerView data = mock(RecyclerView.class);
when(data.getResources()).thenReturn(mResources);
@@ -293,50 +231,6 @@
// should not crash
}
- @Test
- public void testBindConditionAndSuggestion_emptySuggestion_shouldSetConditionAdpater() {
- final Bundle savedInstance = new Bundle();
- savedInstance.putInt(DashboardAdapter.STATE_SUGGESTION_CONDITION_MODE,
- DashboardData.HEADER_MODE_FULLY_EXPANDED);
- mDashboardAdapter = new DashboardAdapter(mContext, savedInstance, mConditionList,
- null /* SuggestionParser */, null /* suggestionControllerMixin */,
- null /* SuggestionDismissController.Callback */);
-
- final List<Tile> suggestions = new ArrayList<>();
- final DashboardCategory category = new DashboardCategory();
- category.addTile(mock(Tile.class));
- mDashboardAdapter.setCategoriesAndSuggestions(category, suggestions);
-
- final RecyclerView data = mock(RecyclerView.class);
- when(data.getResources()).thenReturn(mResources);
- when(data.getContext()).thenReturn(mContext);
- when(mResources.getDisplayMetrics()).thenReturn(mock(DisplayMetrics.class));
- final View itemView = mock(View.class);
- when(itemView.findViewById(R.id.data)).thenReturn(data);
- final DashboardAdapter.SuggestionAndConditionContainerHolder holder =
- new DashboardAdapter.SuggestionAndConditionContainerHolder(itemView);
-
- mDashboardAdapter.onBindConditionAndSuggestion(
- holder, DashboardAdapter.SUGGESTION_CONDITION_HEADER_POSITION);
-
- verify(data).setAdapter(any(ConditionAdapter.class));
- }
-
- /**
- * @deprecated in favor of {@link #makeSuggestionsV2(String...)}
- */
- @Deprecated
- private List<Tile> makeSuggestions(String... pkgNames) {
- final List<Tile> suggestions = new ArrayList<>();
- for (String pkgName : pkgNames) {
- Tile suggestion = new Tile();
- suggestion.intent = new Intent("action");
- suggestion.intent.setComponent(new ComponentName(pkgName, "cls"));
- suggestions.add(suggestion);
- }
- return suggestions;
- }
-
private List<Suggestion> makeSuggestionsV2(String... pkgNames) {
final List<Suggestion> suggestions = new ArrayList<>();
for (String pkgName : pkgNames) {
@@ -348,13 +242,11 @@
return suggestions;
}
- private void setupSuggestions(List<Tile> suggestions) {
- mDashboardAdapter.setCategoriesAndSuggestions(null /* category */, suggestions);
+ private void setupSuggestions(List<Suggestion> suggestions) {
final Context context = RuntimeEnvironment.application;
+ mDashboardAdapter.setSuggestions(suggestions);
mSuggestionHolder = new DashboardAdapter.SuggestionAndConditionHeaderHolder(
LayoutInflater.from(context).inflate(
R.layout.suggestion_condition_header, new RelativeLayout(context), true));
}
-
-
}
diff --git a/tests/robotests/src/com/android/settings/dashboard/DashboardDataTest.java b/tests/robotests/src/com/android/settings/dashboard/DashboardDataTest.java
index 2e4ef71..1116d7d 100644
--- a/tests/robotests/src/com/android/settings/dashboard/DashboardDataTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/DashboardDataTest.java
@@ -23,10 +23,11 @@
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import android.app.PendingIntent;
+import android.service.settings.suggestions.Suggestion;
import android.support.annotation.NonNull;
import android.support.v7.util.DiffUtil;
import android.support.v7.util.ListUpdateCallback;
-import android.widget.RemoteViews;
import com.android.settings.TestConfig;
import com.android.settings.dashboard.conditional.AirplaneModeCondition;
@@ -61,11 +62,10 @@
@Mock
private Tile mTestCategoryTile;
@Mock
- private Tile mTestSuggestion;
- @Mock
private Condition mTestCondition;
@Mock
private Condition mSecondCondition; // condition used to test insert in DiffUtil
+ private Suggestion mTestSuggestion;
@Before
public void SetUp() {
@@ -74,8 +74,11 @@
mDashboardCategory = new DashboardCategory();
// Build suggestions
- final List<Tile> suggestions = new ArrayList<>();
- mTestSuggestion.title = TEST_SUGGESTION_TITLE;
+ final List<Suggestion> suggestions = new ArrayList<>();
+ mTestSuggestion = new Suggestion.Builder("pkg")
+ .setTitle(TEST_SUGGESTION_TITLE)
+ .setPendingIntent(mock(PendingIntent.class))
+ .build();
suggestions.add(mTestSuggestion);
// Build oneItemConditions
@@ -227,8 +230,7 @@
final List<Condition> oneItemConditions = new ArrayList<>();
when(mTestCondition.shouldShow()).thenReturn(true);
oneItemConditions.add(mTestCondition);
- final List<Tile> suggestions = new ArrayList<>();
- mTestSuggestion.title = TEST_SUGGESTION_TITLE;
+ final List<Suggestion> suggestions = new ArrayList<>();
suggestions.add(mTestSuggestion);
final DashboardData oldData = new DashboardData.Builder()
@@ -261,20 +263,16 @@
public void testDiffUtil_typeSuggestedContainer_ResultDataNothingChanged() {
//Build testResultData
final List<ListUpdateResult.ResultData> testResultData = new ArrayList<>();
- testResultData.add(new ListUpdateResult.ResultData(
- ListUpdateResult.ResultData.TYPE_OPERATION_CHANGE, 0, 1));
- Tile tile = new Tile();
- tile.remoteViews = mock(RemoteViews.class);
DashboardData prevData = new DashboardData.Builder()
.setConditions(null)
.setCategory(null)
- .setSuggestions(Arrays.asList(tile))
+ .setSuggestions(Arrays.asList(mTestSuggestion))
.build();
DashboardData currentData = new DashboardData.Builder()
.setConditions(null)
.setCategory(null)
- .setSuggestions(Arrays.asList(tile))
+ .setSuggestions(Arrays.asList(mTestSuggestion))
.build();
testDiffUtil(prevData, currentData, testResultData);
}
diff --git a/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java b/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java
index c330340..6c663ab 100644
--- a/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/DashboardFragmentTest.java
@@ -91,6 +91,19 @@
}
@Test
+ public void testPreferenceControllerSetter_shouldAddAndNotReplace() {
+ final TestPreferenceController controller1 = new TestPreferenceController(mContext);
+ mTestFragment.addPreferenceController(controller1);
+ final TestPreferenceController controller2 = new TestPreferenceController(mContext);
+ mTestFragment.addPreferenceController(controller2);
+
+ final TestPreferenceController retrievedController = mTestFragment.getPreferenceController
+ (TestPreferenceController.class);
+
+ assertThat(controller1).isSameAs(retrievedController);
+ }
+
+ @Test
public void displayTilesAsPreference_shouldAddTilesWithIntent() {
when(mFakeFeatureFactory.dashboardFeatureProvider
.getTilesForCategory(nullable(String.class)))
@@ -146,6 +159,23 @@
}
@Test
+ public void updateState_doesNotSkipControllersOfSameClass() {
+ final AbstractPreferenceController mockController1 =
+ mock(AbstractPreferenceController.class);
+ final AbstractPreferenceController mockController2 =
+ mock(AbstractPreferenceController.class);
+ mTestFragment.addPreferenceController(mockController1);
+ mTestFragment.addPreferenceController(mockController2);
+ when(mockController1.isAvailable()).thenReturn(true);
+ when(mockController2.isAvailable()).thenReturn(true);
+
+ mTestFragment.updatePreferenceStates();
+
+ verify(mockController1).getPreferenceKey();
+ verify(mockController2).getPreferenceKey();
+ }
+
+ @Test
public void tintTileIcon_hasMetadata_shouldReturnIconTintableMetadata() {
final Tile tile = new Tile();
tile.icon = mock(Icon.class);
diff --git a/tests/robotests/src/com/android/settings/dashboard/DashboardSummaryTest.java b/tests/robotests/src/com/android/settings/dashboard/DashboardSummaryTest.java
index f3ed57c..59823ec 100644
--- a/tests/robotests/src/com/android/settings/dashboard/DashboardSummaryTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/DashboardSummaryTest.java
@@ -16,25 +16,6 @@
package com.android.settings.dashboard;
-import android.app.Activity;
-import android.support.v7.widget.LinearLayoutManager;
-
-import com.android.settings.TestConfig;
-import com.android.settings.dashboard.conditional.ConditionManager;
-import com.android.settings.dashboard.conditional.FocusRecyclerView;
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settingslib.drawer.CategoryKey;
-import com.android.settingslib.drawer.DashboardCategory;
-import com.android.settingslib.drawer.Tile;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.robolectric.annotation.Config;
-import org.robolectric.util.ReflectionHelpers;
-
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doNothing;
@@ -45,6 +26,27 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import android.app.Activity;
+import android.content.Context;
+import android.service.settings.suggestions.Suggestion;
+import android.support.v7.widget.LinearLayoutManager;
+
+import com.android.settings.TestConfig;
+import com.android.settings.dashboard.conditional.ConditionManager;
+import com.android.settings.dashboard.conditional.FocusRecyclerView;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settingslib.drawer.CategoryKey;
+import com.android.settingslib.drawer.DashboardCategory;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+import org.robolectric.util.ReflectionHelpers;
+
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
@@ -63,11 +65,13 @@
@Mock
private SummaryLoader mSummaryLoader;
+ private Context mContext;
private DashboardSummary mSummary;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
+ mContext = RuntimeEnvironment.application;
mSummary = spy(new DashboardSummary());
ReflectionHelpers.setField(mSummary, "mAdapter", mAdapter);
ReflectionHelpers.setField(mSummary, "mDashboardFeatureProvider",
@@ -79,9 +83,10 @@
}
@Test
- public void updateCategoryAndSuggestion_shouldGetCategoryFromFeatureProvider() {
+ public void updateCategory_shouldGetCategoryFromFeatureProvider() {
doReturn(mock(Activity.class)).when(mSummary).getActivity();
- mSummary.updateCategoryAndSuggestion(null);
+ mSummary.onAttach(mContext);
+ mSummary.updateCategory();
verify(mSummaryLoader).updateSummaryToCache(nullable(DashboardCategory.class));
verify(mDashboardFeatureProvider).getTilesForCategory(CategoryKey.CATEGORY_HOMEPAGE);
@@ -135,7 +140,7 @@
@Test
public void onSuggestionDismissed_shouldNotRebuildUI() {
- mSummary.onSuggestionDismissed(mock(Tile.class));
+ mSummary.onSuggestionDismissed(mock(Suggestion.class));
verify(mSummary, never()).rebuildUI();
}
}
\ No newline at end of file
diff --git a/tests/robotests/src/com/android/settings/dashboard/suggestions/EventStoreTest.java b/tests/robotests/src/com/android/settings/dashboard/suggestions/EventStoreTest.java
deleted file mode 100644
index 114ee2b..0000000
--- a/tests/robotests/src/com/android/settings/dashboard/suggestions/EventStoreTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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.dashboard.suggestions;
-
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settings.TestConfig;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.robolectric.annotation.Config;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import org.robolectric.RuntimeEnvironment;
-
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public class EventStoreTest {
-
- private EventStore mEventStore;
-
- @Before
- public void setUp() {
- mEventStore = new EventStore(RuntimeEnvironment.application);
- }
-
- @Test
- public void testWriteRead() {
- mEventStore.writeEvent("pkg", EventStore.EVENT_SHOWN);
- long timeMs = System.currentTimeMillis();
- assertThat(mEventStore.readMetric("pkg", EventStore.EVENT_SHOWN, EventStore.METRIC_COUNT))
- .isEqualTo(1);
- assertThat(Math.abs(timeMs - mEventStore
- .readMetric("pkg", EventStore.EVENT_SHOWN, EventStore.METRIC_LAST_EVENT_TIME)) < 10000)
- .isTrue();
- }
-
- @Test
- public void testWriteRead_shouldHaveLatestValues() {
- mEventStore.writeEvent("pkg", EventStore.EVENT_DISMISSED);
- mEventStore.writeEvent("pkg", EventStore.EVENT_DISMISSED);
- assertThat(
- mEventStore.readMetric("pkg", EventStore.EVENT_DISMISSED, EventStore.METRIC_COUNT))
- .isEqualTo(2);
- }
-
- @Test
- public void testWriteRead_shouldReturnDefaultIfNotAvailable() {
- assertThat(mEventStore.readMetric("pkg", EventStore.EVENT_SHOWN, EventStore.METRIC_COUNT))
- .isEqualTo(0);
- assertThat(
- mEventStore
- .readMetric("pkg", EventStore.EVENT_SHOWN, EventStore.METRIC_LAST_EVENT_TIME))
- .isEqualTo(0);
- }
-
-}
diff --git a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionAdapterTest.java b/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionAdapterTest.java
index 030fb6d..26940d6 100644
--- a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionAdapterTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionAdapterTest.java
@@ -16,28 +16,18 @@
package com.android.settings.dashboard.suggestions;
import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import android.app.PendingIntent;
-import android.content.ComponentName;
import android.content.Context;
-import android.content.Intent;
import android.graphics.drawable.Icon;
import android.service.settings.suggestions.Suggestion;
-import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
-import android.widget.RemoteViews;
-import android.widget.TextView;
import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.R;
@@ -56,7 +46,6 @@
import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
-import org.robolectric.shadows.ShadowApplication;
import java.util.ArrayList;
import java.util.List;
@@ -111,37 +100,18 @@
@Test
public void getItemCount_shouldReturnListSize() {
mSuggestionAdapter = new SuggestionAdapter(mContext, mSuggestionControllerMixin,
- mOneSuggestion, null /* suggestionV2 */, new ArrayList<>());
+ mOneSuggestionV2, new ArrayList<>());
assertThat(mSuggestionAdapter.getItemCount()).isEqualTo(1);
mSuggestionAdapter = new SuggestionAdapter(mContext, mSuggestionControllerMixin,
- mTwoSuggestions, null /* suggestionV2 */, new ArrayList<>());
- assertThat(mSuggestionAdapter.getItemCount()).isEqualTo(2);
- }
-
- @Test
- public void getItemCount_v2_shouldReturnListSize() {
- mSuggestionAdapter = new SuggestionAdapter(mContext, mSuggestionControllerMixin,
- null /* suggestions */, mOneSuggestionV2, new ArrayList<>());
- assertThat(mSuggestionAdapter.getItemCount()).isEqualTo(1);
-
- mSuggestionAdapter = new SuggestionAdapter(mContext, mSuggestionControllerMixin,
- null /* suggestions */, mTwoSuggestionsV2, new ArrayList<>());
+ mTwoSuggestionsV2, new ArrayList<>());
assertThat(mSuggestionAdapter.getItemCount()).isEqualTo(2);
}
@Test
public void getItemViewType_shouldReturnSuggestionTile() {
mSuggestionAdapter = new SuggestionAdapter(mContext, mSuggestionControllerMixin,
- mOneSuggestion, null /* suggestionV2 */, new ArrayList<>());
- assertThat(mSuggestionAdapter.getItemViewType(0))
- .isEqualTo(R.layout.suggestion_tile);
- }
-
- @Test
- public void getItemViewType_v2_shouldReturnSuggestionTile() {
- mSuggestionAdapter = new SuggestionAdapter(mContext, mSuggestionControllerMixin,
- null /* suggestions */, mOneSuggestionV2, new ArrayList<>());
+ mOneSuggestionV2, new ArrayList<>());
assertThat(mSuggestionAdapter.getItemViewType(0))
.isEqualTo(R.layout.suggestion_tile);
}
@@ -155,32 +125,19 @@
.setSummary("456")
.build());
mSuggestionAdapter = new SuggestionAdapter(mContext, mSuggestionControllerMixin,
- null /* suggestions */, suggestions, new ArrayList<>());
+ suggestions, new ArrayList<>());
assertThat(mSuggestionAdapter.getItemViewType(0))
.isEqualTo(R.layout.suggestion_tile_with_button);
}
@Test
- public void onBindViewHolder_shouldSetListener() {
- final View view = spy(LayoutInflater.from(mContext).inflate(
- R.layout.suggestion_tile, new LinearLayout(mContext), true));
- mSuggestionHolder = new DashboardAdapter.DashboardItemHolder(view);
- mSuggestionAdapter = new SuggestionAdapter(mContext, mSuggestionControllerMixin,
- mOneSuggestion, null /* suggestionV2 */, new ArrayList<>());
-
- mSuggestionAdapter.onBindViewHolder(mSuggestionHolder, 0);
-
- verify(view).setOnClickListener(any(View.OnClickListener.class));
- }
-
- @Test
public void onBindViewHolder_shouldLog() {
final View view = spy(LayoutInflater.from(mContext).inflate(
R.layout.suggestion_tile, new LinearLayout(mContext), true));
mSuggestionHolder = new DashboardAdapter.DashboardItemHolder(view);
mSuggestionAdapter = new SuggestionAdapter(mContext, mSuggestionControllerMixin,
- null /* suggestionV1*/, mOneSuggestionV2, new ArrayList<>());
+ mOneSuggestionV2, new ArrayList<>());
// Bind twice
mSuggestionAdapter.onBindViewHolder(mSuggestionHolder, 0);
@@ -193,53 +150,10 @@
}
@Test
- public void onBindViewHolder_shouldInflateRemoteView() {
- List<Tile> packages = makeSuggestions("pkg1");
- RemoteViews remoteViews = mock(RemoteViews.class);
- TextView textView = new TextView(RuntimeEnvironment.application);
- doReturn(textView).when(remoteViews).apply(any(Context.class), any(ViewGroup.class));
- packages.get(0).remoteViews = remoteViews;
- setupSuggestions(mActivity, packages, null);
-
- mSuggestionAdapter.onBindViewHolder(mSuggestionHolder, 0);
-
- assertThat(textView.getParent()).isSameAs(mSuggestionHolder.itemView);
- mSuggestionHolder.itemView.performClick();
-
- verify(mActivity).startSuggestion(any(Intent.class));
- }
-
- @Test
- public void onBindViewHolder_primaryViewShouldHandleClick() {
- Context context =
- new ContextThemeWrapper(RuntimeEnvironment.application, R.style.Theme_Settings);
-
- List<Tile> packages = makeSuggestions("pkg1");
- RemoteViews remoteViews = mock(RemoteViews.class);
- FrameLayout layout = new FrameLayout(context);
- Button primary = new Button(context);
- primary.setId(android.R.id.primary);
- layout.addView(primary);
- doReturn(layout).when(remoteViews).apply(any(Context.class), any(ViewGroup.class));
- packages.get(0).remoteViews = remoteViews;
- setupSuggestions(mActivity, packages, null /* suggestionV2 */);
-
- mSuggestionAdapter.onBindViewHolder(mSuggestionHolder, 0);
- mSuggestionHolder.itemView.performClick();
-
- assertThat(ShadowApplication.getInstance().getNextStartedActivity()).isNull();
- verify(mActivity, never()).startSuggestion(any(Intent.class));
-
- primary.performClick();
-
- verify(mActivity).startSuggestion(any(Intent.class));
- }
-
- @Test
- public void onBindViewHolder_v2_itemViewShouldHandleClick()
+ public void onBindViewHolder_itemViewShouldHandleClick()
throws PendingIntent.CanceledException {
final List<Suggestion> suggestions = makeSuggestionsV2("pkg1");
- setupSuggestions(mActivity, null /* suggestionV1 */, suggestions);
+ setupSuggestions(mActivity, suggestions);
mSuggestionAdapter.onBindViewHolder(mSuggestionHolder, 0);
mSuggestionHolder.itemView.performClick();
@@ -249,64 +163,21 @@
}
@Test
- public void onBindViewHolder_viewsShouldClearOnRebind() {
- Context context =
- new ContextThemeWrapper(RuntimeEnvironment.application, R.style.Theme_Settings);
-
- List<Tile> packages = makeSuggestions("pkg1");
- RemoteViews remoteViews = mock(RemoteViews.class);
- FrameLayout layout = new FrameLayout(context);
- Button primary = new Button(context);
- primary.setId(android.R.id.primary);
- layout.addView(primary);
- doReturn(layout).when(remoteViews).apply(any(Context.class), any(ViewGroup.class));
- packages.get(0).remoteViews = remoteViews;
- setupSuggestions(mActivity, packages, null /* suggestionV2 */);
-
- mSuggestionAdapter.onBindViewHolder(mSuggestionHolder, 0);
- mSuggestionAdapter.onBindViewHolder(mSuggestionHolder, 0);
-
- ViewGroup itemView = (ViewGroup) mSuggestionHolder.itemView;
- assertThat(itemView.getChildCount()).isEqualTo(1);
- }
-
- @Test
- public void getSuggestionsV2_shouldReturnSuggestionWhenMatch() {
+ public void getSuggestions_shouldReturnSuggestionWhenMatch() {
final List<Suggestion> suggestionsV2 = makeSuggestionsV2("pkg1");
- setupSuggestions(mActivity, null /* suggestionV1 */, suggestionsV2);
+ setupSuggestions(mActivity, suggestionsV2);
- assertThat(mSuggestionAdapter.getSuggestion(0)).isNull();
- assertThat(mSuggestionAdapter.getSuggestionsV2(0)).isNotNull();
-
- List<Tile> suggestionsV1 = makeSuggestions("pkg1");
- setupSuggestions(mActivity, suggestionsV1, null /* suggestionV2 */);
-
- assertThat(mSuggestionAdapter.getSuggestionsV2(0)).isNull();
assertThat(mSuggestionAdapter.getSuggestion(0)).isNotNull();
-
}
- private void setupSuggestions(Context context, List<Tile> suggestions,
- List<Suggestion> suggestionsV2) {
+ private void setupSuggestions(Context context, List<Suggestion> suggestionsV2) {
mSuggestionAdapter = new SuggestionAdapter(context, mSuggestionControllerMixin,
- suggestions, suggestionsV2, new ArrayList<>());
+ suggestionsV2, new ArrayList<>());
mSuggestionHolder = mSuggestionAdapter.onCreateViewHolder(
new FrameLayout(RuntimeEnvironment.application),
mSuggestionAdapter.getItemViewType(0));
}
- private List<Tile> makeSuggestions(String... pkgNames) {
- final List<Tile> suggestions = new ArrayList<>();
- for (String pkgName : pkgNames) {
- Tile suggestion = new Tile();
- suggestion.intent = new Intent("action");
- suggestion.intent.setComponent(new ComponentName(pkgName, "cls"));
- suggestions.add(suggestion);
- suggestion.icon = mock(Icon.class);
- }
- return suggestions;
- }
-
private List<Suggestion> makeSuggestionsV2(String... pkgNames) {
final List<Suggestion> suggestions = new ArrayList<>();
for (String pkgName : pkgNames) {
diff --git a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionDismissControllerTest.java b/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionDismissControllerTest.java
index 329518a..a437cb4 100644
--- a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionDismissControllerTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionDismissControllerTest.java
@@ -33,8 +33,6 @@
import com.android.settings.TestConfig;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settingslib.drawer.Tile;
-import com.android.settingslib.suggestions.SuggestionParser;
import org.junit.Before;
import org.junit.Test;
@@ -53,8 +51,6 @@
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private RecyclerView mRecyclerView;
@Mock
- private SuggestionParser mSuggestionParser;
- @Mock
private SuggestionControllerMixin mSuggestionControllerMixin;
@Mock
private SuggestionDismissController.Callback mCallback;
@@ -70,7 +66,7 @@
when(mRecyclerView.getResources().getDimension(anyInt())).thenReturn(50F);
mController = new SuggestionDismissController(mContext, mRecyclerView,
- mSuggestionControllerMixin, mSuggestionParser, mCallback);
+ mSuggestionControllerMixin, mCallback);
}
@Test
@@ -108,17 +104,6 @@
@Test
public void onSwiped_shouldTriggerDismissSuggestion() {
final RecyclerView.ViewHolder vh = mock(RecyclerView.ViewHolder.class);
-
- mController.onSwiped(vh, ItemTouchHelper.START);
-
- verify(mFactory.suggestionsFeatureProvider).dismissSuggestion(
- eq(mContext), eq(mSuggestionParser), nullable(Tile.class));
- verify(mCallback).onSuggestionDismissed(nullable(Tile.class));
- }
-
- @Test
- public void onSwiped_v2_shouldTriggerDismissSuggestion() {
- final RecyclerView.ViewHolder vh = mock(RecyclerView.ViewHolder.class);
when(mCallback.getSuggestionAt(anyInt())).thenReturn(
new Suggestion.Builder("id").build());
diff --git a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProviderImplTest.java b/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProviderImplTest.java
index 49fbf88..8ed885f 100644
--- a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProviderImplTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionFeatureProviderImplTest.java
@@ -21,7 +21,6 @@
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
@@ -30,34 +29,27 @@
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
-import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.provider.Settings.Secure;
import android.service.settings.suggestions.Suggestion;
-import android.util.FeatureFlagUtils;
import android.util.Pair;
import com.android.internal.logging.nano.MetricsProto;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.Settings.NightDisplaySuggestionActivity;
import com.android.settings.TestConfig;
-import com.android.settings.core.FeatureFlags;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.SettingsShadowResources;
-import com.android.settings.testutils.shadow.SettingsShadowSystemProperties;
import com.android.settings.testutils.shadow.ShadowSecureSettings;
import com.android.settingslib.drawer.Tile;
-import com.android.settingslib.suggestions.SuggestionParser;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
@@ -71,26 +63,21 @@
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION, shadows = {
ShadowSecureSettings.class,
SettingsShadowResources.class,
- SettingsShadowSystemProperties.class
})
public class SuggestionFeatureProviderImplTest {
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Context mContext;
@Mock
- private SuggestionParser mSuggestionParser;
- @Mock
private SuggestionControllerMixin mSuggestionControllerMixin;
@Mock
- private Tile mSuggestion;
+ private Suggestion mSuggestion;
@Mock
private ActivityManager mActivityManager;
@Mock
private PackageManager mPackageManager;
@Mock
private FingerprintManager mFingerprintManager;
- @Captor
- private ArgumentCaptor<Pair> mTaggedDataCaptor = ArgumentCaptor.forClass(Pair.class);
private FakeFeatureFactory mFactory;
private SuggestionFeatureProviderImpl mProvider;
@@ -103,20 +90,17 @@
// Explicit casting to object due to MockitoCast bug
when((Object) mContext.getSystemService(FingerprintManager.class))
.thenReturn(mFingerprintManager);
+ when(mSuggestion.getId()).thenReturn("test_id");
when(mContext.getApplicationContext()).thenReturn(RuntimeEnvironment.application);
when(mContext.getSystemService(Context.ACTIVITY_SERVICE)).thenReturn(mActivityManager);
when(mActivityManager.isLowRamDevice()).thenReturn(false);
- mSuggestion.intent = new Intent().setClassName("pkg", "cls");
- mSuggestion.category = "category";
-
mProvider = new SuggestionFeatureProviderImpl(mContext);
}
@After
public void tearDown() {
SettingsShadowResources.reset();
- SettingsShadowSystemProperties.clear();
}
@Test
@@ -129,29 +113,18 @@
public void isSuggestionEnabled_isLowMemoryDevice_shouldReturnFalse() {
when(mActivityManager.isLowRamDevice()).thenReturn(true);
- assertThat(mProvider.isSuggestionEnabled(mContext)).isFalse();
+ assertThat(mProvider.isSuggestionV2Enabled(mContext)).isFalse();
}
@Test
- public void isSuggestionV2Enabled_isNotLowMemoryDevice_sysPropOn_shouldReturnTrue() {
+ public void isSuggestionV2Enabled_isNotLowMemoryDevice_shouldReturnTrue() {
when(mActivityManager.isLowRamDevice()).thenReturn(false);
- SettingsShadowSystemProperties.set(
- FeatureFlagUtils.FFLAG_PREFIX + FeatureFlags.SUGGESTIONS_V2, "true");
assertThat(mProvider.isSuggestionV2Enabled(mContext)).isTrue();
}
@Test
- public void dismissSuggestion_noParserOrSuggestion_noop() {
- mProvider.dismissSuggestion(mContext, null, (Tile) null);
- mProvider.dismissSuggestion(mContext, mSuggestionParser, null);
- mProvider.dismissSuggestion(mContext, null, mSuggestion);
-
- verifyZeroInteractions(mFactory.metricsFeatureProvider);
- }
-
- @Test
public void dismissSuggestion_noControllerOrSuggestion_noop() {
- mProvider.dismissSuggestion(mContext, null, (Suggestion) null);
+ mProvider.dismissSuggestion(mContext, null, null);
mProvider.dismissSuggestion(mContext, mSuggestionControllerMixin, null);
mProvider.dismissSuggestion(mContext, null, new Suggestion.Builder("id").build());
@@ -160,81 +133,21 @@
}
@Test
- public void getSuggestionIdentifier_samePackage_returnClassName() {
- final Tile suggestion = new Tile();
- suggestion.intent = new Intent()
- .setClassName(RuntimeEnvironment.application.getPackageName(), "123");
- assertThat(mProvider.getSuggestionIdentifier(RuntimeEnvironment.application, suggestion))
- .isEqualTo("123");
- }
-
- @Test
- public void getSuggestionIdentifier_differentPackage_returnPackageName() {
- final Tile suggestion = new Tile();
- suggestion.intent = new Intent()
- .setClassName(RuntimeEnvironment.application.getPackageName(), "123");
- assertThat(mProvider.getSuggestionIdentifier(mContext, suggestion))
- .isEqualTo(RuntimeEnvironment.application.getPackageName());
- }
-
- @Test
- public void getSuggestionIdentifier_nullComponent_shouldNotCrash() {
- final Tile suggestion = new Tile();
- suggestion.intent = new Intent();
- assertThat(mProvider.getSuggestionIdentifier(mContext, suggestion))
- .isNotEmpty();
- }
-
- @Test
- public void getSuggestionIdentifier_nullContext_shouldNotCrash() {
- final Tile suggestion = new Tile();
- suggestion.intent = new Intent()
- .setClassName(RuntimeEnvironment.application.getPackageName(), "123");
- assertThat(mProvider.getSuggestionIdentifier(null, suggestion))
- .isNotEmpty();
- }
-
- @Test
- public void dismissSuggestion_hasMoreDismissCount_shouldNotDisableComponent() {
- when(mSuggestionParser.dismissSuggestion(any(Tile.class)))
- .thenReturn(false);
- mProvider.dismissSuggestion(mContext, mSuggestionParser, mSuggestion);
-
- verify(mFactory.metricsFeatureProvider).action(
- eq(mContext),
- eq(MetricsProto.MetricsEvent.ACTION_SETTINGS_DISMISS_SUGGESTION),
- anyString(),
- mTaggedDataCaptor.capture());
- assertThat(mTaggedDataCaptor.getAllValues()).containsExactly(
- Pair.create(MetricsEvent.FIELD_SETTINGS_SMART_SUGGESTIONS_ENABLED, 0));
- verify(mContext, never()).getPackageManager();
- }
-
- @Test
public void dismissSuggestion_noContext_shouldDoNothing() {
- mProvider.dismissSuggestion(null, mSuggestionParser, mSuggestion);
+ mProvider.dismissSuggestion(null, mSuggestionControllerMixin, mSuggestion);
verifyZeroInteractions(mFactory.metricsFeatureProvider);
}
@Test
- public void dismissSuggestion_hasNoMoreDismissCount_shouldDisableComponent() {
- when(mSuggestionParser.dismissSuggestion(any(Tile.class)))
- .thenReturn(true);
-
- mProvider.dismissSuggestion(mContext, mSuggestionParser, mSuggestion);
+ public void dismissSuggestion_shouldLogAndDismiss() {
+ mProvider.dismissSuggestion(mContext, mSuggestionControllerMixin, mSuggestion);
verify(mFactory.metricsFeatureProvider).action(
eq(mContext),
eq(MetricsProto.MetricsEvent.ACTION_SETTINGS_DISMISS_SUGGESTION),
- anyString(),
- mTaggedDataCaptor.capture());
- assertThat(mTaggedDataCaptor.getAllValues()).containsExactly(
- Pair.create(MetricsEvent.FIELD_SETTINGS_SMART_SUGGESTIONS_ENABLED, 0));
- verify(mContext.getPackageManager())
- .setComponentEnabledSetting(mSuggestion.intent.getComponent(),
- PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
- PackageManager.DONT_KILL_APP);
+ anyString());
+ verify(mSuggestionControllerMixin).dismissSuggestion(mSuggestion);
}
@Test
diff --git a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionFeaturizerTest.java b/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionFeaturizerTest.java
deleted file mode 100644
index 4d6a743..0000000
--- a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionFeaturizerTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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.dashboard.suggestions;
-
-import java.util.Arrays;
-import java.util.Map;
-
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settings.TestConfig;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.robolectric.annotation.Config;
-
-import static com.google.common.truth.Truth.assertThat;
-
-import org.robolectric.RuntimeEnvironment;
-
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public class SuggestionFeaturizerTest {
-
- private EventStore mEventStore;
- private SuggestionFeaturizer mSuggestionFeaturizer;
-
- @Before
- public void setUp() {
- mEventStore = new EventStore(RuntimeEnvironment.application);
- mSuggestionFeaturizer = new SuggestionFeaturizer(mEventStore);
- }
-
- @Test
- public void testFeaturize_singlePackage() {
- mEventStore.writeEvent("pkg", EventStore.EVENT_DISMISSED);
- mEventStore.writeEvent("pkg", EventStore.EVENT_SHOWN);
- mEventStore.writeEvent("pkg", EventStore.EVENT_SHOWN);
- Map<String, Double> features = mSuggestionFeaturizer.featurize(Arrays.asList("pkg"))
- .get("pkg");
- assertThat(features.get(SuggestionFeaturizer.FEATURE_IS_SHOWN)).isEqualTo(1.0);
- assertThat(features.get(SuggestionFeaturizer.FEATURE_IS_DISMISSED)).isEqualTo(1.0);
- assertThat(features.get(SuggestionFeaturizer.FEATURE_IS_CLICKED)).isEqualTo(0.0);
-
- assertThat(features.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_SHOWN)).isLessThan(1.0);
- assertThat(features.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_DISMISSED))
- .isLessThan(1.0);
- assertThat(features.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_CLICKED))
- .isEqualTo(1.0);
- assertThat(features.get(SuggestionFeaturizer.FEATURE_SHOWN_COUNT))
- .isEqualTo(2.0 / SuggestionFeaturizer.COUNT_NORMALIZATION_FACTOR);
- assertThat(features.get(SuggestionFeaturizer.FEATURE_DISMISSED_COUNT))
- .isEqualTo(1.0 / SuggestionFeaturizer.COUNT_NORMALIZATION_FACTOR);
- assertThat(features.get(SuggestionFeaturizer.FEATURE_CLICKED_COUNT)).isEqualTo(0.0);
- }
-
- @Test
- public void testFeaturize_multiplePackages() {
- mEventStore.writeEvent("pkg1", EventStore.EVENT_DISMISSED);
- mEventStore.writeEvent("pkg2", EventStore.EVENT_SHOWN);
- mEventStore.writeEvent("pkg1", EventStore.EVENT_SHOWN);
- Map<String, Map<String, Double>> features = mSuggestionFeaturizer
- .featurize(Arrays.asList("pkg1", "pkg2"));
- Map<String, Double> features1 = features.get("pkg1");
- Map<String, Double> features2 = features.get("pkg2");
-
- assertThat(features1.get(SuggestionFeaturizer.FEATURE_IS_SHOWN)).isEqualTo(1.0);
- assertThat(features1.get(SuggestionFeaturizer.FEATURE_IS_DISMISSED)).isEqualTo(1.0);
- assertThat(features1.get(SuggestionFeaturizer.FEATURE_IS_CLICKED)).isEqualTo(0.0);
- assertThat(features1.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_SHOWN))
- .isLessThan(1.0);
- assertThat(features1.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_DISMISSED))
- .isLessThan(1.0);
- assertThat(features1.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_CLICKED))
- .isEqualTo(1.0);
- assertThat(features1.get(SuggestionFeaturizer.FEATURE_SHOWN_COUNT))
- .isEqualTo(1.0 / SuggestionFeaturizer.COUNT_NORMALIZATION_FACTOR);
- assertThat(features1.get(SuggestionFeaturizer.FEATURE_DISMISSED_COUNT))
- .isEqualTo(1.0 / SuggestionFeaturizer.COUNT_NORMALIZATION_FACTOR);
- assertThat(features1.get(SuggestionFeaturizer.FEATURE_CLICKED_COUNT)).isEqualTo(0.0);
-
- assertThat(features2.get(SuggestionFeaturizer.FEATURE_IS_SHOWN)).isEqualTo(1.0);
- assertThat(features2.get(SuggestionFeaturizer.FEATURE_IS_DISMISSED)).isEqualTo(0.0);
- assertThat(features2.get(SuggestionFeaturizer.FEATURE_IS_CLICKED)).isEqualTo(0.0);
- assertThat(features2.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_SHOWN))
- .isLessThan(1.0);
- assertThat(features2.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_DISMISSED))
- .isEqualTo(1.0);
- assertThat(features2.get(SuggestionFeaturizer.FEATURE_TIME_FROM_LAST_CLICKED))
- .isEqualTo(1.0);
- assertThat(features2.get(SuggestionFeaturizer.FEATURE_SHOWN_COUNT))
- .isEqualTo(1.0 / SuggestionFeaturizer.COUNT_NORMALIZATION_FACTOR);
- assertThat(features2.get(SuggestionFeaturizer.FEATURE_DISMISSED_COUNT)).isEqualTo(0.0);
- assertThat(features2.get(SuggestionFeaturizer.FEATURE_CLICKED_COUNT)).isEqualTo(0.0);
- }
-}
diff --git a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionRankerTest.java b/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionRankerTest.java
deleted file mode 100644
index 1f32531..0000000
--- a/tests/robotests/src/com/android/settings/dashboard/suggestions/SuggestionRankerTest.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * 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.dashboard.suggestions;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settings.TestConfig;
-import com.android.settingslib.drawer.Tile;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-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;
-import static org.mockito.Mockito.same;
-import static org.mockito.Mockito.spy;
-
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
-public class SuggestionRankerTest {
-
- @Mock
- private SuggestionRanker mSuggestionRanker;
- @Mock
- private SuggestionFeaturizer mSuggestionFeaturizer;
- private Map<String, Map<String, Double>> mFeatures;
- private List<String> mPkgNames;
- private List<Tile> mSuggestions;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- mPkgNames = Arrays.asList("pkg1", "pkg2", "pkg3");
- mFeatures = new HashMap<String, Map<String, Double>>();
- mFeatures.put("pkg1", new HashMap<String, Double>());
- mFeatures.put("pkg2", new HashMap<String, Double>());
- mFeatures.put("pkg3", new HashMap<String, Double>());
- mSuggestions = new ArrayList<Tile>() {
- {
- add(new Tile());
- add(new Tile());
- add(new Tile());
- }
- };
- mSuggestionFeaturizer = mock(SuggestionFeaturizer.class);
- mSuggestionRanker = new SuggestionRanker(mSuggestionFeaturizer);
- when(mSuggestionFeaturizer.featurize(mPkgNames)).thenReturn(mFeatures);
- mSuggestionRanker = spy(mSuggestionRanker);
- when(mSuggestionRanker.getRelevanceMetric(same(mFeatures.get("pkg1")))).thenReturn(0.9);
- when(mSuggestionRanker.getRelevanceMetric(same(mFeatures.get("pkg2")))).thenReturn(0.1);
- when(mSuggestionRanker.getRelevanceMetric(same(mFeatures.get("pkg3")))).thenReturn(0.5);
- }
-
- @Test
- public void testRank() {
- List<Tile> expectedOrderdList = new ArrayList<Tile>() {
- {
- add(mSuggestions.get(0)); // relevance = 0.9
- add(mSuggestions.get(2)); // relevance = 0.5
- add(mSuggestions.get(1)); // relevance = 0.1
- }
- };
- mSuggestionRanker.rankSuggestions(mSuggestions, mPkgNames);
- assertThat(mSuggestions).isEqualTo(expectedOrderdList);
- }
-}
-
diff --git a/tests/robotests/src/com/android/settings/development/BluetoothInbandRingingPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/development/BluetoothInbandRingingPreferenceControllerTest.java
index 4074e25..d0552ec 100644
--- a/tests/robotests/src/com/android/settings/development/BluetoothInbandRingingPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/development/BluetoothInbandRingingPreferenceControllerTest.java
@@ -18,7 +18,7 @@
import static com.android.settings.development.BluetoothInbandRingingPreferenceController
- .BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY;
+ .BLUETOOTH_DISABLE_INBAND_RINGING_PROPERTY;
import static com.google.common.truth.Truth.assertThat;
@@ -84,7 +84,7 @@
mController.onPreferenceChange(mPreference, true /* new value */);
final boolean mode = SettingsShadowSystemProperties.getBoolean(
- BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY, false /* default */);
+ BLUETOOTH_DISABLE_INBAND_RINGING_PROPERTY, false /* default */);
assertThat(mode).isTrue();
}
@@ -94,14 +94,14 @@
mController.onPreferenceChange(mPreference, false /* new value */);
final boolean mode = SettingsShadowSystemProperties.getBoolean(
- BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY, false /* default */);
+ BLUETOOTH_DISABLE_INBAND_RINGING_PROPERTY, false /* default */);
assertThat(mode).isFalse();
}
@Test
public void updateState_settingEnabled_preferenceShouldBeChecked() {
- SettingsShadowSystemProperties.set(BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY,
+ SettingsShadowSystemProperties.set(BLUETOOTH_DISABLE_INBAND_RINGING_PROPERTY,
Boolean.toString(true));
mController.updateState(mPreference);
@@ -110,7 +110,7 @@
@Test
public void updateState_settingDisabled_preferenceShouldNotBeChecked() {
- SettingsShadowSystemProperties.set(BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY,
+ SettingsShadowSystemProperties.set(BLUETOOTH_DISABLE_INBAND_RINGING_PROPERTY,
Boolean.toString(false));
mController.updateState(mPreference);
@@ -122,11 +122,11 @@
mController.onDeveloperOptionsDisabled();
final boolean mode = SettingsShadowSystemProperties.getBoolean(
- BLUETOOTH_ENABLE_INBAND_RINGING_PROPERTY, false /* default */);
+ BLUETOOTH_DISABLE_INBAND_RINGING_PROPERTY, false /* default */);
- assertThat(mode).isTrue();
+ assertThat(mode).isFalse();
verify(mPreference).setEnabled(false);
- verify(mPreference).setChecked(true);
+ verify(mPreference).setChecked(false);
}
@Test
diff --git a/tests/robotests/src/com/android/settings/development/BluetoothMaxConnectedAudioDevicesPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/development/BluetoothMaxConnectedAudioDevicesPreferenceControllerTest.java
new file mode 100644
index 0000000..cf892f8
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/development/BluetoothMaxConnectedAudioDevicesPreferenceControllerTest.java
@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2018 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.development;
+
+import static com.android.settings.development.BluetoothMaxConnectedAudioDevicesPreferenceController
+ .BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_PROPERTY;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.os.SystemProperties;
+import android.support.v7.preference.ListPreference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.settings.R;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settings.testutils.shadow.SettingsShadowSystemProperties;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH,
+ sdk = TestConfig.SDK_VERSION,
+ shadows = {SettingsShadowSystemProperties.class})
+public class BluetoothMaxConnectedAudioDevicesPreferenceControllerTest {
+
+ @Mock
+ private PreferenceScreen mPreferenceScreen;
+
+ private Context mContext;
+ private ListPreference mPreference;
+ private BluetoothMaxConnectedAudioDevicesPreferenceController mController;
+
+ /**
+ * 0: 1 device maximum (Default)
+ * 1: 2 devices maximum
+ * 2: 3 devices maximum
+ * 3: 4 devices maximum
+ * 4: 5 devices maximum
+ */
+ private String[] mListValues;
+ private String[] mListSummaries;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ mContext = RuntimeEnvironment.application;
+ mPreference = new ListPreference(mContext);
+ mListValues = mContext.getResources().getStringArray(
+ R.array.bluetooth_max_connected_audio_devices_values);
+ mListSummaries = mContext.getResources().getStringArray(
+ R.array.bluetooth_max_connected_audio_devices);
+ mController = new BluetoothMaxConnectedAudioDevicesPreferenceController(mContext);
+ when(mPreferenceScreen.findPreference(mController.getPreferenceKey())).thenReturn(
+ mPreference);
+ mController.displayPreference(mPreferenceScreen);
+ }
+
+ @After
+ public void teardown() {
+ SettingsShadowSystemProperties.clear();
+ }
+
+ @Test
+ public void onPreferenceChange_setNumberOfDevices() {
+ for (int numberOfDevices = 0; numberOfDevices < mListValues.length; numberOfDevices++) {
+ mController.onPreferenceChange(mPreference, mListValues[numberOfDevices]);
+
+ final String currentValue = SystemProperties.get(
+ BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_PROPERTY);
+
+ assertThat(currentValue).isEqualTo(mListValues[numberOfDevices]);
+ assertThat(mPreference.getValue()).isEqualTo(mListValues[numberOfDevices]);
+ assertThat(mPreference.getSummary()).isEqualTo(mListSummaries[numberOfDevices]);
+ }
+ }
+
+ @Test
+ public void updateState_NumberOfDevicesUpdated_shouldSetPreference() {
+ for (int numberOfDevices = 0; numberOfDevices < mListValues.length; numberOfDevices++) {
+ SystemProperties.set(BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_PROPERTY,
+ mListValues[numberOfDevices]);
+
+ mController.updateState(mPreference);
+
+ assertThat(mPreference.getValue()).isEqualTo(mListValues[numberOfDevices]);
+ assertThat(mPreference.getSummary()).isEqualTo(mListSummaries[numberOfDevices]);
+ }
+ }
+
+ @Test
+ public void updateState_noValueSet_shouldSetDefaultTo1device() {
+ SystemProperties.set(BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_PROPERTY, "garbage");
+ mController.updateState(mPreference);
+
+ assertThat(mPreference.getValue()).isEqualTo(mListValues[0]);
+ assertThat(mPreference.getSummary()).isEqualTo(mListSummaries[0]);
+ }
+
+ @Test
+ public void onDeveloperOptionsSwitchDisabled_shouldDisablePreference() {
+ mController.onDeveloperOptionsSwitchDisabled();
+
+ assertThat(mPreference.isEnabled()).isFalse();
+ assertThat(mPreference.getValue()).isEqualTo(mListValues[0]);
+ assertThat(mPreference.getSummary()).isEqualTo(mListSummaries[0]);
+ final String currentValue = SystemProperties.get(
+ BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_PROPERTY);
+ assertThat(currentValue).isEqualTo(mListValues[0]);
+ }
+
+ @Test
+ public void onDeveloperOptionsSwitchEnabled_shouldEnablePreference() {
+ for (int numberOfDevices = 0; numberOfDevices < mListValues.length; numberOfDevices++) {
+ mController.onDeveloperOptionsSwitchDisabled();
+ assertThat(mPreference.isEnabled()).isFalse();
+
+ SystemProperties.set(BLUETOOTH_MAX_CONNECTED_AUDIO_DEVICES_PROPERTY,
+ mListValues[numberOfDevices]);
+ mController.onDeveloperOptionsSwitchEnabled();
+
+ assertThat(mPreference.isEnabled()).isTrue();
+ assertThat(mPreference.getValue()).isEqualTo(mListValues[numberOfDevices]);
+ assertThat(mPreference.getSummary()).isEqualTo(mListSummaries[numberOfDevices]);
+ }
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/fingerprint/FingerprintEnrollSuggestionActivityTest.java b/tests/robotests/src/com/android/settings/fingerprint/FingerprintEnrollSuggestionActivityTest.java
index e299fd5..66114aa 100644
--- a/tests/robotests/src/com/android/settings/fingerprint/FingerprintEnrollSuggestionActivityTest.java
+++ b/tests/robotests/src/com/android/settings/fingerprint/FingerprintEnrollSuggestionActivityTest.java
@@ -58,7 +58,8 @@
.thenReturn(mDevicePolicyManager);
when(mDevicePolicyManager.getKeyguardDisabledFeatures(any(), anyInt()))
.thenReturn(0);
- when(mContext.getSystemService(FingerprintManager.class)).thenReturn(mFingerprintManager);
+ when(mContext.getSystemService(Context.FINGERPRINT_SERVICE))
+ .thenReturn(mFingerprintManager);
}
@Test
diff --git a/tests/robotests/src/com/android/settings/fingerprint/FingerprintProfileStatusPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/fingerprint/FingerprintProfileStatusPreferenceControllerTest.java
new file mode 100644
index 0000000..9993a95
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/fingerprint/FingerprintProfileStatusPreferenceControllerTest.java
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2018 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.fingerprint;
+
+import static com.android.settings.core.BasePreferenceController.DISABLED_FOR_USER;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.hardware.fingerprint.FingerprintManager;
+import android.os.UserManager;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.FakeFeatureFactory;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+import org.robolectric.shadows.ShadowApplication;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class FingerprintProfileStatusPreferenceControllerTest {
+
+ private static final int FAKE_PROFILE_USER_ID = 1234;
+
+ @Mock
+ private PackageManager mPackageManager;
+ @Mock
+ private LockPatternUtils mLockPatternUtils;
+ @Mock
+ private FingerprintManager mFingerprintManager;
+ @Mock
+ private UserManager mUm;
+
+ private FakeFeatureFactory mFeatureFactory;
+ private Context mContext;
+ private FingerprintProfileStatusPreferenceController mController;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application);
+ when(mContext.getPackageManager()).thenReturn(mPackageManager);
+ when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)).thenReturn(true);
+ ShadowApplication.getInstance().setSystemService(Context.FINGERPRINT_SERVICE,
+ mFingerprintManager);
+ ShadowApplication.getInstance().setSystemService(Context.USER_SERVICE, mUm);
+
+ mFeatureFactory = FakeFeatureFactory.setupForTest();
+ when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
+ .thenReturn(mLockPatternUtils);
+ when(mUm.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[] {1234});
+ mController = new FingerprintProfileStatusPreferenceController(mContext);
+ }
+
+ @Test
+ public void getUserId_shouldReturnProfileId() {
+ assertThat(mController.getUserId()).isEqualTo(FAKE_PROFILE_USER_ID);
+ }
+
+ @Test
+ public void isUserSupported_separateChallengeAllowed_true() {
+ when(mLockPatternUtils.isSeparateProfileChallengeAllowed(anyInt())).thenReturn(true);
+ assertThat(mController.isUserSupported()).isTrue();
+ }
+
+ @Test
+ public void isUserSupported_separateChallengeNotAllowed_false() {
+ when(mLockPatternUtils.isSeparateProfileChallengeAllowed(anyInt())).thenReturn(false);
+
+ assertThat(mController.isUserSupported()).isFalse();
+ }
+
+ @Test
+ public void getAvailabilityStatus_userNotSupported_DISABLED() {
+ when(mFingerprintManager.isHardwareDetected()).thenReturn(true);
+ when(mLockPatternUtils.isSeparateProfileChallengeAllowed(anyInt())).thenReturn(false);
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_FOR_USER);
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/fingerprint/FingerprintStatusPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/fingerprint/FingerprintStatusPreferenceControllerTest.java
new file mode 100644
index 0000000..ab53382
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/fingerprint/FingerprintStatusPreferenceControllerTest.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2018 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.fingerprint;
+
+import static com.android.settings.core.BasePreferenceController.AVAILABLE;
+import static com.android.settings.core.BasePreferenceController.DISABLED_UNSUPPORTED;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.hardware.fingerprint.Fingerprint;
+import android.hardware.fingerprint.FingerprintManager;
+import android.os.UserManager;
+import android.support.v7.preference.Preference;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.R;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.FakeFeatureFactory;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+import org.robolectric.shadows.ShadowApplication;
+
+import java.util.Arrays;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class FingerprintStatusPreferenceControllerTest {
+
+ @Mock
+ private LockPatternUtils mLockPatternUtils;
+ @Mock
+ private FingerprintManager mFingerprintManager;
+ @Mock
+ private UserManager mUm;
+ @Mock
+ private PackageManager mPackageManager;
+
+ private FakeFeatureFactory mFeatureFactory;
+ private Context mContext;
+ private FingerprintStatusPreferenceController mController;
+ private Preference mPreference;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application);
+ when(mContext.getPackageManager()).thenReturn(mPackageManager);
+ when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)).thenReturn(true);
+ ShadowApplication.getInstance().setSystemService(Context.FINGERPRINT_SERVICE,
+ mFingerprintManager);
+ ShadowApplication.getInstance().setSystemService(Context.USER_SERVICE, mUm);
+ mPreference = new Preference(mContext);
+ mFeatureFactory = FakeFeatureFactory.setupForTest();
+ when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
+ .thenReturn(mLockPatternUtils);
+ when(mUm.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[] {1234});
+ mController = new FingerprintStatusPreferenceController(mContext);
+ }
+
+ @Test
+ public void getAvailabilityStatus_noFingerprintManger_DISABLED() {
+ when(mFingerprintManager.isHardwareDetected()).thenReturn(false);
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_UNSUPPORTED);
+ }
+
+ @Test
+ public void getAvailabilityStatus_hasFingerprintManger_AVAILABLE() {
+ when(mFingerprintManager.isHardwareDetected()).thenReturn(true);
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
+ }
+
+ @Test
+ public void updateState_notSupported_shouldDoNothing() {
+ when(mFingerprintManager.isHardwareDetected()).thenReturn(false);
+
+ mController.updateState(mPreference);
+
+ assertThat(mPreference.isVisible()).isFalse();
+ }
+
+ @Test
+ public void updateState_noFingerprint_shouldShowDefaultSummary() {
+ when(mFingerprintManager.isHardwareDetected()).thenReturn(true);
+
+ mController.updateState(mPreference);
+
+ assertThat(mPreference.getSummary()).isEqualTo(
+ mContext.getString(R.string.security_settings_fingerprint_preference_summary_none));
+ assertThat(mPreference.isVisible()).isTrue();
+ assertThat(mPreference.getOnPreferenceClickListener()).isNotNull();
+ }
+
+ @Test
+ public void updateState_hasFingerprint_shouldShowSummary() {
+ when(mFingerprintManager.isHardwareDetected()).thenReturn(true);
+ when(mFingerprintManager.getEnrolledFingerprints(anyInt()))
+ .thenReturn(Arrays.asList(mock(Fingerprint.class)));
+
+ mController.updateState(mPreference);
+
+ assertThat(mPreference.getSummary()).isEqualTo(mContext.getResources().getQuantityString(
+ R.plurals.security_settings_fingerprint_preference_summary, 1, 1));
+ assertThat(mPreference.isVisible()).isTrue();
+ assertThat(mPreference.getOnPreferenceClickListener()).isNotNull();
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacyTest.java b/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacyTest.java
index bc5b1d7..45448a9 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacyTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/PowerUsageSummaryLegacyTest.java
@@ -401,18 +401,6 @@
}
@Test
- public void testNonIndexableKeys_MatchPreferenceKeys() {
- final Context context = RuntimeEnvironment.application;
- final List<String> niks = PowerUsageSummary.SEARCH_INDEX_DATA_PROVIDER
- .getNonIndexableKeys(context);
-
- final List<String> keys = XmlTestUtils.getKeysFromPreferenceXml(context,
- R.xml.power_usage_summary);
-
- assertThat(keys).containsAllIn(niks);
- }
-
- @Test
public void testPreferenceControllers_getPreferenceKeys_existInPreferenceScreen() {
final Context context = RuntimeEnvironment.application;
final PowerUsageSummary fragment = new PowerUsageSummary();
diff --git a/tests/robotests/src/com/android/settings/gestures/SwipeToNotificationPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/gestures/SwipeToNotificationPreferenceControllerTest.java
index f3cc2ca..86fd267 100644
--- a/tests/robotests/src/com/android/settings/gestures/SwipeToNotificationPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/gestures/SwipeToNotificationPreferenceControllerTest.java
@@ -59,8 +59,7 @@
MockitoAnnotations.initMocks(this);
mController = new SwipeToNotificationPreferenceController(mContext, null, KEY_SWIPE_DOWN);
when(mContext.getPackageManager()).thenReturn(mPackageManager);
- // Explicit casting to object due to MockitoCast bug
- when((Object) mContext.getSystemService(FingerprintManager.class))
+ when(mContext.getSystemService(Context.FINGERPRINT_SERVICE))
.thenReturn(mFingerprintManager);
}
diff --git a/tests/robotests/src/com/android/settings/network/PrivateDnsModeDialogFragmentTest.java b/tests/robotests/src/com/android/settings/network/PrivateDnsModeDialogFragmentTest.java
index f1d7a73..bba689b 100644
--- a/tests/robotests/src/com/android/settings/network/PrivateDnsModeDialogFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/network/PrivateDnsModeDialogFragmentTest.java
@@ -50,7 +50,6 @@
private PrivateDnsModeDialogFragment mFragment;
private Button mSaveButton;
-
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
diff --git a/tests/robotests/src/com/android/settings/password/SetupChooseLockPasswordTest.java b/tests/robotests/src/com/android/settings/password/SetupChooseLockPasswordTest.java
index 28be616..cd5fcc2 100644
--- a/tests/robotests/src/com/android/settings/password/SetupChooseLockPasswordTest.java
+++ b/tests/robotests/src/com/android/settings/password/SetupChooseLockPasswordTest.java
@@ -135,11 +135,9 @@
fragment.onLockTypeSelected(ScreenLockType.PATTERN);
ShadowActivity shadowActivity = shadowOf(activity);
- IntentForResult chooseLockIntent = shadowActivity.getNextStartedActivityForResult();
- assertThat(chooseLockIntent).isNotNull();
- assertThat(chooseLockIntent.requestCode)
- .isEqualTo(SetupChooseLockPasswordFragment.REQUEST_SCREEN_LOCK_OPTIONS);
- assertThat(chooseLockIntent.intent.getStringExtra("foo")).named("Foo extra")
+ final Intent nextStartedActivity = shadowActivity.getNextStartedActivity();
+ assertThat(nextStartedActivity).isNotNull();
+ assertThat(nextStartedActivity.getStringExtra("foo")).named("Foo extra")
.isEqualTo("bar");
}
diff --git a/tests/robotests/src/com/android/settings/security/EncryptionStatusPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/security/EncryptionStatusPreferenceControllerTest.java
index a53ee42..b042736 100644
--- a/tests/robotests/src/com/android/settings/security/EncryptionStatusPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/security/EncryptionStatusPreferenceControllerTest.java
@@ -16,6 +16,10 @@
package com.android.settings.security;
+import static com.android.settings.security.EncryptionStatusPreferenceController
+ .PREF_KEY_ENCRYPTION_DETAIL_PAGE;
+import static com.android.settings.security.EncryptionStatusPreferenceController
+ .PREF_KEY_ENCRYPTION_SECURITY_PAGE;
import static com.google.common.truth.Truth.assertThat;
import android.content.Context;
@@ -48,7 +52,8 @@
@Before
public void setUp() {
mContext = RuntimeEnvironment.application;
- mController = new EncryptionStatusPreferenceController(mContext);
+ mController = new EncryptionStatusPreferenceController(mContext,
+ PREF_KEY_ENCRYPTION_DETAIL_PAGE);
mPreference = new Preference(mContext);
}
@@ -85,6 +90,21 @@
assertThat(mPreference.getSummary())
.isEqualTo(mContext.getText(R.string.summary_placeholder));
+ assertThat(mController.getPreferenceKey()).isNotEqualTo(PREF_KEY_ENCRYPTION_SECURITY_PAGE);
assertThat(mPreference.getFragment()).isEqualTo(CryptKeeperSettings.class.getName());
}
+
+ @Test
+ public void updateSummary_unencrypted_securityPage_shouldNotHaveEncryptionFragment() {
+ mController = new EncryptionStatusPreferenceController(mContext,
+ PREF_KEY_ENCRYPTION_SECURITY_PAGE);
+ ShadowLockPatternUtils.setDeviceEncryptionEnabled(false);
+
+ mController.updateState(mPreference);
+
+ assertThat(mPreference.getSummary())
+ .isEqualTo(mContext.getText(R.string.summary_placeholder));
+
+ assertThat(mPreference.getFragment()).isNotEqualTo(CryptKeeperSettings.class.getName());
+ }
}
diff --git a/tests/robotests/src/com/android/settings/security/LockUnificationPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/security/LockUnificationPreferenceControllerTest.java
new file mode 100644
index 0000000..7a5a9fa
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/security/LockUnificationPreferenceControllerTest.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.FakeFeatureFactory;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+import org.robolectric.shadows.ShadowApplication;
+import org.robolectric.util.ReflectionHelpers;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class LockUnificationPreferenceControllerTest {
+
+ private static final int FAKE_PROFILE_USER_ID = 1234;
+
+ @Mock
+ private LockPatternUtils mLockPatternUtils;
+ @Mock
+ private UserManager mUm;
+ @Mock
+ private PreferenceScreen mScreen;
+ @Mock
+ private SecuritySettingsV2 mHost;
+
+ private FakeFeatureFactory mFeatureFactory;
+ private Context mContext;
+ private LockUnificationPreferenceController mController;
+ private Preference mPreference;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = RuntimeEnvironment.application;
+ ShadowApplication.getInstance().setSystemService(Context.USER_SERVICE, mUm);
+ when(mUm.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[] {FAKE_PROFILE_USER_ID});
+
+ mFeatureFactory = FakeFeatureFactory.setupForTest();
+ when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
+ .thenReturn(mLockPatternUtils);
+
+ mController = new LockUnificationPreferenceController(mContext, mHost);
+ when(mScreen.findPreference(mController.getPreferenceKey()))
+ .thenReturn(mPreference);
+ mPreference = new Preference(mContext);
+ }
+
+ @Test
+ public void isAvailable_noProfile_false() {
+ ReflectionHelpers.setField(mController, "mProfileChallengeUserId", UserHandle.USER_NULL);
+
+ assertThat(mController.isAvailable()).isFalse();
+ }
+
+ @Test
+ public void isAvailable_separateChallengeNotAllowed_false() {
+ when(mLockPatternUtils.isSeparateProfileChallengeAllowed(anyInt())).thenReturn(false);
+
+ assertThat(mController.isAvailable()).isFalse();
+ }
+
+ @Test
+ public void isAvailable_separateChallengeAllowed_true() {
+ when(mLockPatternUtils.isSeparateProfileChallengeAllowed(anyInt())).thenReturn(true);
+
+ assertThat(mController.isAvailable()).isTrue();
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/security/ScreenPinningPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/security/ScreenPinningPreferenceControllerTest.java
new file mode 100644
index 0000000..797e7d0
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/security/ScreenPinningPreferenceControllerTest.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+import static com.android.settings.core.BasePreferenceController.AVAILABLE;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.provider.Settings;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.settings.R;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.FakeFeatureFactory;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class ScreenPinningPreferenceControllerTest {
+
+ @Mock
+ private PreferenceScreen mScreen;
+
+ private FakeFeatureFactory mFeatureFactory;
+ private Context mContext;
+ private ScreenPinningPreferenceController mController;
+ private Preference mPreference;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = RuntimeEnvironment.application;
+ mFeatureFactory = FakeFeatureFactory.setupForTest();
+ mController = new ScreenPinningPreferenceController(mContext);
+ mPreference = new Preference(mContext);
+ mPreference.setKey(mController.getPreferenceKey());
+ when(mScreen.findPreference(mController.getPreferenceKey()))
+ .thenReturn(mPreference);
+ }
+
+ @After
+ public void tearDown() {
+ Settings.System.putInt(mContext.getContentResolver(),
+ Settings.System.LOCK_TO_APP_ENABLED, 0);
+ }
+
+ @Test
+ public void isAlwaysAvailable() {
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
+ }
+
+ @Test
+ public void displayPreference_isOff_shouldDisableOffSummary() {
+ Settings.System.putInt(mContext.getContentResolver(),
+ Settings.System.LOCK_TO_APP_ENABLED, 0);
+
+ mController.displayPreference(mScreen);
+
+ assertThat(mPreference.getSummary())
+ .isEqualTo(mContext.getString(R.string.switch_off_text));
+ }
+
+ @Test
+ public void displayPreference_isOn_shouldDisableOnSummary() {
+ Settings.System.putInt(mContext.getContentResolver(),
+ Settings.System.LOCK_TO_APP_ENABLED, 1);
+
+ mController.displayPreference(mScreen);
+
+ assertThat(mPreference.getSummary())
+ .isEqualTo(mContext.getString(R.string.switch_on_text));
+ }
+
+}
diff --git a/tests/robotests/src/com/android/settings/security/SecuritySettingsTest.java b/tests/robotests/src/com/android/settings/security/SecuritySettingsTest.java
index 231cce9..3171c3d 100644
--- a/tests/robotests/src/com/android/settings/security/SecuritySettingsTest.java
+++ b/tests/robotests/src/com/android/settings/security/SecuritySettingsTest.java
@@ -17,32 +17,26 @@
package com.android.settings.security;
import static com.google.common.truth.Truth.assertThat;
-
import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import android.app.Activity;
import android.content.Context;
-import android.content.pm.PackageManager;
-import android.hardware.fingerprint.FingerprintManager;
import android.os.UserHandle;
import android.os.UserManager;
import android.os.UserManager.EnforcingUser;
import android.support.v7.preference.Preference;
-import android.support.v7.preference.PreferenceGroup;
import android.support.v7.preference.PreferenceScreen;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.R;
import com.android.settings.TestConfig;
import com.android.settings.dashboard.SummaryLoader;
-import com.android.settings.notification.LockScreenNotificationPreferenceController;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.XmlTestUtils;
@@ -90,54 +84,6 @@
}
@Test
- public void testSummaryProvider_notListening() {
- mSummaryProvider.setListening(false);
-
- verifyNoMoreInteractions(mSummaryLoader);
- }
-
- @Test
- public void testSummaryProvider_hasFingerPrint_hasStaticSummary() {
- final FingerprintManager fpm = mock(FingerprintManager.class);
- when(mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
- .thenReturn(true);
-
- // Cast to Object to workaround a robolectric casting bug
- when((Object) mContext.getSystemService(FingerprintManager.class)).thenReturn(fpm);
- when(fpm.isHardwareDetected()).thenReturn(true);
-
- mSummaryProvider.setListening(true);
-
- verify(mContext).getString(R.string.security_dashboard_summary);
- }
-
- @Test
- public void testSummaryProvider_noFpFeature_shouldSetSummaryWithNoFingerprint() {
- final FingerprintManager fpm = mock(FingerprintManager.class);
- when(mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
- .thenReturn(false);
-
- mSummaryProvider.setListening(true);
-
- verify(mContext).getString(R.string.security_dashboard_summary_no_fingerprint);
- }
-
- @Test
- public void testSummaryProvider_noFpHardware_shouldSetSummaryWithNoFingerprint() {
- final FingerprintManager fpm = mock(FingerprintManager.class);
- when(mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
- .thenReturn(true);
-
- // Cast to Object to workaround a robolectric casting bug
- when((Object) mContext.getSystemService(FingerprintManager.class)).thenReturn(fpm);
- when(fpm.isHardwareDetected()).thenReturn(false);
-
- mSummaryProvider.setListening(true);
-
- verify(mContext).getString(R.string.security_dashboard_summary_no_fingerprint);
- }
-
- @Test
public void testInitTrustAgentPreference_secure_shouldSetSummaryToNumberOfTrustAgent() {
final Preference preference = mock(Preference.class);
final PreferenceScreen screen = mock(PreferenceScreen.class);
@@ -162,24 +108,6 @@
}
@Test
- public void testSetLockscreenPreferencesSummary_shouldSetSummaryFromLockScreenNotification() {
- final Preference preference = mock(Preference.class);
- final PreferenceGroup group = mock(PreferenceGroup.class);
- when(group.findPreference(SecuritySettings.KEY_LOCKSCREEN_PREFERENCES))
- .thenReturn(preference);
- final LockScreenNotificationPreferenceController controller =
- mock(LockScreenNotificationPreferenceController.class);
-
- final SecuritySettings securitySettings = new SecuritySettings();
- ReflectionHelpers.setField(securitySettings,
- "mLockScreenNotificationPreferenceController", controller);
-
- when(controller.getSummaryResource()).thenReturn(1234);
- securitySettings.setLockscreenPreferencesSummary(group);
- verify(preference).setSummary(1234);
- }
-
- @Test
public void testNonIndexableKeys_existInXmlLayout() {
final Context context = spy(RuntimeEnvironment.application);
UserManager manager = mock(UserManager.class);
diff --git a/tests/robotests/src/com/android/settings/security/SecuritySettingsV2Test.java b/tests/robotests/src/com/android/settings/security/SecuritySettingsV2Test.java
new file mode 100644
index 0000000..f77903b
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/security/SecuritySettingsV2Test.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.hardware.fingerprint.FingerprintManager;
+
+import com.android.settings.R;
+import com.android.settings.TestConfig;
+import com.android.settings.dashboard.SummaryLoader;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+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;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class SecuritySettingsV2Test {
+
+ @Mock(answer = Answers.RETURNS_DEEP_STUBS)
+ private Context mContext;
+ @Mock
+ private SummaryLoader mSummaryLoader;
+ @Mock
+ private FingerprintManager mFingerprintManager;
+ private SecuritySettings.SummaryProvider mSummaryProvider;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ when(mContext.getSystemService(Context.FINGERPRINT_SERVICE))
+ .thenReturn(mFingerprintManager);
+
+ mSummaryProvider = new SecuritySettings.SummaryProvider(mContext, mSummaryLoader);
+ }
+
+ @Test
+ public void testSummaryProvider_notListening() {
+ mSummaryProvider.setListening(false);
+
+ verifyNoMoreInteractions(mSummaryLoader);
+ }
+
+ @Test
+ public void testSummaryProvider_hasFingerPrint_hasStaticSummary() {
+ when(mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
+ .thenReturn(true);
+ when(mFingerprintManager.isHardwareDetected()).thenReturn(true);
+
+ mSummaryProvider.setListening(true);
+
+ verify(mContext).getString(R.string.security_dashboard_summary);
+ }
+
+ @Test
+ public void testSummaryProvider_noFpFeature_shouldSetSummaryWithNoFingerprint() {
+ when(mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
+ .thenReturn(false);
+
+ mSummaryProvider.setListening(true);
+
+ verify(mContext).getString(R.string.security_dashboard_summary_no_fingerprint);
+ }
+
+ @Test
+ public void testSummaryProvider_noFpHardware_shouldSetSummaryWithNoFingerprint() {
+ when(mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT))
+ .thenReturn(true);
+ when(mFingerprintManager.isHardwareDetected()).thenReturn(false);
+
+ mSummaryProvider.setListening(true);
+
+ verify(mContext).getString(R.string.security_dashboard_summary_no_fingerprint);
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/security/ShowPasswordPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/security/ShowPasswordPreferenceControllerTest.java
new file mode 100644
index 0000000..63cf00b
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/security/ShowPasswordPreferenceControllerTest.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+
+import static com.android.settings.core.BasePreferenceController.AVAILABLE;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.os.UserHandle;
+import android.provider.Settings;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.FakeFeatureFactory;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class ShowPasswordPreferenceControllerTest {
+
+ @Mock
+ private LockPatternUtils mLockPatternUtils;
+ @Mock
+ private PreferenceScreen mScreen;
+
+ private FakeFeatureFactory mFeatureFactory;
+ private Context mContext;
+ private ShowPasswordPreferenceController mController;
+ private Preference mPreference;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = RuntimeEnvironment.application;
+ mFeatureFactory = FakeFeatureFactory.setupForTest();
+ when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
+ .thenReturn(mLockPatternUtils);
+ mController = new ShowPasswordPreferenceController(mContext);
+ mPreference = new Preference(mContext);
+ mPreference.setKey(mController.getPreferenceKey());
+ when(mScreen.findPreference(mController.getPreferenceKey()))
+ .thenReturn(mPreference);
+ }
+
+ @Test
+ public void isAlwaysAvailable() {
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
+ }
+
+ @Test
+ public void isChecked_settingIsOff_false() {
+ Settings.System.putInt(mContext.getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,
+ 0);
+
+ assertThat(mController.isChecked()).isFalse();
+ }
+
+ @Test
+ public void isChecked_settingIsOn_true() {
+ Settings.System.putInt(mContext.getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,
+ 1);
+ assertThat(mController.isChecked()).isTrue();
+ }
+
+ @Test
+ public void changePref_turnOn_shouldChangeSettingTo1() {
+ mController.onPreferenceChange(mPreference, true);
+
+ assertThat(mController.isChecked()).isTrue();
+ verify(mLockPatternUtils).setVisiblePasswordEnabled(true, UserHandle.myUserId());
+ }
+
+ @Test
+ public void changePref_turnOff_shouldChangeSettingTo0() {
+ mController.onPreferenceChange(mPreference, false);
+
+ assertThat(mController.isChecked()).isFalse();
+ verify(mLockPatternUtils).setVisiblePasswordEnabled(false, UserHandle.myUserId());
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/security/SimLockPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/security/SimLockPreferenceControllerTest.java
new file mode 100644
index 0000000..a3a4fe3
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/security/SimLockPreferenceControllerTest.java
@@ -0,0 +1,163 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+import static android.telephony.TelephonyManager.SIM_STATE_READY;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.os.PersistableBundle;
+import android.os.UserManager;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+import android.telephony.CarrierConfigManager;
+import android.telephony.SubscriptionInfo;
+import android.telephony.SubscriptionManager;
+import android.telephony.TelephonyManager;
+
+import com.android.settings.TestConfig;
+import com.android.settings.core.BasePreferenceController;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+import org.robolectric.shadows.ShadowApplication;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class SimLockPreferenceControllerTest {
+
+ @Mock
+ private SubscriptionManager mSubscriptionManager;
+ @Mock
+ private CarrierConfigManager mCarrierManager;
+ @Mock
+ private UserManager mUserManager;
+ @Mock
+ private TelephonyManager mTelephonyManager;
+ @Mock
+ private PreferenceScreen mScreen;
+
+ private Context mContext;
+ private SimLockPreferenceController mController;
+ private Preference mPreference;
+
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = RuntimeEnvironment.application;
+ ShadowApplication shadowApplication = ShadowApplication.getInstance();
+ shadowApplication.setSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE,
+ mSubscriptionManager);
+ shadowApplication.setSystemService(Context.CARRIER_CONFIG_SERVICE, mCarrierManager);
+ shadowApplication.setSystemService(Context.USER_SERVICE, mUserManager);
+ shadowApplication.setSystemService(Context.TELEPHONY_SERVICE, mTelephonyManager);
+ mController = new SimLockPreferenceController(mContext);
+ mPreference = new Preference(mContext);
+ mPreference.setKey(mController.getPreferenceKey());
+ when(mScreen.findPreference(mController.getPreferenceKey()))
+ .thenReturn(mPreference);
+ }
+
+ @Test
+ public void isAvailable_notAdmin_false() {
+ when(mUserManager.isAdminUser()).thenReturn(false);
+
+ assertThat(mController.getAvailabilityStatus())
+ .isEqualTo(BasePreferenceController.DISABLED_FOR_USER);
+ }
+
+ @Test
+ public void isAvailable_simIccNotReady_false() {
+ when(mUserManager.isAdminUser()).thenReturn(true);
+
+ assertThat(mController.getAvailabilityStatus())
+ .isEqualTo(BasePreferenceController.DISABLED_FOR_USER);
+ }
+
+ @Test
+ public void isAvailable_carrierConfigDisabled_false() {
+ when(mUserManager.isAdminUser()).thenReturn(true);
+ setupMockIcc();
+ final PersistableBundle pb = new PersistableBundle();
+ pb.putBoolean(CarrierConfigManager.KEY_HIDE_SIM_LOCK_SETTINGS_BOOL, true);
+ when(mCarrierManager.getConfig()).thenReturn(pb);
+
+ assertThat(mController.getAvailabilityStatus())
+ .isEqualTo(BasePreferenceController.DISABLED_FOR_USER);
+ }
+
+ @Test
+ public void isAvailable_true() {
+ when(mUserManager.isAdminUser()).thenReturn(true);
+ setupMockIcc();
+ final PersistableBundle pb = new PersistableBundle();
+ when(mCarrierManager.getConfig()).thenReturn(pb);
+
+ assertThat(mController.getAvailabilityStatus())
+ .isEqualTo(BasePreferenceController.AVAILABLE);
+ }
+
+ @Test
+ public void displayPreference_simReady_enablePreference() {
+ mController.displayPreference(mScreen);
+
+ assertThat(mPreference.isEnabled()).isFalse();
+ }
+
+ @Test
+ public void displayPreference_simNotReady_disablePreference() {
+ setupMockSimReady();
+
+ mController.displayPreference(mScreen);
+
+ assertThat(mPreference.isEnabled()).isTrue();
+ }
+
+ private void setupMockIcc() {
+ final List<SubscriptionInfo> subscriptionInfoList = new ArrayList<>();
+ SubscriptionInfo info = mock(SubscriptionInfo.class);
+ subscriptionInfoList.add(info);
+ when(mTelephonyManager.hasIccCard(anyInt()))
+ .thenReturn(true);
+ when(mSubscriptionManager.getActiveSubscriptionInfoList())
+ .thenReturn(subscriptionInfoList);
+ }
+
+ private void setupMockSimReady() {
+ final List<SubscriptionInfo> subscriptionInfoList = new ArrayList<>();
+ SubscriptionInfo info = mock(SubscriptionInfo.class);
+ subscriptionInfoList.add(info);
+ when(mTelephonyManager.getSimState(anyInt()))
+ .thenReturn(SIM_STATE_READY);
+ when(mSubscriptionManager.getActiveSubscriptionInfoList())
+ .thenReturn(subscriptionInfoList);
+ }
+
+}
diff --git a/tests/robotests/src/com/android/settings/security/VisiblePatternProfilePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/security/VisiblePatternProfilePreferenceControllerTest.java
new file mode 100644
index 0000000..dd98372
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/security/VisiblePatternProfilePreferenceControllerTest.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2018 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.security;
+
+
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
+import static com.android.settings.core.BasePreferenceController.AVAILABLE;
+import static com.android.settings.core.BasePreferenceController.DISABLED_FOR_USER;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.pm.PackageManager;
+import android.hardware.fingerprint.FingerprintManager;
+import android.os.UserManager;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.FakeFeatureFactory;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settingslib.core.lifecycle.Lifecycle;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+import org.robolectric.shadows.ShadowApplication;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class VisiblePatternProfilePreferenceControllerTest {
+
+ private static final int FAKE_PROFILE_USER_ID = 1234;
+
+ @Mock
+ private PackageManager mPackageManager;
+ @Mock
+ private LockPatternUtils mLockPatternUtils;
+ @Mock
+ private FingerprintManager mFingerprintManager;
+ @Mock
+ private UserManager mUm;
+
+ private Lifecycle mLifecycle;
+ private FakeFeatureFactory mFeatureFactory;
+ private Context mContext;
+ private VisiblePatternProfilePreferenceController mController;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application);
+ when(mContext.getPackageManager()).thenReturn(mPackageManager);
+ when(mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)).thenReturn(true);
+ ShadowApplication.getInstance().setSystemService(Context.FINGERPRINT_SERVICE,
+ mFingerprintManager);
+ ShadowApplication.getInstance().setSystemService(Context.USER_SERVICE, mUm);
+
+ mFeatureFactory = FakeFeatureFactory.setupForTest();
+ when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
+ .thenReturn(mLockPatternUtils);
+ when(mUm.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[] {FAKE_PROFILE_USER_ID});
+
+ mLifecycle = new Lifecycle(() -> mLifecycle);
+ mController = new VisiblePatternProfilePreferenceController(mContext, mLifecycle);
+ }
+
+ @Test
+ public void getAvailabilityStatus_notSecure_DISABLED() {
+ when(mLockPatternUtils.isSecure(FAKE_PROFILE_USER_ID)).thenReturn(false);
+ when(mLockPatternUtils.getKeyguardStoredPasswordQuality(FAKE_PROFILE_USER_ID))
+ .thenReturn(PASSWORD_QUALITY_UNSPECIFIED);
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_FOR_USER);
+ }
+
+ @Test
+ public void getAvailabilityStatus_secureWithPassword_DISABLED() {
+ when(mLockPatternUtils.isSecure(FAKE_PROFILE_USER_ID)).thenReturn(true);
+ when(mLockPatternUtils.getKeyguardStoredPasswordQuality(FAKE_PROFILE_USER_ID))
+ .thenReturn(PASSWORD_QUALITY_ALPHABETIC);
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_FOR_USER);
+ }
+
+ @Test
+ public void getAvailabilityStatus_secureWithPattern_AVAILABLE() {
+ when(mLockPatternUtils.isSecure(FAKE_PROFILE_USER_ID)).thenReturn(true);
+ when(mLockPatternUtils.getKeyguardStoredPasswordQuality(FAKE_PROFILE_USER_ID))
+ .thenReturn(PASSWORD_QUALITY_SOMETHING);
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/security/screenlock/LockScreenPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/security/screenlock/LockScreenPreferenceControllerTest.java
new file mode 100644
index 0000000..671807b
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/security/screenlock/LockScreenPreferenceControllerTest.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2018 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.security.screenlock;
+
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC;
+import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
+import static android.arch.lifecycle.Lifecycle.Event.ON_RESUME;
+import static com.android.settings.core.BasePreferenceController.AVAILABLE;
+import static com.android.settings.core.BasePreferenceController.DISABLED_FOR_USER;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.os.UserManager;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.FakeFeatureFactory;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settingslib.core.lifecycle.Lifecycle;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+import org.robolectric.shadows.ShadowApplication;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class LockScreenPreferenceControllerTest {
+
+ private static final int FAKE_PROFILE_USER_ID = 1234;
+
+ @Mock
+ private LockPatternUtils mLockPatternUtils;
+ @Mock
+ private UserManager mUm;
+ @Mock
+ private PreferenceScreen mScreen;
+
+ private Lifecycle mLifecycle;
+ private FakeFeatureFactory mFeatureFactory;
+ private Context mContext;
+ private LockScreenPreferenceController mController;
+ private Preference mPreference;
+
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = RuntimeEnvironment.application;
+ ShadowApplication.getInstance().setSystemService(Context.USER_SERVICE, mUm);
+
+ mFeatureFactory = FakeFeatureFactory.setupForTest();
+ when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
+ .thenReturn(mLockPatternUtils);
+ when(mUm.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[] {FAKE_PROFILE_USER_ID});
+ mPreference = new Preference(mContext);
+ when(mScreen.findPreference(anyString())).thenReturn(mPreference);
+ mLifecycle = new Lifecycle(() -> mLifecycle);
+ mController = new LockScreenPreferenceController(mContext, mLifecycle);
+
+ }
+
+ @Test
+ public void getAvailabilityStatus_notSecure_lockscreenDisabled_DISABLED() {
+ when(mLockPatternUtils.isSecure(anyInt())).thenReturn(false);
+ when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(true);
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_FOR_USER);
+ }
+
+ @Test
+ public void getAvailabilityStatus_notSecure_lockscreenEnabled_AVAILABLE() {
+ when(mLockPatternUtils.isSecure(anyInt())).thenReturn(false);
+ when(mLockPatternUtils.isLockScreenDisabled(anyInt())).thenReturn(false);
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
+ }
+
+ @Test
+ public void getAvailabilityStatus_secure_hasLockScreen_AVAILABLE() {
+ when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
+ when(mLockPatternUtils.getKeyguardStoredPasswordQuality(anyInt()))
+ .thenReturn(PASSWORD_QUALITY_ALPHABETIC);
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
+ }
+
+ @Test
+ public void getAvailabilityStatus_secure_noLockScreen_DISABLED() {
+ when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
+ when(mLockPatternUtils.getKeyguardStoredPasswordQuality(anyInt()))
+ .thenReturn(PASSWORD_QUALITY_UNSPECIFIED);
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_FOR_USER);
+ }
+
+ @Test
+ public void onResume_available_shouldShow() {
+ when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
+ when(mLockPatternUtils.getKeyguardStoredPasswordQuality(anyInt()))
+ .thenReturn(PASSWORD_QUALITY_ALPHABETIC);
+
+ mController.displayPreference(mScreen);
+ mLifecycle.handleLifecycleEvent(ON_RESUME);
+
+ assertThat(mPreference.isVisible()).isTrue();
+ }
+
+ @Test
+ public void onResume_unavailable_shouldHide() {
+ when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
+ when(mLockPatternUtils.getKeyguardStoredPasswordQuality(anyInt()))
+ .thenReturn(PASSWORD_QUALITY_UNSPECIFIED);
+
+ mController.displayPreference(mScreen);
+ mLifecycle.handleLifecycleEvent(ON_RESUME);
+
+ assertThat(mPreference.isVisible()).isFalse();
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/security/screenlock/ScreenLockSettingsTest.java b/tests/robotests/src/com/android/settings/security/screenlock/ScreenLockSettingsTest.java
index 4213fc5..374b7ec 100644
--- a/tests/robotests/src/com/android/settings/security/screenlock/ScreenLockSettingsTest.java
+++ b/tests/robotests/src/com/android/settings/security/screenlock/ScreenLockSettingsTest.java
@@ -33,6 +33,8 @@
import org.robolectric.annotation.Config;
import org.robolectric.util.ReflectionHelpers;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Map;
@RunWith(SettingsRobolectricTestRunner.class)
@@ -55,10 +57,12 @@
@Test
public void onOwnerInfoUpdated_shouldUpdateOwnerInfoController() {
- final Map<Class, AbstractPreferenceController> preferenceControllers =
+ final Map<Class, List<AbstractPreferenceController>> preferenceControllers =
ReflectionHelpers.getField(mSettings, "mPreferenceControllers");
final OwnerInfoPreferenceController controller = mock(OwnerInfoPreferenceController.class);
- preferenceControllers.put(OwnerInfoPreferenceController.class, controller);
+ List<AbstractPreferenceController> controllerList = new ArrayList<>();
+ controllerList.add(controller);
+ preferenceControllers.put(OwnerInfoPreferenceController.class, controllerList);
mSettings.onOwnerInfoUpdated();
diff --git a/tests/robotests/src/com/android/settings/security/trustagent/ManageTrustAgentsPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/security/trustagent/ManageTrustAgentsPreferenceControllerTest.java
new file mode 100644
index 0000000..8818602
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/security/trustagent/ManageTrustAgentsPreferenceControllerTest.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2018 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.security.trustagent;
+
+import static com.android.settings.core.BasePreferenceController.AVAILABLE;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.R;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.FakeFeatureFactory;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class ManageTrustAgentsPreferenceControllerTest {
+
+ @Mock
+ private TrustAgentManager mTrustAgentManager;
+ @Mock
+ private LockPatternUtils mLockPatternUtils;
+ @Mock
+ private PreferenceScreen mScreen;
+
+ private FakeFeatureFactory mFeatureFactory;
+ private Context mContext;
+ private ManageTrustAgentsPreferenceController mController;
+ private Preference mPreference;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = RuntimeEnvironment.application;
+ mFeatureFactory = FakeFeatureFactory.setupForTest();
+ when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(mContext))
+ .thenReturn(mLockPatternUtils);
+ when(mFeatureFactory.securityFeatureProvider.getTrustAgentManager())
+ .thenReturn(mTrustAgentManager);
+ mController = new ManageTrustAgentsPreferenceController(mContext);
+ mPreference = new Preference(mContext);
+ mPreference.setKey(mController.getPreferenceKey());
+ when(mScreen.findPreference(mController.getPreferenceKey()))
+ .thenReturn(mPreference);
+ }
+
+ @Test
+ public void isAlwaysAvailable() {
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE);
+ }
+
+ @Test
+ public void displayPreference_isNotSecure_shouldDisablePreference() {
+ when(mLockPatternUtils.isSecure(anyInt())).thenReturn(false);
+
+ mController.displayPreference(mScreen);
+
+ assertThat(mPreference.isEnabled()).isFalse();
+ assertThat(mPreference.getSummary())
+ .isEqualTo(mContext.getString(R.string.disabled_because_no_backup_security));
+ }
+
+ @Test
+ public void displayPreference_isSecure_noTrustAgent_shouldShowGenericSummary() {
+ when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
+ when(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils))
+ .thenReturn(new ArrayList<>());
+
+ mController.displayPreference(mScreen);
+
+ assertThat(mPreference.isEnabled()).isTrue();
+ assertThat(mPreference.getSummary())
+ .isEqualTo(mContext.getString(R.string.manage_trust_agents_summary));
+ }
+
+ @Test
+ public void displayPreference_isSecure_hasTrustAgent_shouldShowDetailedSummary() {
+ when(mLockPatternUtils.isSecure(anyInt())).thenReturn(true);
+ when(mTrustAgentManager.getActiveTrustAgents(mContext, mLockPatternUtils))
+ .thenReturn(Arrays.asList(new TrustAgentManager.TrustAgentComponentInfo()));
+
+ mController.displayPreference(mScreen);
+
+ assertThat(mPreference.isEnabled()).isTrue();
+ assertThat(mPreference.getSummary())
+ .isEqualTo(mContext.getResources().getQuantityString(
+ R.plurals.manage_trust_agents_summary_on, 1, 1));
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/security/trustagent/TrustAgentListPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/security/trustagent/TrustAgentListPreferenceControllerTest.java
new file mode 100644
index 0000000..6913c0c
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/security/trustagent/TrustAgentListPreferenceControllerTest.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2018 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.security.trustagent;
+
+
+import static com.android.settings.security.trustagent.TrustAgentListPreferenceController
+ .PREF_KEY_SECURITY_CATEGORY;
+import static com.android.settings.security.trustagent.TrustAgentListPreferenceController
+ .PREF_KEY_TRUST_AGENT;
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.app.Activity;
+import android.content.ComponentName;
+import android.content.Context;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceCategory;
+import android.support.v7.preference.PreferenceScreen;
+
+import com.android.internal.widget.LockPatternUtils;
+import com.android.settings.TestConfig;
+import com.android.settings.security.SecuritySettingsV2;
+import com.android.settings.testutils.FakeFeatureFactory;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settingslib.core.lifecycle.Lifecycle;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.Robolectric;
+import org.robolectric.annotation.Config;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class TrustAgentListPreferenceControllerTest {
+
+ @Mock
+ private TrustAgentManager mTrustAgentManager;
+ @Mock
+ private LockPatternUtils mLockPatternUtils;
+ @Mock
+ private PreferenceScreen mScreen;
+ @Mock
+ private PreferenceCategory mCategory;
+ @Mock
+ private SecuritySettingsV2 mFragment;
+
+ private Lifecycle mLifecycle;
+ private FakeFeatureFactory mFeatureFactory;
+ private Activity mActivity;
+
+ private TrustAgentListPreferenceController mController;
+
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mActivity = Robolectric.buildActivity(Activity.class).get();
+ mLifecycle = new Lifecycle(() -> mLifecycle);
+ mFeatureFactory = FakeFeatureFactory.setupForTest();
+ when(mFeatureFactory.securityFeatureProvider.getLockPatternUtils(any(Context.class)))
+ .thenReturn(mLockPatternUtils);
+ when(mFeatureFactory.securityFeatureProvider.getTrustAgentManager())
+ .thenReturn(mTrustAgentManager);
+ when(mCategory.getKey()).thenReturn(PREF_KEY_SECURITY_CATEGORY);
+ when(mCategory.getContext()).thenReturn(mActivity);
+ when(mScreen.findPreference(PREF_KEY_SECURITY_CATEGORY))
+ .thenReturn(mCategory);
+ mController = new TrustAgentListPreferenceController(mActivity, mFragment, mLifecycle);
+ }
+
+ @Test
+ public void testConstants() {
+ assertThat(mController.isAvailable()).isTrue();
+ assertThat(mController.getPreferenceKey()).isEqualTo(PREF_KEY_TRUST_AGENT);
+ }
+
+ @Test
+ public void onResume_shouldClearOldAgents() {
+ final Preference oldAgent = new Preference(mActivity);
+ oldAgent.setKey(PREF_KEY_TRUST_AGENT);
+ when(mCategory.findPreference(PREF_KEY_TRUST_AGENT))
+ .thenReturn(oldAgent)
+ .thenReturn(null);
+
+ mController.displayPreference(mScreen);
+ mController.onResume();
+
+ verify(mCategory).removePreference(oldAgent);
+ }
+
+ @Test
+ public void onResume_shouldAddNewAgents() {
+ final List<TrustAgentManager.TrustAgentComponentInfo> agents = new ArrayList<>();
+ final TrustAgentManager.TrustAgentComponentInfo agent = mock(
+ TrustAgentManager.TrustAgentComponentInfo.class);
+ agent.title = "Test_title";
+ agent.summary = "test summary";
+ agent.componentName = new ComponentName("pkg", "agent");
+ agent.admin = null;
+ agents.add(agent);
+ when(mTrustAgentManager.getActiveTrustAgents(mActivity, mLockPatternUtils))
+ .thenReturn(agents);
+
+ mController.displayPreference(mScreen);
+ mController.onResume();
+
+ verify(mCategory, atLeastOnce()).addPreference(any(Preference.class));
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/widget/MasterCheckBoxPreferenceTest.java b/tests/robotests/src/com/android/settings/widget/MasterCheckBoxPreferenceTest.java
new file mode 100644
index 0000000..e6530d5
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/widget/MasterCheckBoxPreferenceTest.java
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2018 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.widget;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+import android.content.Context;
+import android.support.v7.preference.Preference.OnPreferenceChangeListener;
+import android.support.v7.preference.PreferenceViewHolder;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.LinearLayout;
+import android.widget.CheckBox;
+
+import com.android.settings.R;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class MasterCheckBoxPreferenceTest {
+
+ private Context mContext;
+ private MasterCheckBoxPreference mPreference;
+
+ @Before
+ public void setUp() {
+ mContext = RuntimeEnvironment.application;
+ mPreference = new MasterCheckBoxPreference(mContext);
+ }
+
+ @Test
+ public void createNewPreference_shouldSetLayout() {
+ assertThat(mPreference.getWidgetLayoutResource())
+ .isEqualTo(R.layout.preference_widget_master_checkbox);
+ }
+
+ @Test
+ public void setChecked_shouldUpdateCheckBoxCheckedState() {
+ final PreferenceViewHolder holder = PreferenceViewHolder.createInstanceForTests(
+ LayoutInflater.from(mContext).inflate(
+ R.layout.preference_widget_master_checkbox, null));
+ final CheckBox checkBox = (CheckBox) holder.findViewById(R.id.checkboxWidget);
+ mPreference.onBindViewHolder(holder);
+
+ mPreference.setChecked(true);
+ assertThat(checkBox.isChecked()).isTrue();
+
+ mPreference.setChecked(false);
+ assertThat(checkBox.isChecked()).isFalse();
+ }
+
+ @Test
+ public void setEnabled_shouldUpdateCheckBoxEnabledState() {
+ final PreferenceViewHolder holder = PreferenceViewHolder.createInstanceForTests(
+ LayoutInflater.from(mContext).inflate(
+ R.layout.preference_widget_master_checkbox, null));
+ final CheckBox checkBox = (CheckBox) holder.findViewById(R.id.checkboxWidget);
+ mPreference.onBindViewHolder(holder);
+
+ mPreference.setEnabled(true);
+ assertThat(checkBox.isEnabled()).isTrue();
+
+ mPreference.setEnabled(false);
+ assertThat(checkBox.isEnabled()).isFalse();
+ }
+
+ @Test
+ public void clickWidgetView_shouldToggleCheckBox() {
+ final LayoutInflater inflater = LayoutInflater.from(mContext);
+ final PreferenceViewHolder holder = PreferenceViewHolder.createInstanceForTests(
+ inflater.inflate(R.layout.preference_two_target, null));
+ final LinearLayout widgetView = holder.itemView.findViewById(android.R.id.widget_frame);
+ inflater.inflate(R.layout.preference_widget_master_checkbox, widgetView, true);
+ final CheckBox checkBox = (CheckBox) holder.findViewById(R.id.checkboxWidget);
+ mPreference.onBindViewHolder(holder);
+
+ widgetView.performClick();
+ assertThat(checkBox.isChecked()).isTrue();
+
+ widgetView.performClick();
+ assertThat(checkBox.isChecked()).isFalse();
+ }
+
+ @Test
+ public void clickWidgetView_shouldNotToggleCheckBoxIfDisabled() {
+ final LayoutInflater inflater = LayoutInflater.from(mContext);
+ final PreferenceViewHolder holder = PreferenceViewHolder.createInstanceForTests(
+ inflater.inflate(R.layout.preference_two_target, null));
+ final LinearLayout widgetView = holder.itemView.findViewById(android.R.id.widget_frame);
+ inflater.inflate(R.layout.preference_widget_master_checkbox, widgetView, true);
+ final CheckBox checkBox = (CheckBox) holder.findViewById(R.id.checkboxWidget);
+ mPreference.onBindViewHolder(holder);
+ mPreference.setEnabled(false);
+
+ widgetView.performClick();
+ assertThat(checkBox.isChecked()).isFalse();
+ }
+
+ @Test
+ public void clickWidgetView_shouldNotifyPreferenceChanged() {
+ final PreferenceViewHolder holder = PreferenceViewHolder.createInstanceForTests(
+ LayoutInflater.from(mContext).inflate(R.layout.preference_two_target, null));
+ final View widgetView = holder.findViewById(android.R.id.widget_frame);
+ final OnPreferenceChangeListener listener = mock(OnPreferenceChangeListener.class);
+ mPreference.setOnPreferenceChangeListener(listener);
+ mPreference.onBindViewHolder(holder);
+
+ mPreference.setChecked(false);
+ widgetView.performClick();
+ verify(listener).onPreferenceChange(mPreference, true);
+
+ mPreference.setChecked(true);
+ widgetView.performClick();
+ verify(listener).onPreferenceChange(mPreference, false);
+ }
+
+ @Test
+ public void onBindViewHolder_checkBoxShouldHaveContentDescription() {
+ final PreferenceViewHolder holder = PreferenceViewHolder.createInstanceForTests(
+ LayoutInflater.from(mContext)
+ .inflate(R.layout.preference_widget_master_checkbox, null));
+ final CheckBox checkBox = (CheckBox) holder.findViewById(R.id.checkboxWidget);
+ final String label = "TestButton";
+ mPreference.setTitle(label);
+
+ mPreference.onBindViewHolder(holder);
+
+ assertThat(checkBox.getContentDescription()).isEqualTo(label);
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/widget/SwitchBarTest.java b/tests/robotests/src/com/android/settings/widget/SwitchBarTest.java
new file mode 100644
index 0000000..c805761
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/widget/SwitchBarTest.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2018 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.widget;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.robolectric.RuntimeEnvironment.application;
+
+import android.content.Context;
+import android.widget.TextView;
+
+import com.android.settings.R;
+import com.android.settings.TestConfig;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.Robolectric;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class SwitchBarTest {
+
+ private Context mContext;
+ private SwitchBar mBar;
+
+ @Before
+ public void setUp() {
+ mContext = RuntimeEnvironment.application;
+ mBar = new SwitchBar(application, Robolectric.buildAttributeSet().build());
+ }
+
+ @Test
+ public void testDefaultLabels() {
+ int defaultOnText = R.string.switch_on_text;
+ int defaultOffText = R.string.switch_off_text;
+ assertThat(((TextView) mBar.findViewById(R.id.switch_text)).getText())
+ .isEqualTo(mContext.getString(defaultOffText));
+
+ mBar.setChecked(true);
+ assertThat(((TextView) mBar.findViewById(R.id.switch_text)).getText())
+ .isEqualTo(mContext.getString(defaultOnText));
+ }
+
+ @Test
+ public void testCustomLabels() {
+ int onText = R.string.master_clear_progress_text;
+ int offText = R.string.manage_space_text;
+ mBar.setSwitchBarText(onText, offText);
+ assertThat(((TextView) mBar.findViewById(R.id.switch_text)).getText())
+ .isEqualTo(mContext.getString(offText));
+
+ mBar.setChecked(true);
+ assertThat(((TextView) mBar.findViewById(R.id.switch_text)).getText())
+ .isEqualTo(mContext.getString(onText));
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/wifi/ConfigureWifiSettingsTest.java b/tests/robotests/src/com/android/settings/wifi/ConfigureWifiSettingsTest.java
index 687287b..f32177c 100644
--- a/tests/robotests/src/com/android/settings/wifi/ConfigureWifiSettingsTest.java
+++ b/tests/robotests/src/com/android/settings/wifi/ConfigureWifiSettingsTest.java
@@ -45,6 +45,17 @@
}
@Test
+ @Config(qualifiers = "mcc999")
+ public void testNonIndexableKeys_ifPageDisabled_shouldNotIndexResource() {
+ final List<String> niks = ConfigureWifiSettings.SEARCH_INDEX_DATA_PROVIDER
+ .getNonIndexableKeys(mContext);
+ final int xmlId = new ConfigureWifiSettings().getPreferenceScreenResId();
+
+ final List<String> keys = XmlTestUtils.getKeysFromPreferenceXml(mContext, xmlId);
+ assertThat(niks).containsAllIn(keys);
+ }
+
+ @Test
public void testNonIndexableKeys_noConnection_blocksIP() {
ConnectivityManager manager = mock(ConnectivityManager.class);
when(manager.getActiveNetworkInfo()).thenReturn(null);
diff --git a/tests/robotests/src/com/android/settings/wifi/WifiMasterSwitchPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/wifi/WifiMasterSwitchPreferenceControllerTest.java
index f1bca6f..1708e36 100644
--- a/tests/robotests/src/com/android/settings/wifi/WifiMasterSwitchPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/wifi/WifiMasterSwitchPreferenceControllerTest.java
@@ -72,11 +72,18 @@
}
@Test
- public void isAvailable_shouldAlwaysReturnTrue() {
+ public void testWifiMasterSwitch_byDefault_shouldBeShown() {
assertThat(mController.isAvailable()).isTrue();
}
@Test
+ @Config(qualifiers = "mcc999")
+ public void testWifiMasterSwitch_ifDisabled_shouldNotBeShown() {
+ assertThat(mController.isAvailable()).isFalse();
+ }
+
+
+ @Test
public void onResume_shouldRegisterCallback() {
mController.onResume();
diff --git a/tests/robotests/src/com/android/settings/wifi/WifiSettingsTest.java b/tests/robotests/src/com/android/settings/wifi/WifiSettingsTest.java
new file mode 100644
index 0000000..5f34800
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/wifi/WifiSettingsTest.java
@@ -0,0 +1,68 @@
+/*
+ * 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.wifi;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.spy;
+
+import android.content.Context;
+
+import com.android.settings.TestConfig;
+import com.android.settings.search.SearchIndexableRaw;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RuntimeEnvironment;
+import org.robolectric.annotation.Config;
+
+import java.util.List;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class WifiSettingsTest {
+
+ private Context mContext;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = spy(RuntimeEnvironment.application);
+ }
+
+ @Test
+ public void testSearchIndexProvider_shouldIndexFragmentTitle() {
+ final List<SearchIndexableRaw> indexRes =
+ WifiSettings.SEARCH_INDEX_DATA_PROVIDER.getRawDataToIndex(mContext,
+ true /* enabled */);
+
+ assertThat(indexRes).isNotNull();
+ assertThat(indexRes.get(0).key).isEqualTo(WifiSettings.DATA_KEY_REFERENCE);
+ }
+
+ @Test
+ @Config(qualifiers = "mcc999")
+ public void testSearchIndexProvider_ifWifiSettingsNotVisible_shouldNotIndexFragmentTitle() {
+ final List<SearchIndexableRaw> indexRes =
+ WifiSettings.SEARCH_INDEX_DATA_PROVIDER.getRawDataToIndex(mContext,
+ true /* enabled */);
+
+ assertThat(indexRes).isEmpty();
+ }
+}
\ No newline at end of file