Merge "Apply the correct theme to DockPreference"
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 78f4e22..eae5eaa 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -2362,27 +2362,6 @@
android:name="Settings$DataUsageSummaryActivity"
android:label="@string/data_usage_summary_title"
android:icon="@drawable/ic_settings_data_usage"
- android:enabled="false"
- android:taskAffinity="com.android.settings"
- android:parentActivityName="Settings">
- <!-- TODO(b/70950124): add shortcut intent-filter -->
- <intent-filter android:priority="1">
- <action android:name="android.settings.DATA_USAGE_SETTINGS" />
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- <intent-filter android:priority="10">
- <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.wireless" />
- <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
- android:value="com.android.settings.datausage.DataUsageSummary" />
- </activity>
-
- <activity
- android:name="Settings$DataUsageSummaryLegacyActivity"
- android:label="@string/data_usage_summary_title"
- android:icon="@drawable/ic_settings_data_usage"
android:taskAffinity="com.android.settings"
android:parentActivityName="Settings">
<intent-filter android:priority="1">
@@ -2398,11 +2377,10 @@
<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.wireless" />
+ android:value="com.android.settings.category.ia.wireless" />
<meta-data android:name="com.android.settings.FRAGMENT_CLASS"
- android:value="com.android.settings.datausage.DataUsageSummaryLegacy" />
+ android:value="com.android.settings.datausage.DataUsageSummary" />
</activity>
-
<activity
android:name="Settings$MobileDataUsageListActivity"
android:label="@string/cellular_data_usage"
diff --git a/res/layout/battery_header.xml b/res/layout/battery_header.xml
index df45d15..9f5bde9 100644
--- a/res/layout/battery_header.xml
+++ b/res/layout/battery_header.xml
@@ -31,6 +31,7 @@
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="56dp"
+ android:layout_marginEnd="8dp"
android:orientation="vertical">
<TextView
diff --git a/res/layout/battery_history_detail.xml b/res/layout/battery_history_detail.xml
index ea75865..ff83801 100644
--- a/res/layout/battery_history_detail.xml
+++ b/res/layout/battery_history_detail.xml
@@ -49,7 +49,7 @@
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="?android:attr/textColorSecondary"/>
- <com.android.settings.graph.UsageView
+ <com.android.settings.widget.UsageView
android:id="@+id/battery_usage"
android:layout_width="match_parent"
android:layout_height="141dp"
diff --git a/res/layout/battery_usage_graph.xml b/res/layout/battery_usage_graph.xml
index f46ac6a..93001c3 100644
--- a/res/layout/battery_usage_graph.xml
+++ b/res/layout/battery_usage_graph.xml
@@ -33,7 +33,7 @@
android:textSize="36sp"
android:textColor="?android:attr/colorAccent" />
- <com.android.settings.graph.UsageView
+ <com.android.settings.widget.UsageView
android:id="@+id/battery_usage"
android:layout_width="match_parent"
android:layout_height="141dp"
diff --git a/res/layout/color_mode_preview.xml b/res/layout/color_mode_preview.xml
index 2838345..88b8281 100644
--- a/res/layout/color_mode_preview.xml
+++ b/res/layout/color_mode_preview.xml
@@ -21,7 +21,6 @@
<ImageView
android:layout_width="match_parent"
android:layout_height="@dimen/color_mode_preview_height"
- android:paddingBottom="@dimen/color_mode_preview_padding_bottom"
android:scaleType="centerCrop"
android:cropToPadding="true"
android:src="@drawable/color_mode_preview"
diff --git a/res/layout/data_usage_graph.xml b/res/layout/data_usage_graph.xml
index 8f83d14..ef16341 100644
--- a/res/layout/data_usage_graph.xml
+++ b/res/layout/data_usage_graph.xml
@@ -22,7 +22,7 @@
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:orientation="vertical">
- <com.android.settings.graph.UsageView
+ <com.android.settings.widget.UsageView
android:id="@+id/data_usage"
android:layout_width="match_parent"
android:layout_height="@dimen/data_usage_chart_height"
diff --git a/res/layout/preference_dropdown_material_settings.xml b/res/layout/preference_dropdown_material_settings.xml
deleted file mode 100644
index a3f5ab9..0000000
--- a/res/layout/preference_dropdown_material_settings.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.
- -->
-
-
-<!-- Based off frameworks/base/core/res/res/layout/preference_dropdown_material.xml
- except that icon space in this layout is always reserved -->
-<FrameLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
-
- <Spinner
- android:id="@+id/spinner"
- android:layout_width="0dp"
- android:layout_height="wrap_content"
- android:layout_marginStart="@dimen/preference_no_icon_padding_start"
- android:visibility="invisible" />
-
- <include layout="@layout/preference_material"/>
-
-</FrameLayout>
\ No newline at end of file
diff --git a/res/layout/screen_zoom_preview_2.xml b/res/layout/screen_zoom_preview_2.xml
index b61f92a..2cfd9b7 100644
--- a/res/layout/screen_zoom_preview_2.xml
+++ b/res/layout/screen_zoom_preview_2.xml
@@ -17,4 +17,7 @@
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
+ android:padding="32dp"
+ android:numColumns="3"
+ android:gravity="center"
android:importantForAccessibility="noHideDescendants" />
diff --git a/res/layout/screen_zoom_preview_app_icon.xml b/res/layout/screen_zoom_preview_app_icon.xml
index 7d7d983..087afb8 100644
--- a/res/layout/screen_zoom_preview_app_icon.xml
+++ b/res/layout/screen_zoom_preview_app_icon.xml
@@ -14,33 +14,28 @@
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:importantForAccessibility="noHideDescendants">
+<LinearLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal|top"
+ android:gravity="center_horizontal"
+ android:orientation="vertical"
+ android:paddingTop="8dp">
- <LinearLayout
- android:layout_width="@dimen/screen_zoom_preview_app_icon_width"
+ <ImageView
+ android:id="@android:id/icon1"
+ android:layout_width="64dp"
+ android:layout_height="64dp"
+ android:layout_marginBottom="4dp"
+ android:scaleType="fitCenter" />
+
+ <TextView
+ android:id="@android:id/text1"
+ android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal|top"
- android:gravity="center_horizontal"
- android:orientation="vertical"
- android:padding="8dp">
-
- <ImageView
- android:id="@android:id/icon1"
- android:layout_width="64dp"
- android:layout_height="64dp"
- android:layout_marginBottom="4dp"
- android:scaleType="fitCenter" />
-
- <TextView
- android:id="@android:id/text1"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:ellipsize="end"
- android:gravity="center_horizontal|top"
- android:singleLine="true"
- android:textAppearance="@android:style/TextAppearance.Material.Caption" />
- </LinearLayout>
-</FrameLayout>
\ No newline at end of file
+ android:ellipsize="end"
+ android:gravity="center_horizontal|top"
+ android:singleLine="true"
+ android:textAppearance="@android:style/TextAppearance.Material.Caption" />
+</LinearLayout>
\ No newline at end of file
diff --git a/res/layout/usage_view.xml b/res/layout/usage_view.xml
index 8e9c580..c24f289 100644
--- a/res/layout/usage_view.xml
+++ b/res/layout/usage_view.xml
@@ -57,7 +57,7 @@
</LinearLayout>
- <com.android.settings.graph.UsageGraph
+ <com.android.settings.widget.UsageGraph
android:id="@+id/usage_graph"
android:layout_width="match_parent"
android:layout_height="match_parent"
@@ -76,12 +76,11 @@
android:id="@+id/bottom_label_space"
android:layout_width="@dimen/usage_graph_labels_width"
android:layout_height="wrap_content"/>
- <com.android.settings.graph.BottomLabelLayout
+ <com.android.settings.widget.BottomLabelLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
- android:orientation="horizontal"
- android:layoutDirection="ltr">
+ android:orientation="horizontal">
<include android:id="@+id/label_start"
layout="@layout/usage_side_label" />
@@ -93,7 +92,7 @@
<include android:id="@+id/label_end"
layout="@layout/usage_side_label" />
- </com.android.settings.graph.BottomLabelLayout>
+ </com.android.settings.widget.BottomLabelLayout>
</LinearLayout>
</LinearLayout>
diff --git a/res/menu/data_usage.xml b/res/menu/data_usage.xml
deleted file mode 100644
index 9fe6b60..0000000
--- a/res/menu/data_usage.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2011 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.
--->
-
-<menu xmlns:android="http://schemas.android.com/apk/res/android">
- <item
- android:id="@+id/data_usage_menu_cellular_networks"
- android:title="@string/data_usage_menu_cellular_networks" />
-</menu>
diff --git a/res/values/dimens.xml b/res/values/dimens.xml
index e0b8c48..30d1e6c 100755
--- a/res/values/dimens.xml
+++ b/res/values/dimens.xml
@@ -62,7 +62,6 @@
<dimen name="captioning_preview_height">200dp</dimen>
<dimen name="color_mode_preview_height">320dp</dimen>
- <dimen name="color_mode_preview_padding_bottom">40dp</dimen>
<dimen name="ring_progress_bar_thickness">4dp</dimen>
<dimen name="settings_side_margin">0dip</dimen>
@@ -252,7 +251,6 @@
<dimen name="unmount_button_padding">8dp</dimen>
<!-- Display, Screen zoom -->
- <dimen name="screen_zoom_preview_app_icon_width">88dp</dimen>
<dimen name="conversation_message_list_padding">10dp</dimen>
<dimen name="conversation_message_contact_icon_text_size">32sp</dimen>
<dimen name="conversation_message_text_size">16sp</dimen>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 773e17f..f0394c9 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -289,6 +289,8 @@
<string name="bluetooth_notif_message">Tap to pair with <xliff:g id="device_name">%1$s</xliff:g>.</string>
<!-- Item in bluetooth settings screen, used to show the list of received files [CHAR LIMIT=30] -->
<string name="bluetooth_show_received_files">Received files</string>
+ <!-- Item in bluetooth settings screen, used to show the list of Files received via Bluetooth [CHAR LIMIT=NONE] -->
+ <string name="bluetooth_show_files_received_via_bluetooth">Files received via Bluetooth</string>
<!-- Strings for BluetoothDevicePicker [CHAR LIMIT=40]-->
<string name="device_picker">Choose Bluetooth device</string>
@@ -6013,8 +6015,6 @@
<string name="data_usage_menu_auto_sync">Auto-sync data</string>
<!-- Title for menu option to show details for all SIM cards. [CHAR LIMIT=26] -->
<string name="data_usage_menu_sim_cards">SIM cards</string>
- <!-- Title for menu option to show details for all cellular networks. [CHAR LIMIT=26] -->
- <string name="data_usage_menu_cellular_networks">Mobile networks</string>
<!-- Summary String for Cellular data enable toggle. [CHAR LIMIT=33] -->
<string name="data_usage_cellular_data_summary">Paused at limit</string>
@@ -6999,6 +6999,9 @@
<string name="keywords_model_and_hardware">serial number, hardware version</string>
<string name="keywords_android_version">android security patch level, baseband version, kernel version</string>
+ <!-- Search keyword for Device Theme Settings [CHAR LIMIT=NONE] -->
+ <string name="keywords_systemui_theme">dark theme</string>
+
<!-- Search keyword for Send Device Feedback Setting [CHAR LIMIT=NONE] -->
<string name="keywords_device_feedback">bug</string>
@@ -7410,7 +7413,7 @@
<!-- Do not disturb settings, messages, events and reminders title [CHAR LIMIT=100]-->
<string name="zen_msg_event_reminder_title">Messages, events & reminders</string>
<!-- Do not disturb settings, messages, events and reminders footer [CHAR LIMIT=NONE]-->
- <string name="zen_msg_event_reminder_footer">When Do Not Disturb is on, messages, reminders, and events will muted, except for the items you allow above. You can adjust messages settings to allow your friends, family, or other contacts to reach you.</string>
+ <string name="zen_msg_event_reminder_footer">When Do Not Disturb is on, messages, reminders, and events will be muted, except for the items you allow above. You can adjust messages settings to allow your friends, family, or other contacts to reach you.</string>
<!-- Do not disturb onboarding dialog, accept new settings [CHAR LIMIT=30]-->
<string name="zen_onboarding_ok">Done</string>
@@ -7975,9 +7978,15 @@
<!-- [CHAR LIMIT=50] Zen mode settings: All messages summary -->
<string name="zen_mode_all_messages">Messages</string>
+ <!-- [CHAR LIMIT=50] Zen mode settings: Messages option (ie: text messages) -->
+ <string name="zen_mode_all_messages_list">messages</string>
+
<!-- [CHAR LIMIT=50] Zen mode settings: Selected messages summary -->
<string name="zen_mode_selected_messages">Some messages</string>
+ <!-- [CHAR LIMIT=50] Zen mode settings: Selected messages (ie: some text messages are allowed to bypass dnd) -->
+ <string name="zen_mode_selected_messages_list">some messages</string>
+
<!-- [CHAR LIMIT=40] Zen mode settings: Calls or messages option value: From anyone -->
<string name="zen_mode_from_anyone">From anyone</string>
@@ -8002,21 +8011,36 @@
<!-- [CHAR LIMIT=50] Zen mode settings: Alarms option -->
<string name="zen_mode_alarms">Alarms</string>
+ <!-- [CHAR LIMIT=50] Zen mode settings: Alarms option (ie: sound from alarm clock) -->
+ <string name="zen_mode_alarms_list">alarms</string>
+
<!-- [CHAR LIMIT=50] Zen mode settings: Media option -->
<string name="zen_mode_media">Media</string>
+ <!-- [CHAR LIMIT=50] Zen mode settings: Media (ie: sound from video) -->
+ <string name="zen_mode_media_list">media</string>
+
<!-- [CHAR LIMIT=50] Zen mode settings: System option which includes sounds such as touch sounds -->
<string name="zen_mode_system">Touch sounds</string>
+ <!-- [CHAR LIMIT=50] Zen mode settings: System sounds (ie: touch sounds) -->
+ <string name="zen_mode_system_list">touch sounds</string>
+
<!-- [CHAR LIMIT=50] Zen mode settings: Reminders option -->
<string name="zen_mode_reminders">Reminders</string>
+ <!-- [CHAR LIMIT=50] Zen mode settings: Reminders (ie: calendar reminders are allowed to bypass dnd) -->
+ <string name="zen_mode_reminders_list">reminders</string>
+
<!-- [CHAR LIMIT=70] Zen mode settings: Allow reminders toggle title -->
<string name="zen_mode_reminders_title">Allow reminders</string>
<!-- [CHAR LIMIT=50] Zen mode settings: Events option -->
<string name="zen_mode_events">Events</string>
+ <!-- [CHAR LIMIT=50] Zen mode settings: Events (ie: calendar events) -->
+ <string name="zen_mode_events_list">events</string>
+
<!-- [CHAR LIMIT=70] Zen mode settings: Allow events toggle title -->
<string name="zen_mode_events_title">Allow events</string>
@@ -8032,6 +8056,9 @@
<!-- [CHAR LIMIT=50] Zen mode settings: Repeat callers option -->
<string name="zen_mode_repeat_callers">Repeat callers</string>
+ <!-- [CHAR LIMIT=50] Zen mode settings: Repeat callers (ie: repeat callers are allowed to bypass dnd) -->
+ <string name="zen_mode_repeat_callers_list">repeat callers</string>
+
<!-- [CHAR LIMIT=70] Zen mode settings: Allow repeat callers toggle title -->
<string name="zen_mode_repeat_callers_title">Allow repeat callers</string>
@@ -9143,12 +9170,6 @@
<!-- Format string for amount of ethernet data used [CHAR LIMIT=30] -->
<string name="ethernet_data_template"><xliff:g id="amount" example="1 GB">^1</xliff:g> ethernet data</string>
- <!-- Format for a summary describing the amount of data before the user is warned [CHAR LIMIT=NONE] -->
- <string name="cell_warning_only"><xliff:g name="amount" example="1 GB">%1$s</xliff:g> Data warning</string>
-
- <!-- Format for a summary describing the amount of data before the user is warned or limited [CHAR LIMIT=NONE] -->
- <string name="cell_warning_and_limit"><xliff:g name="amount" example="1 GB">%1$s</xliff:g> Data warning / <xliff:g name="amount" example="2 GB">%2$s</xliff:g> Data limit</string>
-
<!-- Title of button and screen for billing cycle preferences [CHAR LIMIT=40] -->
<string name="billing_cycle">Data warning & limit</string>
@@ -9918,6 +9939,9 @@
<!-- Help URI, smart battery page [DO NOT TRANSLATE] -->
<string name="help_uri_smart_battery_settings" translatable="false"></string>
+ <!-- Help URI, prevent ringing gesture [DO NOT TRANSLATE] -->
+ <string name="help_uri_prevent_ringing_gesture" translatable="false"></string>
+
<!-- Title label for dnd suggestion, which is displayed in Settings homepage [CHAR LIMIT=100] -->
<string name="zen_suggestion_title">Update Do Not Disturb</string>
diff --git a/res/values/styles_preference.xml b/res/values/styles_preference.xml
index 6b632ca..a55f5ca 100644
--- a/res/values/styles_preference.xml
+++ b/res/values/styles_preference.xml
@@ -20,27 +20,27 @@
<resources>
<!-- Fragment style -->
- <style name="SettingsPreferenceFragmentStyle" parent="@style/PreferenceFragmentStyle.SettingsBase">
+ <style name="SettingsPreferenceFragmentStyle" parent="@style/PreferenceFragment.Material">
<item name="android:layout">@layout/preference_list_fragment</item>
</style>
- <style name="ApnPreference" parent="Preference.SettingsBase">
+ <style name="ApnPreference" parent="@style/Preference.Material">
<item name="android:layout">@layout/apn_preference_layout</item>
</style>
- <style name="SettingsSeekBarPreference" parent="Preference.SettingsBase">
+ <style name="SettingsSeekBarPreference" parent="@style/Preference.Material">
<item name="android:layout">@layout/preference_widget_seekbar_settings</item>
</style>
- <style name="SyncSwitchPreference" parent="Preference.SettingsBase">
+ <style name="SyncSwitchPreference" parent="@style/Preference.Material">
<item name="android:widgetLayout">@layout/preference_widget_sync_toggle</item>
</style>
- <style name="TwoStateButtonPreference" parent="Preference.SettingsBase">
+ <style name="TwoStateButtonPreference" parent="@style/Preference.Material">
<item name="android:layout">@layout/two_state_button</item>
</style>
- <style name="SettingsMultiSelectListPreference" parent="Preference.SettingsBase">
+ <style name="SettingsMultiSelectListPreference" parent="@style/Preference.Material">
<item name="android:positiveButtonText">@android:string/ok</item>
<item name="android:negativeButtonText">@android:string/cancel</item>
</style>
diff --git a/res/xml/app_and_notification.xml b/res/xml/app_and_notification.xml
index 53e575f..dd661e0 100644
--- a/res/xml/app_and_notification.xml
+++ b/res/xml/app_and_notification.xml
@@ -69,7 +69,7 @@
<Preference
android:key="special_access"
- android:fragment="com.android.settings.applications.SpecialAccessSettings"
+ android:fragment="com.android.settings.applications.specialaccess.SpecialAccessSettings"
android:title="@string/special_access"
android:order="20" />
diff --git a/res/xml/battery_saver_settings.xml b/res/xml/battery_saver_settings.xml
index 0460459..eb4954f 100644
--- a/res/xml/battery_saver_settings.xml
+++ b/res/xml/battery_saver_settings.xml
@@ -29,8 +29,8 @@
<com.android.settings.widget.SeekBarPreference
android:key="battery_saver_seek_bar"
android:title="@string/battery_saver_seekbar_title_placeholder"
- android:max="75"
- android:min="5" />
+ android:max="15"
+ android:min="1" />
<com.android.settings.widget.TwoStateButtonPreference
android:key="battery_saver"
diff --git a/res/xml/connected_devices_advanced.xml b/res/xml/connected_devices_advanced.xml
index 41d3e9b..2ff27c9 100644
--- a/res/xml/connected_devices_advanced.xml
+++ b/res/xml/connected_devices_advanced.xml
@@ -62,7 +62,7 @@
<Preference
android:key="bt_received_files"
android:icon="@drawable/ic_folder_vd_theme_24"
- android:title="@string/bluetooth_show_received_files"/>
+ android:title="@string/bluetooth_show_files_received_via_bluetooth"/>
<PreferenceCategory
android:key="dashboard_tile_placeholder"
diff --git a/res/xml/data_usage_legacy.xml b/res/xml/data_usage_legacy.xml
deleted file mode 100644
index bbe908a..0000000
--- a/res/xml/data_usage_legacy.xml
+++ /dev/null
@@ -1,43 +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.
--->
-
-<PreferenceScreen
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:settings="http://schemas.android.com/apk/res-auto"
- android:key="data_usage_screen"
- android:title="@string/data_usage_summary_title">
-
- <PreferenceCategory
- android:key="data_usage_category"
- android:title="@string/usage">
-
- <com.android.settings.SummaryPreference
- android:key="status_header"
- android:selectable="false" />
-
- <Preference
- android:key="limit_summary"
- android:selectable="false"
- settings:allowDividerBelow="true" />
-
- <com.android.settings.datausage.DataSaverPreference
- android:key="restrict_background_legacy"
- android:title="@string/data_saver_title"
- android:fragment="com.android.settings.datausage.DataSaverSummary" />
-
- </PreferenceCategory>
-
-</PreferenceScreen>
diff --git a/res/xml/display_settings.xml b/res/xml/display_settings.xml
index ec8a197..87d422f 100644
--- a/res/xml/display_settings.xml
+++ b/res/xml/display_settings.xml
@@ -75,6 +75,7 @@
android:key="color_mode"
android:title="@string/color_mode_title"
android:fragment="com.android.settings.display.ColorModePreferenceFragment"
+ settings:controller="com.android.settings.display.ColorModePreferenceController"
settings:keywords="@string/keywords_color_mode" />
<Preference
@@ -140,7 +141,8 @@
android:title="@string/device_theme"
android:entries="@array/systemui_theme_entries"
android:entryValues="@array/systemui_theme_values"
- settings:controller="com.android.settings.display.SystemUiThemePreferenceController" />
+ settings:controller="com.android.settings.display.SystemUiThemePreferenceController"
+ settings:keywords="@string/keywords_systemui_theme" />
<Preference
android:key="vr_display_pref"
diff --git a/res/xml/security_lockscreen_settings.xml b/res/xml/security_lockscreen_settings.xml
index a3fcaee..2cd92c5 100644
--- a/res/xml/security_lockscreen_settings.xml
+++ b/res/xml/security_lockscreen_settings.xml
@@ -31,7 +31,8 @@
<com.android.settingslib.RestrictedSwitchPreference
android:key="security_lockscreen_add_users_when_locked"
- android:title="@string/user_add_on_lockscreen_menu" />
+ android:title="@string/user_add_on_lockscreen_menu"
+ settings:controller="com.android.settings.users.AddUserWhenLockedPreferenceController" />
<com.android.settingslib.RestrictedPreference
android:key="owner_info_settings"
diff --git a/res/xml/special_access.xml b/res/xml/special_access.xml
index d1eb623..2c80e94 100644
--- a/res/xml/special_access.xml
+++ b/res/xml/special_access.xml
@@ -15,16 +15,17 @@
-->
<PreferenceScreen
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:settings="http://schemas.android.com/apk/res-auto"
- android:key="special_app_access_screen"
- android:title="@string/special_access">
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:settings="http://schemas.android.com/apk/res-auto"
+ android:key="special_app_access_screen"
+ android:title="@string/special_access">
<Preference
android:key="high_power_apps"
android:title="@string/high_power_apps"
android:fragment="com.android.settings.applications.manageapplications.ManageApplications"
- settings:keywords="@string/keywords_ignore_optimizations">
+ settings:keywords="@string/keywords_ignore_optimizations"
+ settings:controller="com.android.settings.applications.specialaccess.HighPowerAppsController">
<extra
android:name="classname"
android:value="com.android.settings.Settings$HighPowerApplicationsActivity" />
@@ -33,7 +34,8 @@
<Preference
android:key="device_administrators"
android:title="@string/manage_device_admin"
- android:fragment="com.android.settings.DeviceAdminSettings" />
+ android:fragment="com.android.settings.DeviceAdminSettings"
+ settings:controller="com.android.settings.applications.specialaccess.DeviceAdministratorsController" />
<Preference
android:key="system_alert_window"
@@ -48,7 +50,8 @@
<Preference
android:key="zen_access"
android:title="@string/manage_zen_access_title"
- android:fragment="com.android.settings.notification.ZenAccessSettings" />
+ android:fragment="com.android.settings.notification.ZenAccessSettings"
+ settings:controller="com.android.settings.applications.specialaccess.ZenAccessController" />
<Preference
android:key="write_settings_apps"
@@ -63,23 +66,27 @@
<Preference
android:key="notification_access"
android:title="@string/manage_notification_access_title"
- android:fragment="com.android.settings.notification.NotificationAccessSettings" />
+ android:fragment="com.android.settings.notification.NotificationAccessSettings"
+ settings:controller="com.android.settings.applications.specialaccess.NotificationAccessController" />
<Preference
android:key="picture_in_picture"
android:title="@string/picture_in_picture_title"
android:fragment="com.android.settings.applications.appinfo.PictureInPictureSettings"
- settings:keywords="@string/picture_in_picture_keywords" />
+ settings:keywords="@string/picture_in_picture_keywords"
+ settings:controller="com.android.settings.applications.specialaccess.PictureInPictureController" />
<Preference
android:key="premium_sms"
android:title="@string/premium_sms_access"
- android:fragment="com.android.settings.applications.PremiumSmsAccess" />
+ android:fragment="com.android.settings.applications.PremiumSmsAccess"
+ settings:controller="com.android.settings.applications.specialaccess.PremiumSmsController" />
<Preference
android:key="data_saver"
android:title="@string/unrestricted_data_saver"
- android:fragment="com.android.settings.datausage.UnrestrictedDataAccess" />
+ android:fragment="com.android.settings.datausage.UnrestrictedDataAccess"
+ settings:controller="com.android.settings.applications.specialaccess.DataSaverController" />
<Preference
android:key="manage_external_sources"
@@ -105,7 +112,8 @@
android:key="enabled_vr_listeners"
android:title="@string/vr_listeners_title"
android:fragment="com.android.settings.applications.VrListenerSettings"
- settings:keywords="@string/keywords_vr_listener">
+ settings:keywords="@string/keywords_vr_listener"
+ settings:controller="com.android.settings.applications.specialaccess.EnabledVrListenersController">
<extra
android:name="classname"
android:value="com.android.settings.Settings$VrListenersSettingsActivity" />
diff --git a/src/com/android/settings/DisplaySettings.java b/src/com/android/settings/DisplaySettings.java
index 32d68ba..afdf9d0 100644
--- a/src/com/android/settings/DisplaySettings.java
+++ b/src/com/android/settings/DisplaySettings.java
@@ -23,7 +23,6 @@
import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.display.BrightnessLevelPreferenceController;
import com.android.settings.display.CameraGesturePreferenceController;
-import com.android.settings.display.ColorModePreferenceController;
import com.android.settings.display.LiftToWakePreferenceController;
import com.android.settings.display.NightDisplayPreferenceController;
import com.android.settings.display.NightModePreferenceController;
@@ -94,7 +93,6 @@
controllers.add(new WallpaperPreferenceController(context));
controllers.add(new ThemePreferenceController(context));
controllers.add(new BrightnessLevelPreferenceController(context, lifecycle));
- controllers.add(new ColorModePreferenceController(context));
return controllers;
}
diff --git a/src/com/android/settings/FallbackHome.java b/src/com/android/settings/FallbackHome.java
index 5f7b639..84a3283 100644
--- a/src/com/android/settings/FallbackHome.java
+++ b/src/com/android/settings/FallbackHome.java
@@ -18,6 +18,8 @@
import android.app.Activity;
import android.app.ProgressDialog;
+import android.app.WallpaperColors;
+import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
@@ -68,15 +70,27 @@
// we don't flash the wallpaper before SUW
mProvisioned = Settings.Global.getInt(getContentResolver(),
Settings.Global.DEVICE_PROVISIONED, 0) != 0;
+ int flags;
if (!mProvisioned) {
setTheme(R.style.FallbackHome_SetupWizard);
- getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN
- | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
+ flags = View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
+ | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
} else {
- getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
- | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
+ flags = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+ | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
}
+ // Set the system ui flags to light status bar if the wallpaper supports dark text to match
+ // current system ui color tints.
+ final WallpaperColors colors = getSystemService(WallpaperManager.class)
+ .getWallpaperColors(WallpaperManager.FLAG_SYSTEM);
+ if (colors != null
+ && (colors.getColorHints() & WallpaperColors.HINT_SUPPORTS_DARK_TEXT) != 0) {
+ flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
+ | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR;
+ }
+ getWindow().getDecorView().setSystemUiVisibility(flags);
+
registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_USER_UNLOCKED));
maybeFinish();
}
diff --git a/src/com/android/settings/Settings.java b/src/com/android/settings/Settings.java
index 651c3a7..0d85062 100644
--- a/src/com/android/settings/Settings.java
+++ b/src/com/android/settings/Settings.java
@@ -76,7 +76,6 @@
public static class CryptKeeperSettingsActivity extends SettingsActivity { /* empty */ }
public static class DeviceAdminSettingsActivity extends SettingsActivity { /* empty */ }
public static class DataUsageSummaryActivity extends SettingsActivity { /* empty */ }
- public static class DataUsageSummaryLegacyActivity extends SettingsActivity { /* empty */ }
public static class MobileDataUsageListActivity extends SettingsActivity { /* empty */ }
public static class ConfigureWifiSettingsActivity extends SettingsActivity { /* empty */ }
public static class SavedAccessPointsSettingsActivity extends SettingsActivity { /* empty */ }
diff --git a/src/com/android/settings/SettingsActivity.java b/src/com/android/settings/SettingsActivity.java
index 5d6ea4d..8b9b912 100644
--- a/src/com/android/settings/SettingsActivity.java
+++ b/src/com/android/settings/SettingsActivity.java
@@ -664,17 +664,9 @@
Settings.PowerUsageSummaryActivity.class.getName()),
mBatteryPresent, isAdmin) || somethingChanged;
- final boolean isDataUsageSettingsV2Enabled =
- FeatureFlagUtils.isEnabled(this, FeatureFlags.DATA_USAGE_SETTINGS_V2);
- // Enable new data usage page if v2 enabled
somethingChanged = setTileEnabled(changedList, new ComponentName(packageName,
Settings.DataUsageSummaryActivity.class.getName()),
- Utils.isBandwidthControlEnabled() && isDataUsageSettingsV2Enabled, isAdmin)
- || somethingChanged;
- // Enable legacy data usage page if v2 disabled
- somethingChanged = setTileEnabled(changedList, new ComponentName(packageName,
- Settings.DataUsageSummaryLegacyActivity.class.getName()),
- Utils.isBandwidthControlEnabled() && !isDataUsageSettingsV2Enabled, isAdmin)
+ Utils.isBandwidthControlEnabled(), isAdmin)
|| somethingChanged;
somethingChanged = setTileEnabled(changedList, new ComponentName(packageName,
diff --git a/src/com/android/settings/applications/AppStateNotificationBridge.java b/src/com/android/settings/applications/AppStateNotificationBridge.java
index a96a3b1..6cf64c3 100644
--- a/src/com/android/settings/applications/AppStateNotificationBridge.java
+++ b/src/com/android/settings/applications/AppStateNotificationBridge.java
@@ -15,9 +15,13 @@
*/
package com.android.settings.applications;
+import android.app.usage.IUsageStatsManager;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStatsManager;
import android.content.Context;
+import android.os.RemoteException;
+import android.os.UserHandle;
+import android.os.UserManager;
import android.text.format.DateUtils;
import android.util.ArrayMap;
import android.view.View;
@@ -25,6 +29,7 @@
import android.widget.Switch;
import com.android.settings.R;
+import com.android.settings.Utils;
import com.android.settings.notification.NotificationBackend;
import com.android.settingslib.applications.ApplicationsState;
import com.android.settingslib.applications.ApplicationsState.AppEntry;
@@ -33,6 +38,7 @@
import java.util.ArrayList;
import java.util.Comparator;
+import java.util.List;
import java.util.Map;
/**
@@ -42,17 +48,24 @@
public class AppStateNotificationBridge extends AppStateBaseBridge {
private final Context mContext;
- private UsageStatsManager mUsageStatsManager;
+ private IUsageStatsManager mUsageStatsManager;
+ protected List<Integer> mUserIds;
private NotificationBackend mBackend;
private static final int DAYS_TO_CHECK = 7;
public AppStateNotificationBridge(Context context, ApplicationsState appState,
- Callback callback, UsageStatsManager usageStatsManager,
- NotificationBackend backend) {
+ Callback callback, IUsageStatsManager usageStatsManager,
+ UserManager userManager, NotificationBackend backend) {
super(appState, callback);
mContext = context;
mUsageStatsManager = usageStatsManager;
mBackend = backend;
+ mUserIds = new ArrayList<>();
+ mUserIds.add(mContext.getUserId());
+ int workUserId = Utils.getManagedProfileId(userManager, mContext.getUserId());
+ if (workUserId != UserHandle.USER_NULL) {
+ mUserIds.add(workUserId);
+ }
}
@Override
@@ -62,7 +75,8 @@
final Map<String, NotificationsSentState> map = getAggregatedUsageEvents();
for (AppEntry entry : apps) {
- NotificationsSentState stats = map.get(entry.info.packageName);
+ NotificationsSentState stats =
+ map.get(getKey(UserHandle.getUserId(entry.info.uid), entry.info.packageName));
calculateAvgSentCounts(stats);
addBlockStatus(entry, stats);
entry.extraInfo = stats;
@@ -71,8 +85,8 @@
@Override
protected void updateExtraInfo(AppEntry entry, String pkg, int uid) {
- Map<String, NotificationsSentState> map = getAggregatedUsageEvents();
- NotificationsSentState stats = map.get(entry.info.packageName);
+ NotificationsSentState stats = getAggregatedUsageEvents(
+ UserHandle.getUserId(entry.info.uid), entry.info.packageName);
calculateAvgSentCounts(stats);
addBlockStatus(entry, stats);
entry.extraInfo = stats;
@@ -116,18 +130,59 @@
long now = System.currentTimeMillis();
long startTime = now - (DateUtils.DAY_IN_MILLIS * DAYS_TO_CHECK);
- UsageEvents events = mUsageStatsManager.queryEvents(startTime, now);
+ for (int userId : mUserIds) {
+ UsageEvents events = null;
+ try {
+ events = mUsageStatsManager.queryEventsForUser(
+ startTime, now, userId, mContext.getPackageName());
+ } catch (RemoteException e) {
+ e.printStackTrace();
+ }
+ if (events != null) {
+ UsageEvents.Event event = new UsageEvents.Event();
+ while (events.hasNextEvent()) {
+ events.getNextEvent(event);
+ NotificationsSentState stats =
+ aggregatedStats.get(getKey(userId, event.getPackageName()));
+ if (stats == null) {
+ stats = new NotificationsSentState();
+ aggregatedStats.put(getKey(userId, event.getPackageName()), stats);
+ }
+
+ if (event.getEventType() == UsageEvents.Event.NOTIFICATION_INTERRUPTION) {
+ if (event.getTimeStamp() > stats.lastSent) {
+ stats.lastSent = event.getTimeStamp();
+ }
+ stats.sentCount++;
+ }
+
+ }
+ }
+ }
+ return aggregatedStats;
+ }
+
+ protected NotificationsSentState getAggregatedUsageEvents(int userId, String pkg) {
+ NotificationsSentState stats = null;
+
+ long now = System.currentTimeMillis();
+ long startTime = now - (DateUtils.DAY_IN_MILLIS * DAYS_TO_CHECK);
+ UsageEvents events = null;
+ try {
+ events = mUsageStatsManager.queryEventsForPackageForUser(
+ startTime, now, userId, pkg, mContext.getPackageName());
+ } catch (RemoteException e) {
+ e.printStackTrace();
+ }
if (events != null) {
UsageEvents.Event event = new UsageEvents.Event();
while (events.hasNextEvent()) {
events.getNextEvent(event);
- NotificationsSentState stats = aggregatedStats.get(event.getPackageName());
- if (stats == null) {
- stats = new NotificationsSentState();
- aggregatedStats.put(event.getPackageName(), stats);
- }
if (event.getEventType() == UsageEvents.Event.NOTIFICATION_INTERRUPTION) {
+ if (stats == null) {
+ stats = new NotificationsSentState();
+ }
if (event.getTimeStamp() > stats.lastSent) {
stats.lastSent = event.getTimeStamp();
}
@@ -136,7 +191,7 @@
}
}
- return aggregatedStats;
+ return stats;
}
private static NotificationsSentState getNotificationsSentState(AppEntry entry) {
@@ -149,6 +204,10 @@
return null;
}
+ protected static String getKey(int userId, String pkg) {
+ return userId + "|" + pkg;
+ }
+
public View.OnClickListener getSwitchOnClickListener(final AppEntry entry) {
if (entry != null) {
return v -> {
diff --git a/src/com/android/settings/applications/SpecialAccessSettings.java b/src/com/android/settings/applications/SpecialAccessSettings.java
deleted file mode 100644
index 7679b1f..0000000
--- a/src/com/android/settings/applications/SpecialAccessSettings.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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.
- */
-
-package com.android.settings.applications;
-
-import android.app.ActivityManager;
-import android.content.Context;
-import android.os.Bundle;
-import androidx.annotation.NonNull;
-import android.provider.SearchIndexableResource;
-import androidx.preference.Preference;
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.settings.R;
-import com.android.settings.dashboard.DashboardFragment;
-import com.android.settings.search.BaseSearchIndexProvider;
-import com.android.settings.search.Indexable;
-import com.android.settingslib.core.AbstractPreferenceController;
-import com.android.settingslib.search.SearchIndexable;
-
-import java.util.ArrayList;
-import java.util.List;
-
-@SearchIndexable
-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"};
-
- @Override
- protected String getLogTag() {
- return TAG;
- }
-
- @Override
- protected int getPreferenceScreenResId() {
- return R.xml.special_access;
- }
-
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
-
- if (ActivityManager.isLowRamDeviceStatic()) {
- for (String disabledFeature : DISABLED_FEATURES_LOW_RAM) {
- Preference pref = findPreference(disabledFeature);
- if (pref != null) {
- removePreference(disabledFeature);
- }
- }
- }
- }
-
- @Override
- protected List<AbstractPreferenceController> createPreferenceControllers(Context context) {
- 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
- public int getMetricsCategory() {
- return MetricsEvent.SPECIAL_ACCESS;
- }
-
- public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
- new BaseSearchIndexProvider() {
- @Override
- public List<SearchIndexableResource> getXmlResourcesToIndex(Context context,
- boolean enabled) {
- final ArrayList<SearchIndexableResource> result = new ArrayList<>();
-
- final SearchIndexableResource sir = new SearchIndexableResource(context);
- sir.xmlResId = R.xml.special_access;
- result.add(sir);
- return result;
- }
-
- @Override
- public List<AbstractPreferenceController> createPreferenceControllers(
- Context context) {
- return buildPreferenceControllers(context);
- }
- };
-}
diff --git a/src/com/android/settings/applications/appinfo/AppActionButtonPreferenceController.java b/src/com/android/settings/applications/appinfo/AppActionButtonPreferenceController.java
deleted file mode 100644
index 79c2224..0000000
--- a/src/com/android/settings/applications/appinfo/AppActionButtonPreferenceController.java
+++ /dev/null
@@ -1,321 +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.applications.appinfo;
-
-import android.app.Activity;
-import android.app.ActivityManager;
-import android.app.admin.DevicePolicyManager;
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.os.UserHandle;
-import android.os.UserManager;
-import androidx.annotation.VisibleForTesting;
-import androidx.preference.PreferenceScreen;
-import android.util.Log;
-import android.webkit.IWebViewUpdateService;
-
-import com.android.settings.R;
-import com.android.settings.Utils;
-import com.android.settings.applications.ApplicationFeatureProvider;
-import com.android.settings.core.BasePreferenceController;
-import com.android.settings.overlay.FeatureFactory;
-import com.android.settings.widget.ActionButtonPreference;
-import com.android.settingslib.RestrictedLockUtils;
-import com.android.settingslib.applications.AppUtils;
-import com.android.settingslib.applications.ApplicationsState.AppEntry;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-
-public class AppActionButtonPreferenceController extends BasePreferenceController
- implements AppInfoDashboardFragment.Callback {
-
- private static final String TAG = "AppActionButtonControl";
- private static final String KEY_ACTION_BUTTONS = "action_buttons";
-
- @VisibleForTesting
- ActionButtonPreference mActionButtons;
- private final AppInfoDashboardFragment mParent;
- private final String mPackageName;
- private final HashSet<String> mHomePackages = new HashSet<>();
- private final ApplicationFeatureProvider mApplicationFeatureProvider;
-
- private int mUserId;
- private DevicePolicyManager mDpm;
- private UserManager mUserManager;
- private PackageManager mPm;
-
- private final BroadcastReceiver mCheckKillProcessesReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- final boolean enabled = getResultCode() != Activity.RESULT_CANCELED;
- Log.d(TAG, "Got broadcast response: Restart status for "
- + mParent.getAppEntry().info.packageName + " " + enabled);
- updateForceStopButton(enabled);
- }
- };
-
- public AppActionButtonPreferenceController(Context context, AppInfoDashboardFragment parent,
- String packageName) {
- super(context, KEY_ACTION_BUTTONS);
- mParent = parent;
- mPackageName = packageName;
- mUserId = UserHandle.myUserId();
- mApplicationFeatureProvider = FeatureFactory.getFactory(context)
- .getApplicationFeatureProvider(context);
- }
-
- @Override
- public int getAvailabilityStatus() {
- return AppUtils.isInstant(mParent.getPackageInfo().applicationInfo)
- ? DISABLED_FOR_USER : AVAILABLE;
- }
-
- @Override
- public void displayPreference(PreferenceScreen screen) {
- super.displayPreference(screen);
- mActionButtons = ((ActionButtonPreference) screen.findPreference(KEY_ACTION_BUTTONS))
- .setButton2Text(R.string.force_stop)
- .setButton2Positive(false)
- .setButton2Enabled(false);
- }
-
- @Override
- public void refreshUi() {
- if (mPm == null) {
- mPm = mContext.getPackageManager();
- }
- if (mDpm == null) {
- mDpm = (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
- }
- if (mUserManager == null) {
- mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
- }
- final AppEntry appEntry = mParent.getAppEntry();
- final PackageInfo packageInfo = mParent.getPackageInfo();
-
- // Get list of "home" apps and trace through any meta-data references
- final List<ResolveInfo> homeActivities = new ArrayList<ResolveInfo>();
- mPm.getHomeActivities(homeActivities);
- mHomePackages.clear();
- for (int i = 0; i < homeActivities.size(); i++) {
- final ResolveInfo ri = homeActivities.get(i);
- final String activityPkg = ri.activityInfo.packageName;
- mHomePackages.add(activityPkg);
-
- // Also make sure to include anything proxying for the home app
- final Bundle metadata = ri.activityInfo.metaData;
- if (metadata != null) {
- final String metaPkg = metadata.getString(ActivityManager.META_HOME_ALTERNATE);
- if (signaturesMatch(metaPkg, activityPkg)) {
- mHomePackages.add(metaPkg);
- }
- }
- }
-
- checkForceStop(appEntry, packageInfo);
- initUninstallButtons(appEntry, packageInfo);
- }
-
- @VisibleForTesting
- void initUninstallButtons(AppEntry appEntry, PackageInfo packageInfo) {
- final boolean isBundled = (appEntry.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
- boolean enabled;
- if (isBundled) {
- enabled = handleDisableable(appEntry, packageInfo);
- } else {
- enabled = initUninstallButtonForUserApp();
- }
- // If this is a device admin, it can't be uninstalled or disabled.
- // We do this here so the text of the button is still set correctly.
- if (isBundled && mDpm.packageHasActiveAdmins(packageInfo.packageName)) {
- enabled = false;
- }
-
- // We don't allow uninstalling DO/PO on *any* users, because if it's a system app,
- // "uninstall" is actually "downgrade to the system version + disable", and "downgrade"
- // will clear data on all users.
- if (Utils.isProfileOrDeviceOwner(mUserManager, mDpm, packageInfo.packageName)) {
- enabled = false;
- }
-
- // Don't allow uninstalling the device provisioning package.
- if (Utils.isDeviceProvisioningPackage(mContext.getResources(), appEntry.info.packageName)) {
- enabled = false;
- }
-
- // If the uninstall intent is already queued, disable the uninstall button
- if (mDpm.isUninstallInQueue(mPackageName)) {
- enabled = false;
- }
-
- // Home apps need special handling. Bundled ones we don't risk downgrading
- // because that can interfere with home-key resolution. Furthermore, we
- // can't allow uninstallation of the only home app, and we don't want to
- // allow uninstallation of an explicitly preferred one -- the user can go
- // to Home settings and pick a different one, after which we'll permit
- // uninstallation of the now-not-default one.
- if (enabled && mHomePackages.contains(packageInfo.packageName)) {
- if (isBundled) {
- enabled = false;
- } else {
- ArrayList<ResolveInfo> homeActivities = new ArrayList<ResolveInfo>();
- ComponentName currentDefaultHome = mPm.getHomeActivities(homeActivities);
- if (currentDefaultHome == null) {
- // No preferred default, so permit uninstall only when
- // there is more than one candidate
- enabled = (mHomePackages.size() > 1);
- } else {
- // There is an explicit default home app -- forbid uninstall of
- // that one, but permit it for installed-but-inactive ones.
- enabled = !packageInfo.packageName.equals(currentDefaultHome.getPackageName());
- }
- }
- }
-
- if (RestrictedLockUtils.hasBaseUserRestriction(
- mContext, UserManager.DISALLOW_APPS_CONTROL, mUserId)) {
- enabled = false;
- }
-
- try {
- final IWebViewUpdateService webviewUpdateService =
- IWebViewUpdateService.Stub.asInterface(
- ServiceManager.getService("webviewupdate"));
- if (webviewUpdateService.isFallbackPackage(appEntry.info.packageName)) {
- enabled = false;
- }
- } catch (RemoteException e) {
- throw new RuntimeException(e);
- }
-
- mActionButtons.setButton1Enabled(enabled);
- if (enabled) {
- // Register listener
- mActionButtons.setButton1OnClickListener(v -> mParent.handleUninstallButtonClick());
- }
- }
-
- @VisibleForTesting
- boolean initUninstallButtonForUserApp() {
- boolean enabled = true;
- final PackageInfo packageInfo = mParent.getPackageInfo();
- if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) == 0
- && mUserManager.getUsers().size() >= 2) {
- // When we have multiple users, there is a separate menu
- // to uninstall for all users.
- enabled = false;
- } else if (AppUtils.isInstant(packageInfo.applicationInfo)) {
- enabled = false;
- mActionButtons.setButton1Visible(false);
- }
- mActionButtons.setButton1Text(R.string.uninstall_text).setButton1Positive(false);
- return enabled;
- }
-
- @VisibleForTesting
- boolean handleDisableable(AppEntry appEntry, PackageInfo packageInfo) {
- boolean disableable = false;
- // Try to prevent the user from bricking their phone
- // by not allowing disabling of apps signed with the
- // system cert and any launcher app in the system.
- if (mHomePackages.contains(appEntry.info.packageName)
- || Utils.isSystemPackage(mContext.getResources(), mPm, packageInfo)) {
- // Disable button for core system applications.
- mActionButtons
- .setButton1Text(R.string.disable_text)
- .setButton1Positive(false);
- } else if (appEntry.info.enabled && appEntry.info.enabledSetting
- != PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
- mActionButtons
- .setButton1Text(R.string.disable_text)
- .setButton1Positive(false);
- disableable = !mApplicationFeatureProvider.getKeepEnabledPackages()
- .contains(appEntry.info.packageName);
- } else {
- mActionButtons
- .setButton1Text(R.string.enable_text)
- .setButton1Positive(true);
- disableable = true;
- }
-
- return disableable;
- }
-
- private void updateForceStopButton(boolean enabled) {
- final boolean disallowedBySystem = RestrictedLockUtils.hasBaseUserRestriction(
- mContext, UserManager.DISALLOW_APPS_CONTROL, mUserId);
- mActionButtons
- .setButton2Enabled(disallowedBySystem ? false : enabled)
- .setButton2OnClickListener(
- disallowedBySystem ? null : v -> mParent.handleForceStopButtonClick());
- }
-
- void checkForceStop(AppEntry appEntry, PackageInfo packageInfo) {
- if (mDpm.packageHasActiveAdmins(packageInfo.packageName)) {
- // User can't force stop device admin.
- Log.w(TAG, "User can't force stop device admin");
- updateForceStopButton(false);
- } else if (mPm.isPackageStateProtected(packageInfo.packageName,
- UserHandle.getUserId(appEntry.info.uid))) {
- Log.w(TAG, "User can't force stop protected packages");
- updateForceStopButton(false);
- } else if (AppUtils.isInstant(packageInfo.applicationInfo)) {
- updateForceStopButton(false);
- mActionButtons.setButton2Visible(false);
- } else if ((appEntry.info.flags & ApplicationInfo.FLAG_STOPPED) == 0) {
- // If the app isn't explicitly stopped, then always show the
- // force stop button.
- Log.w(TAG, "App is not explicitly stopped");
- updateForceStopButton(true);
- } else {
- final Intent intent = new Intent(Intent.ACTION_QUERY_PACKAGE_RESTART,
- Uri.fromParts("package", appEntry.info.packageName, null));
- intent.putExtra(Intent.EXTRA_PACKAGES, new String[] {appEntry.info.packageName});
- intent.putExtra(Intent.EXTRA_UID, appEntry.info.uid);
- intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(appEntry.info.uid));
- Log.d(TAG, "Sending broadcast to query restart status for "
- + appEntry.info.packageName);
- mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null,
- mCheckKillProcessesReceiver, null, Activity.RESULT_CANCELED, null, null);
- }
- }
-
- private boolean signaturesMatch(String pkg1, String pkg2) {
- if (pkg1 != null && pkg2 != null) {
- try {
- return mPm.checkSignatures(pkg1, pkg2) >= PackageManager.SIGNATURE_MATCH;
- } catch (Exception e) {
- // e.g. named alternate package not found during lookup;
- // this is an expected case sometimes
- }
- }
- return false;
- }
-
-}
diff --git a/src/com/android/settings/fuelgauge/AppButtonsPreferenceController.java b/src/com/android/settings/applications/appinfo/AppButtonsPreferenceController.java
similarity index 97%
rename from src/com/android/settings/fuelgauge/AppButtonsPreferenceController.java
rename to src/com/android/settings/applications/appinfo/AppButtonsPreferenceController.java
index a2ba9a9..dfbe064 100644
--- a/src/com/android/settings/fuelgauge/AppButtonsPreferenceController.java
+++ b/src/com/android/settings/applications/appinfo/AppButtonsPreferenceController.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.settings.fuelgauge;
+package com.android.settings.applications.appinfo;
import android.app.Activity;
import android.app.ActivityManager;
@@ -49,13 +49,13 @@
import com.android.settings.SettingsActivity;
import com.android.settings.Utils;
import com.android.settings.applications.ApplicationFeatureProvider;
+import com.android.settings.core.BasePreferenceController;
import com.android.settings.core.PreferenceControllerMixin;
import com.android.settings.overlay.FeatureFactory;
import com.android.settings.widget.ActionButtonPreference;
import com.android.settingslib.RestrictedLockUtils;
import com.android.settingslib.applications.AppUtils;
import com.android.settingslib.applications.ApplicationsState;
-import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.core.lifecycle.LifecycleObserver;
@@ -74,8 +74,7 @@
* An easy way to handle them is to delegate them to {@link #handleDialogClick(int)} and
* {@link #handleActivityResult(int, int, Intent)} in this controller.
*/
-//TODO(80312809): Merge this class into {@link AppActionButtonPreferenceController}
-public class AppButtonsPreferenceController extends AbstractPreferenceController implements
+public class AppButtonsPreferenceController extends BasePreferenceController implements
PreferenceControllerMixin, LifecycleObserver, OnResume, OnDestroy,
ApplicationsState.Callbacks {
public static final String APP_CHG = "chg";
@@ -120,9 +119,8 @@
public AppButtonsPreferenceController(SettingsActivity activity, Fragment fragment,
Lifecycle lifecycle, String packageName, ApplicationsState state,
- DevicePolicyManager dpm, UserManager userManager,
- PackageManager packageManager, int requestUninstall, int requestRemoveDeviceAdmin) {
- super(activity);
+ int requestUninstall, int requestRemoveDeviceAdmin) {
+ super(activity, KEY_ACTION_BUTTONS);
if (!(fragment instanceof ButtonActionDialogFragment.AppButtonsDialogListener)) {
throw new IllegalArgumentException(
@@ -133,9 +131,9 @@
mMetricsFeatureProvider = factory.getMetricsFeatureProvider();
mApplicationFeatureProvider = factory.getApplicationFeatureProvider(activity);
mState = state;
- mDpm = dpm;
- mUserManager = userManager;
- mPm = packageManager;
+ mDpm = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
+ mUserManager = (UserManager) activity.getSystemService(Context.USER_SERVICE);
+ mPm = activity.getPackageManager();
mPackageName = packageName;
mActivity = activity;
mFragment = fragment;
@@ -153,9 +151,10 @@
}
@Override
- public boolean isAvailable() {
+ public int getAvailabilityStatus() {
// TODO(b/37313605): Re-enable once this controller supports instant apps
- return mAppEntry != null && !AppUtils.isInstant(mAppEntry.info);
+ return mAppEntry != null && !AppUtils.isInstant(mAppEntry.info)
+ ? AVAILABLE : DISABLED_FOR_USER ;
}
@Override
diff --git a/src/com/android/settings/applications/appinfo/AppInfoDashboardFragment.java b/src/com/android/settings/applications/appinfo/AppInfoDashboardFragment.java
index 1f8a3a0..7107ff7 100755
--- a/src/com/android/settings/applications/appinfo/AppInfoDashboardFragment.java
+++ b/src/com/android/settings/applications/appinfo/AppInfoDashboardFragment.java
@@ -19,14 +19,12 @@
import static com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
import android.app.Activity;
-import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.Context;
-import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
@@ -35,7 +33,6 @@
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.UserInfo;
import android.net.Uri;
-import android.os.AsyncTask;
import android.os.Bundle;
import android.os.UserHandle;
import android.os.UserManager;
@@ -47,7 +44,6 @@
import android.view.MenuItem;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.settings.DeviceAdminAdd;
import com.android.settings.R;
import com.android.settings.SettingsActivity;
import com.android.settings.SettingsPreferenceFragment;
@@ -62,7 +58,6 @@
import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.core.lifecycle.Lifecycle;
-import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -77,7 +72,8 @@
* uninstall the application.
*/
public class AppInfoDashboardFragment extends DashboardFragment
- implements ApplicationsState.Callbacks {
+ implements ApplicationsState.Callbacks,
+ ButtonActionDialogFragment.AppButtonsDialogListener {
private static final String TAG = "AppInfoDashboard";
@@ -101,10 +97,7 @@
// Dialog identifiers used in showDialog
private static final int DLG_BASE = 0;
- private static final int DLG_FORCE_STOP = DLG_BASE + 1;
- private static final int DLG_DISABLE = DLG_BASE + 2;
- private static final int DLG_SPECIAL_DISABLE = DLG_BASE + 3;
- static final int DLG_CLEAR_INSTANT_APP = DLG_BASE + 4;
+ static final int DLG_CLEAR_INSTANT_APP = DLG_BASE + 1;
public static final String ARG_PACKAGE_NAME = "package";
public static final String ARG_PACKAGE_UID = "uid";
@@ -132,12 +125,11 @@
private boolean mInitialized;
private boolean mShowUninstalled;
private boolean mUpdatedSysApp = false;
- private boolean mDisableAfterUninstall;
private List<Callback> mCallbacks = new ArrayList<>();
private InstantAppButtonsPreferenceController mInstantAppButtonPreferenceController;
- private AppActionButtonPreferenceController mAppActionButtonPreferenceController;
+ private AppButtonsPreferenceController mAppButtonsPreferenceController;
/**
* Callback to invoke when app info has been changed.
@@ -146,11 +138,6 @@
void refreshUi();
}
- private boolean isDisabledUntilUsed() {
- return mAppEntry.info.enabledSetting
- == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
- }
-
@Override
public void onAttach(Context context) {
super.onAttach(context);
@@ -262,9 +249,6 @@
// when app state changes.
controllers.add(
new AppHeaderViewPreferenceController(context, this, packageName, lifecycle));
- mAppActionButtonPreferenceController =
- new AppActionButtonPreferenceController(context, this, packageName);
- controllers.add(mAppActionButtonPreferenceController);
for (AbstractPreferenceController controller : controllers) {
mCallbacks.add((Callback) controller);
@@ -275,6 +259,10 @@
mInstantAppButtonPreferenceController =
new InstantAppButtonsPreferenceController(context, this, packageName, lifecycle);
controllers.add(mInstantAppButtonPreferenceController);
+ mAppButtonsPreferenceController = new AppButtonsPreferenceController(
+ (SettingsActivity) getActivity(), this, lifecycle, packageName, mState,
+ REQUEST_UNINSTALL, REQUEST_REMOVE_DEVICE_ADMIN);
+ controllers.add(mAppButtonsPreferenceController);
controllers.add(new AppBatteryPreferenceController(context, this, packageName, lifecycle));
controllers.add(new AppMemoryPreferenceController(context, this, lifecycle));
controllers.add(new DefaultHomeShortcutPreferenceController(context, packageName));
@@ -374,30 +362,19 @@
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
- switch (requestCode) {
- case REQUEST_UNINSTALL:
- // Refresh option menu
- getActivity().invalidateOptionsMenu();
+ if (requestCode == REQUEST_UNINSTALL) {
+ // Refresh option menu
+ getActivity().invalidateOptionsMenu();
+ }
+ if (mAppButtonsPreferenceController != null) {
+ mAppButtonsPreferenceController.handleActivityResult(requestCode, resultCode, data);
+ }
+ }
- if (mDisableAfterUninstall) {
- mDisableAfterUninstall = false;
- new DisableChanger(this, mAppEntry.info,
- PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER)
- .execute((Object) null);
- }
- if (!refreshUi()) {
- onPackageRemoved();
- } else {
- startListeningToPackageRemove();
- }
- break;
- case REQUEST_REMOVE_DEVICE_ADMIN:
- if (!refreshUi()) {
- setIntentAndFinish(true, true);
- } else {
- startListeningToPackageRemove();
- }
- break;
+ @Override
+ public void handleDialogClick(int id) {
+ if (mAppButtonsPreferenceController != null) {
+ mAppButtonsPreferenceController.handleDialogClick(id);
}
}
@@ -442,6 +419,7 @@
for (Callback callback : mCallbacks) {
callback.refreshUi();
}
+ mAppButtonsPreferenceController.refreshUi();
if (!mInitialized) {
// First time init: are we displaying an uninstalled app?
@@ -471,53 +449,6 @@
@VisibleForTesting
AlertDialog createDialog(int id, int errorCode) {
- switch (id) {
- case DLG_DISABLE:
- return new AlertDialog.Builder(getActivity())
- .setMessage(getActivity().getText(R.string.app_disable_dlg_text))
- .setPositiveButton(R.string.app_disable_dlg_positive,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- // Disable the app
- mMetricsFeatureProvider.action(getContext(),
- MetricsEvent.ACTION_SETTINGS_DISABLE_APP);
- new DisableChanger(AppInfoDashboardFragment.this,
- mAppEntry.info,
- PackageManager
- .COMPONENT_ENABLED_STATE_DISABLED_USER)
- .execute((Object) null);
- }
- })
- .setNegativeButton(R.string.dlg_cancel, null)
- .create();
- case DLG_SPECIAL_DISABLE:
- return new AlertDialog.Builder(getActivity())
- .setMessage(getActivity().getText(R.string.app_disable_dlg_text))
- .setPositiveButton(R.string.app_disable_dlg_positive,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- // Disable the app and ask for uninstall
- mMetricsFeatureProvider.action(getContext(),
- MetricsEvent.ACTION_SETTINGS_DISABLE_APP);
- uninstallPkg(mAppEntry.info.packageName,
- false, true);
- }
- })
- .setNegativeButton(R.string.dlg_cancel, null)
- .create();
- case DLG_FORCE_STOP:
- return new AlertDialog.Builder(getActivity())
- .setTitle(getActivity().getText(R.string.force_stop_dlg_title))
- .setMessage(getActivity().getText(R.string.force_stop_dlg_text))
- .setPositiveButton(R.string.dlg_ok, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- // Force stop
- forceStopPackage(mAppEntry.info.packageName);
- }
- })
- .setNegativeButton(R.string.dlg_cancel, null)
- .create();
- }
return mInstantAppButtonPreferenceController.createDialog(id);
}
@@ -530,22 +461,6 @@
mMetricsFeatureProvider.action(
getContext(), MetricsEvent.ACTION_SETTINGS_UNINSTALL_APP);
startActivityForResult(uninstallIntent, REQUEST_UNINSTALL);
- mDisableAfterUninstall = andDisable;
- }
-
- private void forceStopPackage(String pkgName) {
- mMetricsFeatureProvider.action(getContext(), MetricsEvent.ACTION_APP_FORCE_STOP, pkgName);
- final ActivityManager am = (ActivityManager) getActivity().getSystemService(
- Context.ACTIVITY_SERVICE);
- Log.d(TAG, "Stopping package " + pkgName);
- am.forceStopPackage(pkgName);
- final int userId = UserHandle.getUserId(mAppEntry.info.uid);
- mState.invalidatePackage(pkgName, userId);
- final AppEntry newEnt = mState.getEntry(pkgName, userId);
- if (newEnt != null) {
- mAppEntry = newEnt;
- }
- mAppActionButtonPreferenceController.checkForceStop(mAppEntry, mPackageInfo);
}
public static void startAppInfoFragment(Class<?> fragment, int title, Bundle args,
@@ -565,74 +480,6 @@
.launch();
}
- void handleUninstallButtonClick() {
- if (mAppEntry == null) {
- setIntentAndFinish(true, true);
- return;
- }
- final String packageName = mAppEntry.info.packageName;
- if (mDpm.packageHasActiveAdmins(mPackageInfo.packageName)) {
- stopListeningToPackageRemove();
- final Activity activity = getActivity();
- final Intent uninstallDAIntent = new Intent(activity, DeviceAdminAdd.class);
- uninstallDAIntent.putExtra(DeviceAdminAdd.EXTRA_DEVICE_ADMIN_PACKAGE_NAME,
- mPackageName);
- mMetricsFeatureProvider.action(
- activity, MetricsEvent.ACTION_SETTINGS_UNINSTALL_DEVICE_ADMIN);
- activity.startActivityForResult(uninstallDAIntent, REQUEST_REMOVE_DEVICE_ADMIN);
- return;
- }
- final EnforcedAdmin admin = RestrictedLockUtils.checkIfUninstallBlocked(getActivity(),
- packageName, mUserId);
- final boolean uninstallBlockedBySystem = mAppsControlDisallowedBySystem ||
- RestrictedLockUtils.hasBaseUserRestriction(getActivity(), packageName, mUserId);
- if (admin != null && !uninstallBlockedBySystem) {
- RestrictedLockUtils.sendShowAdminSupportDetailsIntent(getActivity(), admin);
- } else if ((mAppEntry.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
- if (mAppEntry.info.enabled && !isDisabledUntilUsed()) {
- // If the system app has an update and this is the only user on the device,
- // then offer to downgrade the app, otherwise only offer to disable the
- // app for this user.
- if (mUpdatedSysApp && isSingleUser()) {
- showDialogInner(DLG_SPECIAL_DISABLE, 0);
- } else {
- showDialogInner(DLG_DISABLE, 0);
- }
- } else {
- mMetricsFeatureProvider.action(
- getActivity(),
- MetricsEvent.ACTION_SETTINGS_ENABLE_APP);
- new DisableChanger(this, mAppEntry.info,
- PackageManager.COMPONENT_ENABLED_STATE_ENABLED)
- .execute((Object) null);
- }
- } else if ((mAppEntry.info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
- uninstallPkg(packageName, true, false);
- } else {
- uninstallPkg(packageName, false, false);
- }
- }
-
- void handleForceStopButtonClick() {
- if (mAppEntry == null) {
- setIntentAndFinish(true, true);
- return;
- }
- if (mAppsControlDisallowedAdmin != null && !mAppsControlDisallowedBySystem) {
- RestrictedLockUtils.sendShowAdminSupportDetailsIntent(
- getActivity(), mAppsControlDisallowedAdmin);
- } else {
- showDialogInner(DLG_FORCE_STOP, 0);
- //forceStopPackage(mAppInfo.packageName);
- }
- }
-
- /** Returns whether there is only one user on this device, not including the system-only user */
- private boolean isSingleUser() {
- final int userCount = mUserManager.getUserCount();
- return userCount == 1 || (mUserManager.isSplitSystemUser() && userCount == 2);
- }
-
private void onPackageRemoved() {
getActivity().finishActivity(SUB_INFO_FRAGMENT);
getActivity().finishAndRemoveTask();
@@ -659,26 +506,6 @@
return count;
}
- private static class DisableChanger extends AsyncTask<Object, Object, Object> {
- final PackageManager mPm;
- final WeakReference<AppInfoDashboardFragment> mActivity;
- final ApplicationInfo mInfo;
- final int mState;
-
- DisableChanger(AppInfoDashboardFragment activity, ApplicationInfo info, int state) {
- mPm = activity.mPm;
- mActivity = new WeakReference<AppInfoDashboardFragment>(activity);
- mInfo = info;
- mState = state;
- }
-
- @Override
- protected Object doInBackground(Object... params) {
- mPm.setApplicationEnabledSetting(mInfo.packageName, mState, 0);
- return null;
- }
- }
-
private String getPackageName() {
if (mPackageName != null) {
return mPackageName;
diff --git a/src/com/android/settings/fuelgauge/ButtonActionDialogFragment.java b/src/com/android/settings/applications/appinfo/ButtonActionDialogFragment.java
similarity index 96%
rename from src/com/android/settings/fuelgauge/ButtonActionDialogFragment.java
rename to src/com/android/settings/applications/appinfo/ButtonActionDialogFragment.java
index f4784a9..a3f1bab 100644
--- a/src/com/android/settings/fuelgauge/ButtonActionDialogFragment.java
+++ b/src/com/android/settings/applications/appinfo/ButtonActionDialogFragment.java
@@ -1,6 +1,5 @@
-package com.android.settings.fuelgauge;
+package com.android.settings.applications.appinfo;
-import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
@@ -26,7 +25,7 @@
/**
* Interface to handle the dialog click
*/
- interface AppButtonsDialogListener {
+ public interface AppButtonsDialogListener {
void handleDialogClick(int type);
}
diff --git a/src/com/android/settings/applications/defaultapps/DefaultBrowserPicker.java b/src/com/android/settings/applications/defaultapps/DefaultBrowserPicker.java
index c243970..1cb7985 100644
--- a/src/com/android/settings/applications/defaultapps/DefaultBrowserPicker.java
+++ b/src/com/android/settings/applications/defaultapps/DefaultBrowserPicker.java
@@ -17,11 +17,9 @@
package com.android.settings.applications.defaultapps;
import android.content.Context;
-import android.content.pm.ComponentInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
-import android.util.ArraySet;
import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.R;
@@ -29,7 +27,6 @@
import java.util.ArrayList;
import java.util.List;
-import java.util.Set;
/**
* Fragment for choosing default browser.
@@ -61,24 +58,13 @@
final List<DefaultAppInfo> candidates = new ArrayList<>();
final Context context = getContext();
// Resolve that intent and check that the handleAllWebDataURI boolean is set
- final List<ResolveInfo> list = mPm.queryIntentActivitiesAsUser(
- DefaultBrowserPreferenceController.BROWSE_PROBE, PackageManager.MATCH_ALL, mUserId);
+ final List<ResolveInfo> list =
+ DefaultBrowserPreferenceController.getCandidates(mPm, mUserId);
- final int count = list.size();
- final Set<String> addedPackages = new ArraySet<>();
- for (int i = 0; i < count; i++) {
- ResolveInfo info = list.get(i);
- if (info.activityInfo == null || !info.handleAllWebDataURI) {
- continue;
- }
- final String packageName = info.activityInfo.packageName;
- if (addedPackages.contains(packageName)) {
- continue;
- }
+ for (ResolveInfo info : list) {
try {
candidates.add(new DefaultAppInfo(context, mPm,
- mPm.getApplicationInfoAsUser(packageName, 0, mUserId)));
- addedPackages.add(packageName);
+ mPm.getApplicationInfoAsUser(info.activityInfo.packageName, 0, mUserId)));
} catch (PackageManager.NameNotFoundException e) {
// Skip unknown packages.
}
diff --git a/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java b/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java
index 5395be9..d4e86ff 100644
--- a/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java
+++ b/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceController.java
@@ -26,12 +26,15 @@
import android.net.Uri;
import androidx.preference.Preference;
import android.text.TextUtils;
+import android.util.ArraySet;
import android.util.IconDrawableFactory;
import android.util.Log;
import com.android.settingslib.applications.DefaultAppInfo;
+import java.util.ArrayList;
import java.util.List;
+import java.util.Set;
public class DefaultBrowserPreferenceController extends DefaultAppPreferenceController {
@@ -48,7 +51,7 @@
@Override
public boolean isAvailable() {
- final List<ResolveInfo> candidates = getCandidates();
+ final List<ResolveInfo> candidates = getCandidates(mPackageManager, mUserId);
return candidates != null && !candidates.isEmpty();
}
@@ -103,14 +106,31 @@
return getOnlyAppIcon();
}
- private List<ResolveInfo> getCandidates() {
- return mPackageManager.queryIntentActivitiesAsUser(BROWSE_PROBE, PackageManager.MATCH_ALL,
- mUserId);
+ static List<ResolveInfo> getCandidates(PackageManager packageManager, int userId) {
+ final List<ResolveInfo> candidates = new ArrayList<>();
+ // Resolve that intent and check that the handleAllWebDataURI boolean is set
+ final List<ResolveInfo> list = packageManager.queryIntentActivitiesAsUser(
+ BROWSE_PROBE, PackageManager.MATCH_ALL, userId);
+ if (list != null) {
+ final Set<String> addedPackages = new ArraySet<>();
+ for (ResolveInfo info : list) {
+ if (info.activityInfo == null || !info.handleAllWebDataURI) {
+ continue;
+ }
+ final String packageName = info.activityInfo.packageName;
+ if (addedPackages.contains(packageName)) {
+ continue;
+ }
+ candidates.add(info);
+ addedPackages.add(packageName);
+ }
+ }
+ return candidates;
}
private String getOnlyAppLabel() {
// Resolve that intent and check that the handleAllWebDataURI boolean is set
- final List<ResolveInfo> list = getCandidates();
+ final List<ResolveInfo> list = getCandidates(mPackageManager, mUserId);
if (list != null && list.size() == 1) {
final ResolveInfo info = list.get(0);
final String label = info.loadLabel(mPackageManager).toString();
@@ -123,7 +143,7 @@
}
private Drawable getOnlyAppIcon() {
- final List<ResolveInfo> list = getCandidates();
+ final List<ResolveInfo> list = getCandidates(mPackageManager, mUserId);
if (list != null && list.size() == 1) {
final ResolveInfo info = list.get(0);
final ComponentInfo cn = info.getComponentInfo();
diff --git a/src/com/android/settings/applications/manageapplications/ManageApplications.java b/src/com/android/settings/applications/manageapplications/ManageApplications.java
index 2250f28..dc9214e 100644
--- a/src/com/android/settings/applications/manageapplications/ManageApplications.java
+++ b/src/com/android/settings/applications/manageapplications/ManageApplications.java
@@ -41,6 +41,7 @@
import android.annotation.Nullable;
import android.annotation.StringRes;
import android.app.Activity;
+import android.app.usage.IUsageStatsManager;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
@@ -48,6 +49,7 @@
import android.content.pm.PackageItemInfo;
import android.os.Bundle;
import android.os.Environment;
+import android.os.ServiceManager;
import android.os.UserHandle;
import android.os.UserManager;
import android.preference.PreferenceFrameLayout;
@@ -224,7 +226,8 @@
private View mSpinnerHeader;
private Spinner mFilterSpinner;
private FilterSpinnerAdapter mFilterAdapter;
- private UsageStatsManager mUsageStatsManager;
+ private IUsageStatsManager mUsageStatsManager;
+ private UserManager mUserManager;
private NotificationBackend mNotificationBackend;
private ResetAppsHelper mResetAppsHelper;
private String mVolumeUuid;
@@ -294,8 +297,9 @@
screenTitle = R.string.change_wifi_state_title;
} else if (className.equals(Settings.NotificationAppListActivity.class.getName())) {
mListType = LIST_TYPE_NOTIFICATION;
- mUsageStatsManager =
- (UsageStatsManager) getContext().getSystemService(Context.USAGE_STATS_SERVICE);
+ mUsageStatsManager = IUsageStatsManager.Stub.asInterface(
+ ServiceManager.getService(Context.USAGE_STATS_SERVICE));
+ mUserManager = UserManager.get(getContext());
mNotificationBackend = new NotificationBackend();
mSortOrder = R.id.sort_order_recent_notification;
screenTitle = R.string.app_notifications_title;
@@ -889,6 +893,7 @@
if (mManageApplications.mListType == LIST_TYPE_NOTIFICATION) {
mExtraInfoBridge = new AppStateNotificationBridge(mContext, mState, this,
manageApplications.mUsageStatsManager,
+ manageApplications.mUserManager,
manageApplications.mNotificationBackend);
} else if (mManageApplications.mListType == LIST_TYPE_USAGE_ACCESS) {
mExtraInfoBridge = new AppStateUsageBridge(mContext, mState, this);
diff --git a/src/com/android/settings/applications/DataSaverController.java b/src/com/android/settings/applications/specialaccess/DataSaverController.java
similarity index 80%
rename from src/com/android/settings/applications/DataSaverController.java
rename to src/com/android/settings/applications/specialaccess/DataSaverController.java
index afe7cd6..56687d7 100644
--- a/src/com/android/settings/applications/DataSaverController.java
+++ b/src/com/android/settings/applications/specialaccess/DataSaverController.java
@@ -15,20 +15,17 @@
*/
-package com.android.settings.applications;
+package com.android.settings.applications.specialaccess;
import android.content.Context;
-import androidx.annotation.VisibleForTesting;
-import com.android.settings.core.BasePreferenceController;
import com.android.settings.R;
+import com.android.settings.core.BasePreferenceController;
public class DataSaverController extends BasePreferenceController {
- @VisibleForTesting static final String KEY_DATA_SAVER = "data_saver";
-
- public DataSaverController(Context context) {
- super(context, KEY_DATA_SAVER);
+ public DataSaverController(Context context, String key) {
+ super(context, key);
}
@AvailabilityStatus
diff --git a/src/com/android/settings/applications/DeviceAdministratorsController.java b/src/com/android/settings/applications/specialaccess/DeviceAdministratorsController.java
similarity index 79%
rename from src/com/android/settings/applications/DeviceAdministratorsController.java
rename to src/com/android/settings/applications/specialaccess/DeviceAdministratorsController.java
index ec1d556..bdb99ef 100644
--- a/src/com/android/settings/applications/DeviceAdministratorsController.java
+++ b/src/com/android/settings/applications/specialaccess/DeviceAdministratorsController.java
@@ -14,20 +14,17 @@
* limitations under the License.
*/
-package com.android.settings.applications;
+package com.android.settings.applications.specialaccess;
import android.content.Context;
-import androidx.annotation.VisibleForTesting;
-import com.android.settings.core.BasePreferenceController;
import com.android.settings.R;
+import com.android.settings.core.BasePreferenceController;
public class DeviceAdministratorsController extends BasePreferenceController {
- @VisibleForTesting static final String KEY_DEVICE_ADMIN = "device_administrators";
-
- public DeviceAdministratorsController(Context context) {
- super(context, KEY_DEVICE_ADMIN);
+ public DeviceAdministratorsController(Context context, String key) {
+ super(context, key);
}
@AvailabilityStatus
diff --git a/src/com/android/settings/applications/EnabledVrListenersController.java b/src/com/android/settings/applications/specialaccess/EnabledVrListenersController.java
similarity index 78%
rename from src/com/android/settings/applications/EnabledVrListenersController.java
rename to src/com/android/settings/applications/specialaccess/EnabledVrListenersController.java
index 7b33529..5967b0d 100644
--- a/src/com/android/settings/applications/EnabledVrListenersController.java
+++ b/src/com/android/settings/applications/specialaccess/EnabledVrListenersController.java
@@ -14,25 +14,24 @@
* limitations under the License.
*/
-package com.android.settings.applications;
+package com.android.settings.applications.specialaccess;
+import android.app.ActivityManager;
import android.content.Context;
-import androidx.annotation.VisibleForTesting;
-import com.android.settings.core.BasePreferenceController;
import com.android.settings.R;
+import com.android.settings.core.BasePreferenceController;
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);
+ public EnabledVrListenersController(Context context, String key) {
+ super(context, key);
}
@AvailabilityStatus
public int getAvailabilityStatus() {
return mContext.getResources().getBoolean(R.bool.config_show_enabled_vr_listeners)
+ && !ActivityManager.isLowRamDeviceStatic()
? AVAILABLE
: UNSUPPORTED_ON_DEVICE;
}
diff --git a/src/com/android/settings/applications/HighPowerAppsController.java b/src/com/android/settings/applications/specialaccess/HighPowerAppsController.java
similarity index 79%
rename from src/com/android/settings/applications/HighPowerAppsController.java
rename to src/com/android/settings/applications/specialaccess/HighPowerAppsController.java
index 39b8451..b893b88 100644
--- a/src/com/android/settings/applications/HighPowerAppsController.java
+++ b/src/com/android/settings/applications/specialaccess/HighPowerAppsController.java
@@ -14,20 +14,17 @@
* limitations under the License.
*/
-package com.android.settings.applications;
+package com.android.settings.applications.specialaccess;
import android.content.Context;
-import androidx.annotation.VisibleForTesting;
-import com.android.settings.core.BasePreferenceController;
import com.android.settings.R;
+import com.android.settings.core.BasePreferenceController;
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);
+ public HighPowerAppsController(Context context, String key) {
+ super(context, key);
}
@AvailabilityStatus
diff --git a/src/com/android/settings/applications/DataSaverController.java b/src/com/android/settings/applications/specialaccess/NotificationAccessController.java
similarity index 60%
copy from src/com/android/settings/applications/DataSaverController.java
copy to src/com/android/settings/applications/specialaccess/NotificationAccessController.java
index afe7cd6..773cd7d 100644
--- a/src/com/android/settings/applications/DataSaverController.java
+++ b/src/com/android/settings/applications/specialaccess/NotificationAccessController.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * 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.
@@ -14,27 +14,23 @@
* limitations under the License.
*/
+package com.android.settings.applications.specialaccess;
-package com.android.settings.applications;
-
+import android.app.ActivityManager;
import android.content.Context;
-import androidx.annotation.VisibleForTesting;
import com.android.settings.core.BasePreferenceController;
-import com.android.settings.R;
-public class DataSaverController extends BasePreferenceController {
+public class NotificationAccessController extends BasePreferenceController {
- @VisibleForTesting static final String KEY_DATA_SAVER = "data_saver";
-
- public DataSaverController(Context context) {
- super(context, KEY_DATA_SAVER);
+ public NotificationAccessController(Context context, String preferenceKey) {
+ super(context, preferenceKey);
}
- @AvailabilityStatus
+ @Override
public int getAvailabilityStatus() {
- return mContext.getResources().getBoolean(R.bool.config_show_data_saver)
+ return !ActivityManager.isLowRamDeviceStatic()
? AVAILABLE
: UNSUPPORTED_ON_DEVICE;
}
-}
\ No newline at end of file
+}
diff --git a/src/com/android/settings/applications/DataSaverController.java b/src/com/android/settings/applications/specialaccess/PictureInPictureController.java
similarity index 60%
copy from src/com/android/settings/applications/DataSaverController.java
copy to src/com/android/settings/applications/specialaccess/PictureInPictureController.java
index afe7cd6..6666605 100644
--- a/src/com/android/settings/applications/DataSaverController.java
+++ b/src/com/android/settings/applications/specialaccess/PictureInPictureController.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * 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.
@@ -14,27 +14,23 @@
* limitations under the License.
*/
+package com.android.settings.applications.specialaccess;
-package com.android.settings.applications;
-
+import android.app.ActivityManager;
import android.content.Context;
-import androidx.annotation.VisibleForTesting;
import com.android.settings.core.BasePreferenceController;
-import com.android.settings.R;
-public class DataSaverController extends BasePreferenceController {
+public class PictureInPictureController extends BasePreferenceController {
- @VisibleForTesting static final String KEY_DATA_SAVER = "data_saver";
-
- public DataSaverController(Context context) {
- super(context, KEY_DATA_SAVER);
+ public PictureInPictureController(Context context, String preferenceKey) {
+ super(context, preferenceKey);
}
- @AvailabilityStatus
+ @Override
public int getAvailabilityStatus() {
- return mContext.getResources().getBoolean(R.bool.config_show_data_saver)
+ return !ActivityManager.isLowRamDeviceStatic()
? AVAILABLE
: UNSUPPORTED_ON_DEVICE;
}
-}
\ No newline at end of file
+}
diff --git a/src/com/android/settings/applications/PremiumSmsController.java b/src/com/android/settings/applications/specialaccess/PremiumSmsController.java
similarity index 80%
rename from src/com/android/settings/applications/PremiumSmsController.java
rename to src/com/android/settings/applications/specialaccess/PremiumSmsController.java
index eeb5d86..0e8c198 100644
--- a/src/com/android/settings/applications/PremiumSmsController.java
+++ b/src/com/android/settings/applications/specialaccess/PremiumSmsController.java
@@ -14,20 +14,17 @@
* limitations under the License.
*/
-package com.android.settings.applications;
+package com.android.settings.applications.specialaccess;
import android.content.Context;
-import androidx.annotation.VisibleForTesting;
-import com.android.settings.core.BasePreferenceController;
import com.android.settings.R;
+import com.android.settings.core.BasePreferenceController;
public class PremiumSmsController extends BasePreferenceController {
- @VisibleForTesting static final String KEY_PREMIUM_SMS = "premium_sms";
-
- public PremiumSmsController(Context context) {
- super(context, KEY_PREMIUM_SMS);
+ public PremiumSmsController(Context context, String key) {
+ super(context, key);
}
@AvailabilityStatus
diff --git a/src/com/android/settings/applications/specialaccess/SpecialAccessSettings.java b/src/com/android/settings/applications/specialaccess/SpecialAccessSettings.java
new file mode 100644
index 0000000..80cadcc
--- /dev/null
+++ b/src/com/android/settings/applications/specialaccess/SpecialAccessSettings.java
@@ -0,0 +1,65 @@
+/*
+ * 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.
+ */
+
+package com.android.settings.applications.specialaccess;
+
+import android.content.Context;
+import android.provider.SearchIndexableResource;
+
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.settings.R;
+import com.android.settings.dashboard.DashboardFragment;
+import com.android.settings.search.BaseSearchIndexProvider;
+import com.android.settings.search.Indexable;
+import com.android.settingslib.search.SearchIndexable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@SearchIndexable
+public class SpecialAccessSettings extends DashboardFragment {
+
+ private static final String TAG = "SpecialAccessSettings";
+
+ @Override
+ protected String getLogTag() {
+ return TAG;
+ }
+
+ @Override
+ protected int getPreferenceScreenResId() {
+ return R.xml.special_access;
+ }
+
+ @Override
+ public int getMetricsCategory() {
+ return MetricsEvent.SPECIAL_ACCESS;
+ }
+
+ public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+ new BaseSearchIndexProvider() {
+ @Override
+ public List<SearchIndexableResource> getXmlResourcesToIndex(Context context,
+ boolean enabled) {
+ final ArrayList<SearchIndexableResource> result = new ArrayList<>();
+
+ final SearchIndexableResource sir = new SearchIndexableResource(context);
+ sir.xmlResId = R.xml.special_access;
+ result.add(sir);
+ return result;
+ }
+ };
+}
diff --git a/src/com/android/settings/applications/DataSaverController.java b/src/com/android/settings/applications/specialaccess/ZenAccessController.java
similarity index 60%
copy from src/com/android/settings/applications/DataSaverController.java
copy to src/com/android/settings/applications/specialaccess/ZenAccessController.java
index afe7cd6..41344a3 100644
--- a/src/com/android/settings/applications/DataSaverController.java
+++ b/src/com/android/settings/applications/specialaccess/ZenAccessController.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * 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.
@@ -14,27 +14,23 @@
* limitations under the License.
*/
+package com.android.settings.applications.specialaccess;
-package com.android.settings.applications;
-
+import android.app.ActivityManager;
import android.content.Context;
-import androidx.annotation.VisibleForTesting;
import com.android.settings.core.BasePreferenceController;
-import com.android.settings.R;
-public class DataSaverController extends BasePreferenceController {
+public class ZenAccessController extends BasePreferenceController {
- @VisibleForTesting static final String KEY_DATA_SAVER = "data_saver";
-
- public DataSaverController(Context context) {
- super(context, KEY_DATA_SAVER);
+ public ZenAccessController(Context context, String preferenceKey) {
+ super(context, preferenceKey);
}
- @AvailabilityStatus
+ @Override
public int getAvailabilityStatus() {
- return mContext.getResources().getBoolean(R.bool.config_show_data_saver)
+ return !ActivityManager.isLowRamDeviceStatic()
? AVAILABLE
: UNSUPPORTED_ON_DEVICE;
}
-}
\ No newline at end of file
+}
diff --git a/src/com/android/settings/bluetooth/AvailableMediaBluetoothDeviceUpdater.java b/src/com/android/settings/bluetooth/AvailableMediaBluetoothDeviceUpdater.java
index 9a287f1..ea520ea 100644
--- a/src/com/android/settings/bluetooth/AvailableMediaBluetoothDeviceUpdater.java
+++ b/src/com/android/settings/bluetooth/AvailableMediaBluetoothDeviceUpdater.java
@@ -97,6 +97,11 @@
if (DBG) {
Log.d(TAG, "isFilterMatched() current audio profile : " + currentAudioProfile);
}
+ // If device is Hearing Aid, it is compatible with HFP and A2DP.
+ // It would show in Available Devices group.
+ if (cachedDevice.isConnectedHearingAidDevice()) {
+ return true;
+ }
// According to the current audio profile type,
// this page will show the bluetooth device that have corresponding profile.
// For example:
diff --git a/src/com/android/settings/bluetooth/ConnectedBluetoothDeviceUpdater.java b/src/com/android/settings/bluetooth/ConnectedBluetoothDeviceUpdater.java
index 0ac3e6d..bb543ba 100644
--- a/src/com/android/settings/bluetooth/ConnectedBluetoothDeviceUpdater.java
+++ b/src/com/android/settings/bluetooth/ConnectedBluetoothDeviceUpdater.java
@@ -101,6 +101,11 @@
if (DBG) {
Log.d(TAG, "isFilterMatched() current audio profile : " + currentAudioProfile);
}
+ // If device is Hearing Aid, it is compatible with HFP and A2DP.
+ // It would not show in Connected Devices group.
+ if (cachedDevice.isConnectedHearingAidDevice()) {
+ return false;
+ }
// According to the current audio profile type,
// this page will show the bluetooth device that doesn't have corresponding profile.
// For example:
diff --git a/src/com/android/settings/core/FeatureFlags.java b/src/com/android/settings/core/FeatureFlags.java
index a1bce23..006bd70 100644
--- a/src/com/android/settings/core/FeatureFlags.java
+++ b/src/com/android/settings/core/FeatureFlags.java
@@ -21,8 +21,6 @@
*/
public class FeatureFlags {
public static final String BATTERY_DISPLAY_APP_LIST = "settings_battery_display_app_list";
- public static final String ZONE_PICKER_V2 = "settings_zone_picker_v2";
public static final String BLUETOOTH_WHILE_DRIVING = "settings_bluetooth_while_driving";
- public static final String DATA_USAGE_SETTINGS_V2 = "settings_data_usage_v2";
public static final String AUDIO_SWITCHER_SETTINGS = "settings_audio_switcher";
}
diff --git a/src/com/android/settings/core/gateway/SettingsGateway.java b/src/com/android/settings/core/gateway/SettingsGateway.java
index 6cf29597..a050628 100644
--- a/src/com/android/settings/core/gateway/SettingsGateway.java
+++ b/src/com/android/settings/core/gateway/SettingsGateway.java
@@ -59,7 +59,6 @@
import com.android.settings.connecteddevice.usb.UsbDetailsFragment;
import com.android.settings.datausage.DataUsageList;
import com.android.settings.datausage.DataUsageSummary;
-import com.android.settings.datausage.DataUsageSummaryLegacy;
import com.android.settings.deletionhelper.AutomaticStorageManagerSettings;
import com.android.settings.development.DevelopmentSettingsDashboardFragment;
import com.android.settings.deviceinfo.PrivateVolumeForget;
@@ -192,7 +191,6 @@
SwipeUpGestureSettings.class.getName(),
CryptKeeperSettings.class.getName(),
DataUsageSummary.class.getName(),
- DataUsageSummaryLegacy.class.getName(),
DreamSettings.class.getName(),
UserSettings.class.getName(),
NotificationAccessSettings.class.getName(),
diff --git a/src/com/android/settings/dashboard/conditional/BackgroundDataCondition.java b/src/com/android/settings/dashboard/conditional/BackgroundDataCondition.java
index a7e160f..d5372a2 100644
--- a/src/com/android/settings/dashboard/conditional/BackgroundDataCondition.java
+++ b/src/com/android/settings/dashboard/conditional/BackgroundDataCondition.java
@@ -18,12 +18,10 @@
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.NetworkPolicyManager;
-import android.util.FeatureFlagUtils;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.R;
import com.android.settings.Settings;
-import com.android.settings.core.FeatureFlags;
public class BackgroundDataCondition extends Condition {
@@ -58,11 +56,8 @@
@Override
public void onPrimaryClick() {
- final Class activityClass = FeatureFlagUtils.isEnabled(mManager.getContext(),
- FeatureFlags.DATA_USAGE_SETTINGS_V2)
- ? Settings.DataUsageSummaryActivity.class
- : Settings.DataUsageSummaryLegacyActivity.class;
- mManager.getContext().startActivity(new Intent(mManager.getContext(), activityClass)
+ mManager.getContext().startActivity(new Intent(mManager.getContext(),
+ Settings.DataUsageSummaryActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
diff --git a/src/com/android/settings/datausage/BillingCyclePreference.java b/src/com/android/settings/datausage/BillingCyclePreference.java
index 7d454a1..70a123f 100644
--- a/src/com/android/settings/datausage/BillingCyclePreference.java
+++ b/src/com/android/settings/datausage/BillingCyclePreference.java
@@ -14,24 +14,20 @@
package com.android.settings.datausage;
-import static android.net.NetworkPolicy.CYCLE_NONE;
-
import android.content.Context;
import android.content.Intent;
import android.net.NetworkTemplate;
import android.os.Bundle;
import android.os.RemoteException;
-import androidx.preference.Preference;
import android.util.AttributeSet;
-import android.util.FeatureFlagUtils;
import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.R;
-
-import com.android.settings.core.FeatureFlags;
import com.android.settings.core.SubSettingLauncher;
import com.android.settings.datausage.CellDataPreference.DataStateListener;
+import androidx.preference.Preference;
+
public class BillingCyclePreference extends Preference implements TemplatePreference {
private NetworkTemplate mTemplate;
@@ -60,14 +56,8 @@
mTemplate = template;
mSubId = subId;
mServices = services;
- final int cycleDay = services.mPolicyEditor.getPolicyCycleDay(mTemplate);
- if (FeatureFlagUtils.isEnabled(getContext(), FeatureFlags.DATA_USAGE_SETTINGS_V2)) {
- setSummary(null);
- } else if (cycleDay != CYCLE_NONE) {
- setSummary(getContext().getString(R.string.billing_cycle_fragment_summary, cycleDay));
- } else {
- setSummary(null);
- }
+ setSummary(null);
+
setIntent(getIntent());
}
diff --git a/src/com/android/settings/datausage/BillingCycleSettings.java b/src/com/android/settings/datausage/BillingCycleSettings.java
index 5cdf22a..8360df8 100644
--- a/src/com/android/settings/datausage/BillingCycleSettings.java
+++ b/src/com/android/settings/datausage/BillingCycleSettings.java
@@ -14,7 +14,6 @@
package com.android.settings.datausage;
-import static android.net.NetworkPolicy.CYCLE_NONE;
import static android.net.NetworkPolicy.LIMIT_DISABLED;
import static android.net.NetworkPolicy.WARNING_DISABLED;
@@ -27,10 +26,7 @@
import android.net.NetworkPolicy;
import android.net.NetworkTemplate;
import android.os.Bundle;
-import androidx.preference.SwitchPreference;
-import androidx.preference.Preference;
import android.text.format.Time;
-import android.util.FeatureFlagUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
@@ -41,11 +37,13 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.R;
-import com.android.settings.core.FeatureFlags;
import com.android.settings.core.instrumentation.InstrumentedDialogFragment;
import com.android.settingslib.NetworkPolicyEditor;
import com.android.settingslib.net.DataUsageController;
+import androidx.preference.Preference;
+import androidx.preference.SwitchPreference;
+
public class BillingCycleSettings extends DataUsageBase implements
Preference.OnPreferenceChangeListener, DataUsageEditController {
@@ -63,7 +61,8 @@
private static final String KEY_BILLING_CYCLE = "billing_cycle";
private static final String KEY_SET_DATA_WARNING = "set_data_warning";
private static final String KEY_DATA_WARNING = "data_warning";
- @VisibleForTesting static final String KEY_SET_DATA_LIMIT = "set_data_limit";
+ @VisibleForTesting
+ static final String KEY_SET_DATA_LIMIT = "set_data_limit";
private static final String KEY_DATA_LIMIT = "data_limit";
private NetworkTemplate mNetworkTemplate;
@@ -76,11 +75,11 @@
@VisibleForTesting
void setUpForTest(NetworkPolicyEditor policyEditor,
- Preference billingCycle,
- Preference dataLimit,
- Preference dataWarning,
- SwitchPreference enableLimit,
- SwitchPreference enableWarning) {
+ Preference billingCycle,
+ Preference dataLimit,
+ Preference dataWarning,
+ SwitchPreference enableLimit,
+ SwitchPreference enableWarning) {
services.mPolicyEditor = policyEditor;
mBillingCycle = billingCycle;
mDataLimit = dataLimit;
@@ -118,14 +117,7 @@
@VisibleForTesting
void updatePrefs() {
- final int cycleDay = services.mPolicyEditor.getPolicyCycleDay(mNetworkTemplate);
- if (FeatureFlagUtils.isEnabled(getContext(), FeatureFlags.DATA_USAGE_SETTINGS_V2)) {
- mBillingCycle.setSummary(null);
- } else if (cycleDay != CYCLE_NONE) {
- mBillingCycle.setSummary(getString(R.string.billing_cycle_fragment_summary, cycleDay));
- } else {
- mBillingCycle.setSummary(null);
- }
+ mBillingCycle.setSummary(null);
final long warningBytes = services.mPolicyEditor.getPolicyWarningBytes(mNetworkTemplate);
if (warningBytes != WARNING_DISABLED) {
mDataWarning.setSummary(DataUsageUtils.formatDataUsage(getContext(), warningBytes));
@@ -402,7 +394,8 @@
*/
public static class ConfirmLimitFragment extends InstrumentedDialogFragment implements
DialogInterface.OnClickListener {
- @VisibleForTesting static final String EXTRA_LIMIT_BYTES = "limitBytes";
+ @VisibleForTesting
+ static final String EXTRA_LIMIT_BYTES = "limitBytes";
public static final float FLOAT = 1.2f;
public static void show(BillingCycleSettings parent) {
diff --git a/src/com/android/settings/datausage/ChartDataUsagePreference.java b/src/com/android/settings/datausage/ChartDataUsagePreference.java
index d02aa88..92d5cc8 100644
--- a/src/com/android/settings/datausage/ChartDataUsagePreference.java
+++ b/src/com/android/settings/datausage/ChartDataUsagePreference.java
@@ -18,9 +18,6 @@
import android.net.NetworkPolicy;
import android.net.NetworkStatsHistory;
import android.net.TrafficStats;
-import androidx.annotation.VisibleForTesting;
-import androidx.preference.Preference;
-import androidx.preference.PreferenceViewHolder;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.Formatter;
@@ -30,7 +27,11 @@
import com.android.settings.R;
import com.android.settings.Utils;
-import com.android.settings.graph.UsageView;
+import com.android.settings.widget.UsageView;
+
+import androidx.annotation.VisibleForTesting;
+import androidx.preference.Preference;
+import androidx.preference.PreferenceViewHolder;
public class ChartDataUsagePreference extends Preference {
diff --git a/src/com/android/settings/datausage/DataUsageBase.java b/src/com/android/settings/datausage/DataUsageBase.java
index b889a2f..c5df0bb 100644
--- a/src/com/android/settings/datausage/DataUsageBase.java
+++ b/src/com/android/settings/datausage/DataUsageBase.java
@@ -14,25 +14,19 @@
package com.android.settings.datausage;
-import static android.net.ConnectivityManager.TYPE_ETHERNET;
-
import android.content.Context;
-import android.net.ConnectivityManager;
import android.net.INetworkStatsService;
-import android.net.INetworkStatsSession;
import android.net.NetworkPolicy;
import android.net.NetworkPolicyManager;
-import android.net.NetworkTemplate;
-import android.net.TrafficStats;
import android.os.Bundle;
import android.os.INetworkManagementService;
import android.os.RemoteException;
import android.os.ServiceManager;
-import android.os.SystemProperties;
import android.os.UserManager;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;
+
import com.android.settings.SettingsPreferenceFragment;
import com.android.settingslib.NetworkPolicyEditor;
@@ -99,34 +93,4 @@
return false;
}
}
-
- /**
- * Test if device has an ethernet network connection.
- */
- public boolean hasEthernet(Context context) {
- if (DataUsageUtils.TEST_RADIOS) {
- return SystemProperties.get(DataUsageUtils.TEST_RADIOS_PROP).contains(ETHERNET);
- }
-
- final ConnectivityManager conn = ConnectivityManager.from(context);
- final boolean hasEthernet = conn.isNetworkSupported(TYPE_ETHERNET);
-
- final long ethernetBytes;
- try {
- INetworkStatsSession statsSession = services.mStatsService.openSession();
- if (statsSession != null) {
- ethernetBytes = statsSession.getSummaryForNetwork(
- NetworkTemplate.buildTemplateEthernet(), Long.MIN_VALUE, Long.MAX_VALUE)
- .getTotalBytes();
- TrafficStats.closeQuietly(statsSession);
- } else {
- ethernetBytes = 0;
- }
- } catch (RemoteException e) {
- throw new RuntimeException(e);
- }
-
- // only show ethernet when both hardware present and traffic has occurred
- return hasEthernet && ethernetBytes > 0;
- }
}
diff --git a/src/com/android/settings/datausage/DataUsageBaseFragment.java b/src/com/android/settings/datausage/DataUsageBaseFragment.java
index e9c73ff..f6e88cc 100644
--- a/src/com/android/settings/datausage/DataUsageBaseFragment.java
+++ b/src/com/android/settings/datausage/DataUsageBaseFragment.java
@@ -14,27 +14,19 @@
package com.android.settings.datausage;
-import static android.net.ConnectivityManager.TYPE_ETHERNET;
-
import android.content.Context;
-import android.net.ConnectivityManager;
import android.net.INetworkStatsService;
-import android.net.INetworkStatsSession;
import android.net.NetworkPolicy;
import android.net.NetworkPolicyManager;
-import android.net.NetworkTemplate;
-import android.net.TrafficStats;
import android.os.Bundle;
import android.os.INetworkManagementService;
import android.os.RemoteException;
import android.os.ServiceManager;
-import android.os.SystemProperties;
import android.os.UserManager;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.Log;
-import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.dashboard.DashboardFragment;
import com.android.settingslib.NetworkPolicyEditor;
@@ -54,7 +46,7 @@
ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
services.mStatsService = INetworkStatsService.Stub.asInterface(
ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
- services.mPolicyManager = (NetworkPolicyManager)context
+ services.mPolicyManager = (NetworkPolicyManager) context
.getSystemService(Context.NETWORK_POLICY_SERVICE);
services.mPolicyEditor = new NetworkPolicyEditor(services.mPolicyManager);
@@ -98,35 +90,4 @@
return false;
}
}
-
- /**
- * Test if device has an ethernet network connection.
- * TODO(b/77590489): Remove this method when DataUsageSummaryLegacy is deprecated.
- */
- public boolean hasEthernet(Context context) {
- if (DataUsageUtils.TEST_RADIOS) {
- return SystemProperties.get(DataUsageUtils.TEST_RADIOS_PROP).contains(ETHERNET);
- }
-
- final ConnectivityManager conn = ConnectivityManager.from(context);
- final boolean hasEthernet = conn.isNetworkSupported(TYPE_ETHERNET);
-
- final long ethernetBytes;
- try {
- INetworkStatsSession statsSession = services.mStatsService.openSession();
- if (statsSession != null) {
- ethernetBytes = statsSession.getSummaryForNetwork(
- NetworkTemplate.buildTemplateEthernet(), Long.MIN_VALUE, Long.MAX_VALUE)
- .getTotalBytes();
- TrafficStats.closeQuietly(statsSession);
- } else {
- ethernetBytes = 0;
- }
- } catch (RemoteException e) {
- throw new RuntimeException(e);
- }
-
- // only show ethernet when both hardware present and traffic has occurred
- return hasEthernet && ethernetBytes > 0;
- }
}
diff --git a/src/com/android/settings/datausage/DataUsagePreference.java b/src/com/android/settings/datausage/DataUsagePreference.java
index bb3902c..af8d6d4 100644
--- a/src/com/android/settings/datausage/DataUsagePreference.java
+++ b/src/com/android/settings/datausage/DataUsagePreference.java
@@ -19,17 +19,16 @@
import android.content.res.TypedArray;
import android.net.NetworkTemplate;
import android.os.Bundle;
-import androidx.core.content.res.TypedArrayUtils;
-import androidx.preference.Preference;
import android.util.AttributeSet;
-import android.util.FeatureFlagUtils;
import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.R;
-import com.android.settings.core.FeatureFlags;
import com.android.settings.core.SubSettingLauncher;
import com.android.settingslib.net.DataUsageController;
+import androidx.core.content.res.TypedArrayUtils;
+import androidx.preference.Preference;
+
public class DataUsagePreference extends Preference implements TemplatePreference {
private NetworkTemplate mTemplate;
@@ -54,20 +53,13 @@
mSubId = subId;
DataUsageController controller = new DataUsageController(getContext());
DataUsageController.DataUsageInfo usageInfo = controller.getDataUsageInfo(mTemplate);
- if (FeatureFlagUtils.isEnabled(getContext(), FeatureFlags.DATA_USAGE_SETTINGS_V2)) {
- if (mTemplate.isMatchRuleMobile()) {
- setTitle(R.string.app_cellular_data_usage);
- } else {
- setTitle(mTitleRes);
- setSummary(getContext().getString(R.string.data_usage_template,
- DataUsageUtils.formatDataUsage(getContext(), usageInfo.usageLevel),
- usageInfo.period));
- }
+ if (mTemplate.isMatchRuleMobile()) {
+ setTitle(R.string.app_cellular_data_usage);
} else {
setTitle(mTitleRes);
setSummary(getContext().getString(R.string.data_usage_template,
DataUsageUtils.formatDataUsage(getContext(), usageInfo.usageLevel),
- usageInfo.period));
+ usageInfo.period));
}
setIntent(getIntent());
}
@@ -81,18 +73,10 @@
.setArguments(args)
.setDestination(DataUsageList.class.getName())
.setSourceMetricsCategory(MetricsProto.MetricsEvent.VIEW_UNKNOWN);
- if (FeatureFlagUtils.isEnabled(getContext(), FeatureFlags.DATA_USAGE_SETTINGS_V2)) {
- if (mTemplate.isMatchRuleMobile()) {
- launcher.setTitleRes(R.string.app_cellular_data_usage);
- } else {
- launcher.setTitleRes(mTitleRes);
- }
+ if (mTemplate.isMatchRuleMobile()) {
+ launcher.setTitleRes(R.string.app_cellular_data_usage);
} else {
- if (mTitleRes > 0) {
- launcher.setTitleRes(mTitleRes);
- } else {
- launcher.setTitleText(getTitle());
- }
+ launcher.setTitleRes(mTitleRes);
}
return launcher.toIntent();
}
diff --git a/src/com/android/settings/datausage/DataUsageSummary.java b/src/com/android/settings/datausage/DataUsageSummary.java
index 1b012f1..58a5a8f 100644
--- a/src/com/android/settings/datausage/DataUsageSummary.java
+++ b/src/com/android/settings/datausage/DataUsageSummary.java
@@ -15,15 +15,10 @@
package com.android.settings.datausage;
import android.app.Activity;
-import android.content.ComponentName;
import android.content.Context;
-import android.content.Intent;
import android.net.NetworkTemplate;
import android.os.Bundle;
import android.provider.SearchIndexableResource;
-import androidx.annotation.VisibleForTesting;
-import androidx.preference.Preference;
-import androidx.preference.PreferenceScreen;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.SubscriptionPlan;
@@ -33,7 +28,6 @@
import android.text.TextUtils;
import android.text.format.Formatter;
import android.text.style.RelativeSizeSpan;
-import android.view.MenuItem;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.R;
@@ -49,6 +43,10 @@
import java.util.ArrayList;
import java.util.List;
+import androidx.annotation.VisibleForTesting;
+import androidx.preference.Preference;
+import androidx.preference.PreferenceScreen;
+
/**
* Settings preference fragment that displays data usage summary.
*/
@@ -121,20 +119,6 @@
}
@Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.data_usage_menu_cellular_networks: {
- final Intent intent = new Intent(Intent.ACTION_MAIN);
- intent.setComponent(new ComponentName("com.android.phone",
- "com.android.phone.MobileNetworkSettings"));
- startActivity(intent);
- return true;
- }
- }
- return false;
- }
-
- @Override
public boolean onPreferenceTreeClick(Preference preference) {
if (preference == findPreference(KEY_STATUS_HEADER)) {
BillingCycleSettings.BytesEditorFragment.show(this, false);
diff --git a/src/com/android/settings/datausage/DataUsageSummaryLegacy.java b/src/com/android/settings/datausage/DataUsageSummaryLegacy.java
deleted file mode 100644
index 5c19afb..0000000
--- a/src/com/android/settings/datausage/DataUsageSummaryLegacy.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- * 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.
- */
-
-package com.android.settings.datausage;
-
-import android.app.Activity;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.net.NetworkPolicyManager;
-import android.net.NetworkTemplate;
-import android.os.Bundle;
-import android.os.UserManager;
-import android.provider.SearchIndexableResource;
-import androidx.annotation.VisibleForTesting;
-import androidx.preference.Preference;
-import androidx.preference.PreferenceScreen;
-import android.telephony.SubscriptionInfo;
-import android.telephony.SubscriptionManager;
-import android.text.BidiFormatter;
-import android.text.Spannable;
-import android.text.SpannableString;
-import android.text.TextUtils;
-import android.text.format.Formatter;
-import android.text.style.RelativeSizeSpan;
-import android.view.Menu;
-import android.view.MenuInflater;
-import android.view.MenuItem;
-
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.settings.R;
-import com.android.settings.SummaryPreference;
-import com.android.settings.Utils;
-import com.android.settings.dashboard.SummaryLoader;
-import com.android.settings.search.BaseSearchIndexProvider;
-import com.android.settings.search.Indexable;
-import com.android.settingslib.NetworkPolicyEditor;
-import com.android.settingslib.core.AbstractPreferenceController;
-import com.android.settingslib.net.DataUsageController;
-import com.android.settingslib.search.SearchIndexable;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Legacy {@link DataUsageSummary} fragment.
- */
-@SearchIndexable(forTarget = SearchIndexable.ALL & ~SearchIndexable.ARC)
-public class DataUsageSummaryLegacy extends DataUsageBaseFragment implements Indexable,
- DataUsageEditController {
-
- private static final String TAG = "DataUsageSummaryLegacy";
-
- static final boolean LOGD = false;
-
- public static final String KEY_RESTRICT_BACKGROUND = "restrict_background_legacy";
-
- private static final String KEY_STATUS_HEADER = "status_header";
- private static final String KEY_LIMIT_SUMMARY = "limit_summary";
-
- // Mobile data keys
- public static final String KEY_MOBILE_USAGE_TITLE = "mobile_category";
- public static final String KEY_MOBILE_DATA_USAGE_TOGGLE = "data_usage_enable";
- public static final String KEY_MOBILE_DATA_USAGE = "cellular_data_usage";
- public static final String KEY_MOBILE_BILLING_CYCLE = "billing_preference";
-
- // Wifi keys
- public static final String KEY_WIFI_USAGE_TITLE = "wifi_category";
- public static final String KEY_WIFI_DATA_USAGE = "wifi_data_usage";
-
- private DataUsageController mDataUsageController;
- private DataUsageInfoController mDataInfoController;
- private SummaryPreference mSummaryPreference;
- private Preference mLimitPreference;
- private NetworkTemplate mDefaultTemplate;
- private int mDataUsageTemplate;
- private NetworkPolicyEditor mPolicyEditor;
-
- @Override
- public int getHelpResource() {
- return R.string.help_url_data_usage;
- }
-
- @Override
- public void onCreate(Bundle icicle) {
- super.onCreate(icicle);
-
- final Context context = getContext();
- NetworkPolicyManager policyManager = NetworkPolicyManager.from(context);
- mPolicyEditor = new NetworkPolicyEditor(policyManager);
-
- boolean hasMobileData = DataUsageUtils.hasMobileData(context);
- mDataUsageController = new DataUsageController(context);
- mDataInfoController = new DataUsageInfoController();
-
- int defaultSubId = DataUsageUtils.getDefaultSubscriptionId(context);
- if (defaultSubId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
- hasMobileData = false;
- }
- mDefaultTemplate = DataUsageUtils.getDefaultTemplate(context, defaultSubId);
- mSummaryPreference = (SummaryPreference) findPreference(KEY_STATUS_HEADER);
-
- if (!hasMobileData || !isAdmin()) {
- removePreference(KEY_RESTRICT_BACKGROUND);
- }
- if (hasMobileData) {
- mLimitPreference = findPreference(KEY_LIMIT_SUMMARY);
- List<SubscriptionInfo> subscriptions =
- services.mSubscriptionManager.getActiveSubscriptionInfoList();
- if (subscriptions == null || subscriptions.size() == 0) {
- addMobileSection(defaultSubId);
- }
- for (int i = 0; subscriptions != null && i < subscriptions.size(); i++) {
- SubscriptionInfo subInfo = subscriptions.get(i);
- if (subscriptions.size() > 1) {
- addMobileSection(subInfo.getSubscriptionId(), subInfo);
- } else {
- addMobileSection(subInfo.getSubscriptionId());
- }
- }
- mSummaryPreference.setSelectable(true);
- } else {
- removePreference(KEY_LIMIT_SUMMARY);
- mSummaryPreference.setSelectable(false);
- }
- boolean hasWifiRadio = DataUsageUtils.hasWifiRadio(context);
- if (hasWifiRadio) {
- addWifiSection();
- }
- if (hasEthernet(context)) {
- addEthernetSection();
- }
- mDataUsageTemplate = hasMobileData ? R.string.cell_data_template
- : hasWifiRadio ? R.string.wifi_data_template
- : R.string.ethernet_data_template;
-
- setHasOptionsMenu(true);
- }
-
- @Override
- public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
- if (UserManager.get(getContext()).isAdminUser()) {
- inflater.inflate(R.menu.data_usage, menu);
- }
- super.onCreateOptionsMenu(menu, inflater);
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.data_usage_menu_cellular_networks: {
- final Intent intent = new Intent(Intent.ACTION_MAIN);
- intent.setComponent(new ComponentName("com.android.phone",
- "com.android.phone.MobileNetworkSettings"));
- startActivity(intent);
- return true;
- }
- }
- return false;
- }
-
- @Override
- public boolean onPreferenceTreeClick(Preference preference) {
- if (preference == findPreference(KEY_STATUS_HEADER)) {
- BillingCycleSettings.BytesEditorFragment.show(this, false);
- return false;
- }
- return super.onPreferenceTreeClick(preference);
- }
-
- @Override
- protected int getPreferenceScreenResId() {
- return R.xml.data_usage_legacy;
- }
-
- @Override
- protected String getLogTag() {
- return TAG;
- }
-
- @Override
- protected List<AbstractPreferenceController> createPreferenceControllers(Context context) {
- return null;
- }
-
- private void addMobileSection(int subId) {
- addMobileSection(subId, null);
- }
-
- private void addMobileSection(int subId, SubscriptionInfo subInfo) {
- TemplatePreferenceCategory category = (TemplatePreferenceCategory)
- inflatePreferences(R.xml.data_usage_cellular);
- category.setTemplate(getNetworkTemplate(subId), subId, services);
- category.pushTemplates(services);
- if (subInfo != null && !TextUtils.isEmpty(subInfo.getDisplayName())) {
- Preference title = category.findPreference(KEY_MOBILE_USAGE_TITLE);
- title.setTitle(subInfo.getDisplayName());
- }
- }
-
- private void addWifiSection() {
- TemplatePreferenceCategory category = (TemplatePreferenceCategory)
- inflatePreferences(R.xml.data_usage_wifi);
- category.setTemplate(NetworkTemplate.buildTemplateWifiWildcard(), 0, services);
- }
-
- private void addEthernetSection() {
- TemplatePreferenceCategory category = (TemplatePreferenceCategory)
- inflatePreferences(R.xml.data_usage_ethernet);
- category.setTemplate(NetworkTemplate.buildTemplateEthernet(), 0, services);
- }
-
- private Preference inflatePreferences(int resId) {
- PreferenceScreen rootPreferences = getPreferenceManager().inflateFromResource(
- getPrefContext(), resId, null);
- Preference pref = rootPreferences.getPreference(0);
- rootPreferences.removeAll();
-
- PreferenceScreen screen = getPreferenceScreen();
- pref.setOrder(screen.getPreferenceCount());
- screen.addPreference(pref);
-
- return pref;
- }
-
- private NetworkTemplate getNetworkTemplate(int subscriptionId) {
- NetworkTemplate mobileAll = NetworkTemplate.buildTemplateMobileAll(
- services.mTelephonyManager.getSubscriberId(subscriptionId));
- return NetworkTemplate.normalize(mobileAll,
- services.mTelephonyManager.getMergedSubscriberIds());
- }
-
- @Override
- public void onResume() {
- super.onResume();
- updateState();
- }
-
- @VisibleForTesting
- static CharSequence formatUsage(Context context, String template, long usageLevel) {
- final float LARGER_SIZE = 1.25f * 1.25f; // (1/0.8)^2
- final float SMALLER_SIZE = 1.0f / LARGER_SIZE; // 0.8^2
- final int FLAGS = Spannable.SPAN_INCLUSIVE_INCLUSIVE;
-
- final Formatter.BytesResult usedResult = Formatter.formatBytes(context.getResources(),
- usageLevel, Formatter.FLAG_CALCULATE_ROUNDED);
- final SpannableString enlargedValue = new SpannableString(usedResult.value);
- enlargedValue.setSpan(new RelativeSizeSpan(LARGER_SIZE), 0, enlargedValue.length(), FLAGS);
-
- final SpannableString amountTemplate = new SpannableString(
- context.getString(com.android.internal.R.string.fileSizeSuffix)
- .replace("%1$s", "^1").replace("%2$s", "^2"));
- final CharSequence formattedUsage = TextUtils.expandTemplate(amountTemplate,
- enlargedValue, usedResult.units);
-
- final SpannableString fullTemplate = new SpannableString(template);
- fullTemplate.setSpan(new RelativeSizeSpan(SMALLER_SIZE), 0, fullTemplate.length(), FLAGS);
- return TextUtils.expandTemplate(fullTemplate,
- BidiFormatter.getInstance().unicodeWrap(formattedUsage.toString()));
- }
-
- private void updateState() {
- DataUsageController.DataUsageInfo info = mDataUsageController.getDataUsageInfo(
- mDefaultTemplate);
- Context context = getContext();
- mDataInfoController.updateDataLimit(info,
- services.mPolicyEditor.getPolicy(mDefaultTemplate));
-
- if (mSummaryPreference != null) {
- mSummaryPreference.setTitle(
- formatUsage(context, getString(mDataUsageTemplate), info.usageLevel));
- final long limit = mDataInfoController.getSummaryLimit(info);
- mSummaryPreference.setSummary(info.period);
- if (limit <= 0) {
- mSummaryPreference.setChartEnabled(false);
- } else {
- mSummaryPreference.setChartEnabled(true);
- mSummaryPreference.setLabels(Formatter.formatFileSize(context, 0),
- Formatter.formatFileSize(context, limit));
- mSummaryPreference.setRatios(info.usageLevel / (float) limit, 0,
- (limit - info.usageLevel) / (float) limit);
- }
- }
- if (mLimitPreference != null && (info.warningLevel > 0 || info.limitLevel > 0)) {
- String warning = Formatter.formatFileSize(context, info.warningLevel);
- String limit = Formatter.formatFileSize(context, info.limitLevel);
- mLimitPreference.setSummary(getString(info.limitLevel <= 0 ? R.string.cell_warning_only
- : R.string.cell_warning_and_limit, warning, limit));
- } else if (mLimitPreference != null) {
- mLimitPreference.setSummary(null);
- }
-
- PreferenceScreen screen = getPreferenceScreen();
- for (int i = 1; i < screen.getPreferenceCount(); i++) {
- ((TemplatePreferenceCategory) screen.getPreference(i)).pushTemplates(services);
- }
- }
-
- @Override
- public int getMetricsCategory() {
- return MetricsEvent.DATA_USAGE_SUMMARY;
- }
-
- @Override
- public NetworkPolicyEditor getNetworkPolicyEditor() {
- return services.mPolicyEditor;
- }
-
- @Override
- public NetworkTemplate getNetworkTemplate() {
- return mDefaultTemplate;
- }
-
- @Override
- public void updateDataUsage() {
- updateState();
- }
-
- private static class SummaryProvider
- implements SummaryLoader.SummaryProvider {
-
- private final Activity mActivity;
- private final SummaryLoader mSummaryLoader;
- private final DataUsageController mDataController;
-
- public SummaryProvider(Activity activity, SummaryLoader summaryLoader) {
- mActivity = activity;
- mSummaryLoader = summaryLoader;
- mDataController = new DataUsageController(activity);
- }
-
- @Override
- public void setListening(boolean listening) {
- if (listening) {
- DataUsageController.DataUsageInfo info = mDataController.getDataUsageInfo();
- String used;
- if (info == null) {
- used = Formatter.formatFileSize(mActivity, 0);
- } else if (info.limitLevel <= 0) {
- used = Formatter.formatFileSize(mActivity, info.usageLevel);
- } else {
- used = Utils.formatPercentage(info.usageLevel, info.limitLevel);
- }
- mSummaryLoader.setSummary(this,
- mActivity.getString(R.string.data_usage_summary_format, used));
- }
- }
- }
-
- public static final SummaryLoader.SummaryProviderFactory SUMMARY_PROVIDER_FACTORY
- = SummaryProvider::new;
-
- /**
- * For search
- */
- public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
- new BaseSearchIndexProvider() {
-
- @Override
- public List<SearchIndexableResource> getXmlResourcesToIndex(Context context,
- boolean enabled) {
- List<SearchIndexableResource> resources = new ArrayList<>();
- SearchIndexableResource resource = new SearchIndexableResource(context);
- resource.xmlResId = R.xml.data_usage_legacy;
- resources.add(resource);
-
- resource = new SearchIndexableResource(context);
- resource.xmlResId = R.xml.data_usage_cellular;
- resources.add(resource);
-
- resource = new SearchIndexableResource(context);
- resource.xmlResId = R.xml.data_usage_wifi;
- resources.add(resource);
-
- return resources;
- }
-
- @Override
- public List<String> getNonIndexableKeys(Context context) {
- List<String> keys = super.getNonIndexableKeys(context);
-
- if (!DataUsageUtils.hasMobileData(context)) {
- keys.add(KEY_MOBILE_USAGE_TITLE);
- keys.add(KEY_MOBILE_DATA_USAGE_TOGGLE);
- keys.add(KEY_MOBILE_DATA_USAGE);
- keys.add(KEY_MOBILE_BILLING_CYCLE);
- }
-
- if (!DataUsageUtils.hasWifiRadio(context)) {
- keys.add(KEY_WIFI_DATA_USAGE);
- }
-
- // This title is named Wifi, and will confuse users.
- keys.add(KEY_WIFI_USAGE_TITLE);
-
- return keys;
- }
- };
-}
diff --git a/src/com/android/settings/datetime/timezone/BaseTimeZoneAdapter.java b/src/com/android/settings/datetime/timezone/BaseTimeZoneAdapter.java
index 1a868b8..253bd2f 100644
--- a/src/com/android/settings/datetime/timezone/BaseTimeZoneAdapter.java
+++ b/src/com/android/settings/datetime/timezone/BaseTimeZoneAdapter.java
@@ -78,7 +78,7 @@
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch(viewType) {
case TYPE_HEADER: {
- final View view = inflater.inflate(R.layout.preference_category_material_settings,
+ final View view = inflater.inflate(R.layout.preference_category_material,
parent, false);
return new HeaderViewHolder(view);
}
diff --git a/src/com/android/settings/development/qstile/DevelopmentTiles.java b/src/com/android/settings/development/qstile/DevelopmentTiles.java
index 5482b02..ec017c5 100644
--- a/src/com/android/settings/development/qstile/DevelopmentTiles.java
+++ b/src/com/android/settings/development/qstile/DevelopmentTiles.java
@@ -16,7 +16,9 @@
package com.android.settings.development.qstile;
+import android.content.ComponentName;
import android.content.Context;
+import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
@@ -25,7 +27,6 @@
import android.provider.Settings;
import android.service.quicksettings.Tile;
import android.service.quicksettings.TileService;
-import androidx.annotation.VisibleForTesting;
import android.util.Log;
import android.view.IWindowManager;
import android.view.ThreadedRenderer;
@@ -34,9 +35,12 @@
import android.widget.Toast;
import com.android.internal.app.LocalePicker;
+import com.android.internal.statusbar.IStatusBarService;
import com.android.settingslib.development.DevelopmentSettingsEnabler;
import com.android.settingslib.development.SystemPropPoker;
+import androidx.annotation.VisibleForTesting;
+
public abstract class DevelopmentTiles extends TileService {
private static final String TAG = "DevelopmentTiles";
@@ -58,6 +62,20 @@
setIsEnabled(false);
SystemPropPoker.getInstance().poke();
}
+ final ComponentName cn = new ComponentName(getPackageName(), getClass().getName());
+ try {
+ getPackageManager().setComponentEnabledSetting(
+ cn, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
+ PackageManager.DONT_KILL_APP);
+ final IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
+ ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
+ if (statusBarService != null) {
+ statusBarService.remTile(cn);
+ }
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to modify QS tile for component " +
+ cn.toString(), e);
+ }
state = Tile.STATE_UNAVAILABLE;
} else {
state = isEnabled() ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE;
diff --git a/src/com/android/settings/deviceinfo/imei/ImeiInfoDialogController.java b/src/com/android/settings/deviceinfo/imei/ImeiInfoDialogController.java
index 71da4a3..4157886 100644
--- a/src/com/android/settings/deviceinfo/imei/ImeiInfoDialogController.java
+++ b/src/com/android/settings/deviceinfo/imei/ImeiInfoDialogController.java
@@ -53,6 +53,9 @@
static final int ID_GSM_SETTINGS = R.id.gsm_settings;
private static CharSequence getTextAsDigits(CharSequence text) {
+ if (TextUtils.isEmpty(text)) {
+ return "";
+ }
if (TextUtils.isDigitsOnly(text)) {
final Spannable spannable = new SpannableStringBuilder(text);
final TtsSpan span = new TtsSpan.DigitsBuilder(text.toString()).build();
diff --git a/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java b/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java
index 9604f74..0272b5c 100644
--- a/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java
+++ b/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceController.java
@@ -402,10 +402,14 @@
try {
final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
+ // b/33117269: Note that launchIntent may launch activity in different task which set
+ // different launchMode (e.g. Files), using startActivityForesult to set task as
+ // source task, and set requestCode as 0 means don't care about returnCode currently.
if (userId == -1) {
- mFragment.startActivity(intent);
+ mFragment.startActivityForResult(intent, 0 /* requestCode not used */);
} else {
- mFragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
+ mFragment.getActivity().startActivityForResultAsUser(intent,
+ 0 /* requestCode not used */, new UserHandle(userId));
}
} catch (ActivityNotFoundException e) {
Log.w(TAG, "No activity found for " + intent);
diff --git a/src/com/android/settings/display/AppGridView.java b/src/com/android/settings/display/AppGridView.java
index 0027537..d48eb09 100644
--- a/src/com/android/settings/display/AppGridView.java
+++ b/src/com/android/settings/display/AppGridView.java
@@ -22,7 +22,6 @@
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.UserHandle;
-import androidx.annotation.VisibleForTesting;
import android.util.AttributeSet;
import android.util.IconDrawableFactory;
import android.view.View;
@@ -37,28 +36,32 @@
import java.util.Collections;
import java.util.List;
+import androidx.annotation.VisibleForTesting;
+
public class AppGridView extends GridView {
public AppGridView(Context context) {
- this(context, null);
+ super(context);
+ init(context);
}
public AppGridView(Context context, AttributeSet attrs) {
- this(context, attrs, 0);
+ super(context, attrs);
+ init(context);
}
public AppGridView(Context context, AttributeSet attrs, int defStyleAttr) {
- this(context, attrs, defStyleAttr, 0);
+ super(context, attrs, defStyleAttr);
+ init(context);
}
public AppGridView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleResId) {
super(context, attrs, defStyleAttr, defStyleResId);
- setNumColumns(AUTO_FIT);
+ init(context);
- final int columnWidth = getResources().getDimensionPixelSize(
- R.dimen.screen_zoom_preview_app_icon_width);
- setColumnWidth(columnWidth);
+ }
+ private void init(Context context) {
setAdapter(new AppsAdapter(context, R.layout.screen_zoom_preview_app_icon,
android.R.id.text1, android.R.id.icon1));
}
@@ -105,6 +108,7 @@
}
private void loadAllApps() {
+ final int needAppCount = 6;
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
@@ -117,6 +121,9 @@
if (label != null) {
results.add(new ActivityEntry(info, label.toString(), iconFactory));
}
+ if (results.size() >= needAppCount) {
+ break;
+ }
}
Collections.sort(results);
diff --git a/src/com/android/settings/display/ColorModePreferenceController.java b/src/com/android/settings/display/ColorModePreferenceController.java
index ebb4370..6a86cd9 100644
--- a/src/com/android/settings/display/ColorModePreferenceController.java
+++ b/src/com/android/settings/display/ColorModePreferenceController.java
@@ -27,15 +27,14 @@
public class ColorModePreferenceController extends BasePreferenceController {
private static final String TAG = "ColorModePreference";
- private static final String KEY_COLOR_MODE = "color_mode";
private static final int SURFACE_FLINGER_TRANSACTION_QUERY_WIDE_COLOR = 1024;
private final ConfigurationWrapper mConfigWrapper;
private ColorDisplayController mColorDisplayController;
- public ColorModePreferenceController(Context context) {
- super(context, KEY_COLOR_MODE);
+ public ColorModePreferenceController(Context context, String key) {
+ super(context, key);
mConfigWrapper = new ConfigurationWrapper();
}
@@ -43,7 +42,7 @@
public int getAvailabilityStatus() {
return mConfigWrapper.isScreenWideColorGamut()
&& !getColorDisplayController().getAccessibilityTransformActivated() ?
- AVAILABLE : DISABLED_FOR_USER;
+ AVAILABLE_UNSEARCHABLE : DISABLED_FOR_USER;
}
@Override
diff --git a/src/com/android/settings/display/ColorModePreferenceFragment.java b/src/com/android/settings/display/ColorModePreferenceFragment.java
index ab17c72..874dc71 100644
--- a/src/com/android/settings/display/ColorModePreferenceFragment.java
+++ b/src/com/android/settings/display/ColorModePreferenceFragment.java
@@ -15,6 +15,8 @@
import android.content.Context;
import android.graphics.drawable.Drawable;
+import android.provider.SearchIndexableResource;
+
import androidx.annotation.VisibleForTesting;
import androidx.preference.PreferenceScreen;
@@ -23,13 +25,18 @@
import com.android.settings.applications.LayoutPreference;
import com.android.settings.R;
+import com.android.settings.search.BaseSearchIndexProvider;
+import com.android.settings.search.Indexable;
import com.android.settings.widget.RadioButtonPickerFragment;
+import com.android.settingslib.search.SearchIndexable;
import com.android.settingslib.widget.CandidateInfo;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
@SuppressWarnings("WeakerAccess")
+@SearchIndexable
public class ColorModePreferenceFragment extends RadioButtonPickerFragment
implements ColorDisplayController.Callback {
@@ -181,4 +188,15 @@
getActivity().onBackPressed();
}
}
+
+ public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+ new BaseSearchIndexProvider() {
+ @Override
+ public List<SearchIndexableResource> getXmlResourcesToIndex(
+ Context context, boolean enabled) {
+ final SearchIndexableResource sir = new SearchIndexableResource(context);
+ sir.xmlResId = R.xml.color_mode_settings;
+ return Arrays.asList(sir);
+ }
+ };
}
diff --git a/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java b/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java
index c25463a..af1de48 100644
--- a/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java
+++ b/src/com/android/settings/fuelgauge/AdvancedPowerUsageDetail.java
@@ -20,7 +20,6 @@
import android.app.Activity;
import android.app.ActivityManager;
import android.app.LoaderManager;
-import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
@@ -28,7 +27,6 @@
import android.os.BatteryStats;
import android.os.Bundle;
import android.os.UserHandle;
-import android.os.UserManager;
import androidx.annotation.VisibleForTesting;
import androidx.preference.Preference;
import android.text.TextUtils;
@@ -43,6 +41,8 @@
import com.android.settings.SettingsActivity;
import com.android.settings.Utils;
import com.android.settings.applications.LayoutPreference;
+import com.android.settings.applications.appinfo.AppButtonsPreferenceController;
+import com.android.settings.applications.appinfo.ButtonActionDialogFragment;
import com.android.settings.core.InstrumentedPreferenceFragment;
import com.android.settings.core.SubSettingLauncher;
import com.android.settings.dashboard.DashboardFragment;
@@ -112,9 +112,6 @@
private AppButtonsPreferenceController mAppButtonsPreferenceController;
private BackgroundActivityPreferenceController mBackgroundActivityPreferenceController;
- private DevicePolicyManager mDpm;
- private UserManager mUserManager;
- private PackageManager mPackageManager;
private List<Anomaly> mAnomalies;
private String mPackageName;
@@ -203,9 +200,6 @@
super.onAttach(activity);
mState = ApplicationsState.getInstance(getActivity().getApplication());
- mDpm = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
- mUserManager = (UserManager) activity.getSystemService(Context.USER_SERVICE);
- mPackageManager = activity.getPackageManager();
mBatteryUtils = BatteryUtils.getInstance(getContext());
}
@@ -332,8 +326,8 @@
controllers.add(new BatteryOptimizationPreferenceController(
(SettingsActivity) getActivity(), this, packageName));
mAppButtonsPreferenceController = new AppButtonsPreferenceController(
- (SettingsActivity) getActivity(), this, getLifecycle(), packageName, mState, mDpm,
- mUserManager, mPackageManager, REQUEST_UNINSTALL, REQUEST_REMOVE_DEVICE_ADMIN);
+ (SettingsActivity) getActivity(), this, getLifecycle(), packageName, mState,
+ REQUEST_UNINSTALL, REQUEST_REMOVE_DEVICE_ADMIN);
controllers.add(mAppButtonsPreferenceController);
return controllers;
diff --git a/src/com/android/settings/fuelgauge/BatteryHistoryDetail.java b/src/com/android/settings/fuelgauge/BatteryHistoryDetail.java
index 3661467..1343fef 100644
--- a/src/com/android/settings/fuelgauge/BatteryHistoryDetail.java
+++ b/src/com/android/settings/fuelgauge/BatteryHistoryDetail.java
@@ -25,12 +25,13 @@
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
+
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.os.BatteryStatsHelper;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.fuelgauge.BatteryActiveView.BatteryActiveProvider;
-import com.android.settings.graph.UsageView;
+import com.android.settings.widget.UsageView;
public class BatteryHistoryDetail extends SettingsPreferenceFragment {
public static final String EXTRA_STATS = "stats";
@@ -76,7 +77,7 @@
mPhoneParser = new BatteryCellParser();
setHasOptionsMenu(true);
}
-
+
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
diff --git a/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java b/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java
index 6ef0957..89b3edd 100644
--- a/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java
+++ b/src/com/android/settings/fuelgauge/BatteryHistoryPreference.java
@@ -17,15 +17,17 @@
package com.android.settings.fuelgauge;
import android.content.Context;
-import androidx.annotation.VisibleForTesting;
-import androidx.preference.Preference;
-import androidx.preference.PreferenceViewHolder;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
+
import com.android.internal.os.BatteryStatsHelper;
import com.android.settings.R;
-import com.android.settings.graph.UsageView;
+import com.android.settings.widget.UsageView;
+
+import androidx.annotation.VisibleForTesting;
+import androidx.preference.Preference;
+import androidx.preference.PreferenceViewHolder;
/**
* Custom preference for displaying power consumption as a bar and an icon on the left for the
diff --git a/src/com/android/settings/fuelgauge/BatteryInfo.java b/src/com/android/settings/fuelgauge/BatteryInfo.java
index 9afaaba..f642d30 100644
--- a/src/com/android/settings/fuelgauge/BatteryInfo.java
+++ b/src/com/android/settings/fuelgauge/BatteryInfo.java
@@ -24,18 +24,19 @@
import android.os.BatteryStats.HistoryItem;
import android.os.Bundle;
import android.os.SystemClock;
-import androidx.annotation.WorkerThread;
import android.text.format.Formatter;
import android.util.SparseIntArray;
import com.android.internal.os.BatteryStatsHelper;
import com.android.settings.Utils;
-import com.android.settings.graph.UsageView;
import com.android.settings.overlay.FeatureFactory;
+import com.android.settings.widget.UsageView;
import com.android.settingslib.R;
import com.android.settingslib.utils.PowerUtil;
import com.android.settingslib.utils.StringUtil;
+import androidx.annotation.WorkerThread;
+
public class BatteryInfo {
public CharSequence chargeLabel;
@@ -129,7 +130,7 @@
remaining = context.getString(R.string.remaining_length_format,
Formatter.formatShortElapsedTime(context, remainingTimeUs / 1000));
}
- view.setBottomLabels(new CharSequence[]{timeString, remaining});
+ view.setBottomLabels(new CharSequence[] {timeString, remaining});
}
public static void getBatteryInfo(final Context context, final Callback callback) {
@@ -173,7 +174,7 @@
if (discharging && provider != null
&& provider.isEnhancedBatteryPredictionEnabled(context)) {
Estimate estimate = provider.getEnhancedBatteryPrediction(context);
- if(estimate != null) {
+ if (estimate != null) {
BatteryUtils
.logRuntime(LOG_TAG, "time for enhanced BatteryInfo", startTime);
return BatteryInfo.getBatteryInfo(context, batteryBroadcast, stats,
diff --git a/src/com/android/settings/fuelgauge/BatteryUtils.java b/src/com/android/settings/fuelgauge/BatteryUtils.java
index 4a3e6d4..83b0e1b 100644
--- a/src/com/android/settings/fuelgauge/BatteryUtils.java
+++ b/src/com/android/settings/fuelgauge/BatteryUtils.java
@@ -24,18 +24,12 @@
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.BatteryStats;
-import android.os.Bundle;
import android.os.Build;
+import android.os.Bundle;
import android.os.Process;
import android.os.SystemClock;
import android.os.UserHandle;
import android.os.UserManager;
-import androidx.annotation.IntDef;
-import androidx.annotation.Nullable;
-import androidx.annotation.StringRes;
-import androidx.annotation.VisibleForTesting;
-import androidx.annotation.WorkerThread;
-import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.util.SparseLongArray;
@@ -48,7 +42,6 @@
import com.android.settings.fuelgauge.batterytip.AnomalyInfo;
import com.android.settings.fuelgauge.batterytip.StatsManagerConfig;
import com.android.settings.overlay.FeatureFactory;
-
import com.android.settingslib.fuelgauge.PowerWhitelistBackend;
import com.android.settingslib.utils.PowerUtil;
@@ -58,6 +51,12 @@
import java.util.Comparator;
import java.util.List;
+import androidx.annotation.IntDef;
+import androidx.annotation.Nullable;
+import androidx.annotation.StringRes;
+import androidx.annotation.VisibleForTesting;
+import androidx.annotation.WorkerThread;
+
/**
* Utils for battery operation
*/
@@ -93,14 +92,14 @@
public static BatteryUtils getInstance(Context context) {
if (sInstance == null || sInstance.isDataCorrupted()) {
- sInstance = new BatteryUtils(context);
+ sInstance = new BatteryUtils(context.getApplicationContext());
}
return sInstance;
}
@VisibleForTesting
BatteryUtils(Context context) {
- mContext = context.getApplicationContext();
+ mContext = context;
mPackageManager = context.getPackageManager();
mAppOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
mPowerUsageFeatureProvider = FeatureFactory.getFactory(
diff --git a/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceController.java b/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceController.java
index b082eeb..379b995 100644
--- a/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceController.java
+++ b/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceController.java
@@ -43,6 +43,7 @@
public class AutoBatterySeekBarPreferenceController extends BasePreferenceController implements
LifecycleObserver, OnStart, OnStop, SeekBarPreference.OnPreferenceChangeListener {
private static final String TAG = "AutoBatterySeekBarPreferenceController";
+ private static final int INTERVAL = 5;
@VisibleForTesting
static final String KEY_AUTO_BATTERY_SEEK_BAR = "battery_saver_seek_bar";
private SeekBarPreference mPreference;
@@ -92,7 +93,7 @@
public boolean onPreferenceChange(Preference preference, Object newValue) {
final int progress = (int) newValue;
Settings.Global.putInt(mContext.getContentResolver(),
- Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, progress);
+ Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, progress * INTERVAL);
return true;
}
@@ -102,7 +103,7 @@
// Override the max value with LOW_POWER_MODE_TRIGGER_LEVEL_MAX, if set.
final int maxLevel = Settings.Global.getInt(contentResolver,
- Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL_MAX, 0);
+ Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL_MAX, 0) / INTERVAL;
if (maxLevel > 0) {
if (!(preference instanceof SeekBarPreference)) {
Log.e(TAG, "Unexpected preference class: " + preference.getClass());
@@ -127,7 +128,7 @@
preference.setTitle(mContext.getString(R.string.battery_saver_seekbar_title,
Utils.formatPercentage(level)));
SeekBarPreference seekBarPreference = (SeekBarPreference) preference;
- seekBarPreference.setProgress(level);
+ seekBarPreference.setProgress(level / INTERVAL);
seekBarPreference.setSeekBarContentDescription(
mContext.getString(R.string.battery_saver_turn_on_automatically_title));
}
diff --git a/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobService.java b/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobService.java
index f7793aa..2dc35f1 100644
--- a/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobService.java
+++ b/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobService.java
@@ -157,7 +157,7 @@
metricsFeatureProvider.action(context,
MetricsProto.MetricsEvent.ACTION_ANOMALY_IGNORED,
packageName,
- Pair.create(MetricsProto.MetricsEvent.FIELD_CONTEXT,
+ Pair.create(MetricsProto.MetricsEvent.FIELD_ANOMALY_TYPE,
anomalyInfo.anomalyType),
Pair.create(MetricsProto.MetricsEvent.FIELD_APP_VERSION_CODE,
versionCode));
diff --git a/src/com/android/settings/fuelgauge/batterytip/StatsManagerConfig.java b/src/com/android/settings/fuelgauge/batterytip/StatsManagerConfig.java
index a0d4e9b..7d81c42 100644
--- a/src/com/android/settings/fuelgauge/batterytip/StatsManagerConfig.java
+++ b/src/com/android/settings/fuelgauge/batterytip/StatsManagerConfig.java
@@ -46,15 +46,181 @@
AnomalyType.EXCESSIVE_WAKEUPS_IN_BACKGROUND,
AnomalyType.EXCESSIVE_UNOPTIMIZED_BLE_SCAN,
AnomalyType.EXCESSIVE_BACKGROUND_SERVICE,
- AnomalyType.EXCESSIVE_WIFI_SCAN})
+ AnomalyType.EXCESSIVE_WIFI_SCAN,
+ AnomalyType.EXCESSIVE_FLASH_WRITES,
+ AnomalyType.EXCESSIVE_MEMORY_IN_BACKGROUND,
+ AnomalyType.EXCESSIVE_DAVEY_RATE,
+ AnomalyType.EXCESSIVE_JANKY_FRAMES,
+ AnomalyType.SLOW_COLD_START_TIME,
+ AnomalyType.SLOW_HOT_START_TIME,
+ AnomalyType.SLOW_WARM_START_TIME,
+ AnomalyType.EXCESSIVE_BACKGROUND_SYNCS,
+ AnomalyType.EXCESSIVE_GPS_SCANS_IN_BACKGROUND,
+ AnomalyType.EXCESSIVE_JOB_SCHEDULING,
+ AnomalyType.EXCESSIVE_MOBILE_NETWORK_IN_BACKGROUND,
+ AnomalyType.EXCESSIVE_WIFI_LOCK_TIME,
+ AnomalyType.JOB_TIMED_OUT,
+ AnomalyType.LONG_UNOPTIMIZED_BLE_SCAN,
+ AnomalyType.BACKGROUND_ANR,
+ AnomalyType.BACKGROUND_CRASH_RATE,
+ AnomalyType.EXCESSIVE_ANR_LOOPING,
+ AnomalyType.EXCESSIVE_ANRS,
+ AnomalyType.EXCESSIVE_CRASH_RATE,
+ AnomalyType.EXCESSIVE_CRASH_LOOPING,
+ AnomalyType.NUMBER_OF_OPEN_FILES,
+ })
public @interface AnomalyType {
+ /**
+ * This represents an error condition in the anomaly detection.
+ */
int NULL = -1;
+
+ /**
+ * The anomaly type does not match any other defined type.
+ */
int UNKNOWN_REASON = 0;
+
+ /**
+ * The application held a partial (screen off) wake lock for a period of time that
+ * exceeded the threshold with the screen off when not charging.
+ */
int EXCESSIVE_WAKELOCK_ALL_SCREEN_OFF = 1;
+
+ /**
+ * The application exceeded the maximum number of wakeups while in the background
+ * when not charging.
+ */
int EXCESSIVE_WAKEUPS_IN_BACKGROUND = 2;
+
+ /**
+ * The application did unoptimized Bluetooth scans too frequently when not charging.
+ */
int EXCESSIVE_UNOPTIMIZED_BLE_SCAN = 3;
+
+ /**
+ * The application ran in the background for a period of time that exceeded the
+ * threshold.
+ */
int EXCESSIVE_BACKGROUND_SERVICE = 4;
+
+ /**
+ * The application exceeded the maximum number of wifi scans when not charging.
+ */
int EXCESSIVE_WIFI_SCAN = 5;
+
+ /**
+ * The application exceed the maximum number of flash writes
+ */
+ int EXCESSIVE_FLASH_WRITES = 6;
+
+ /**
+ * The application used more than the maximum memory, while not spending any time
+ * in the foreground.
+ */
+ int EXCESSIVE_MEMORY_IN_BACKGROUND = 7;
+
+ /**
+ * The application exceeded the maximum percentage of frames with a render rate of
+ * greater than 700ms.
+ */
+ int EXCESSIVE_DAVEY_RATE = 8;
+
+ /**
+ * The application exceeded the maximum percentage of frames with a render rate
+ * greater than 16ms.
+ */
+ int EXCESSIVE_JANKY_FRAMES = 9;
+
+ /**
+ * The application exceeded the maximum cold start time - the app has not been
+ * launched since last system start, died or was killed.
+ */
+ int SLOW_COLD_START_TIME = 10;
+
+ /**
+ * The application exceeded the maximum hot start time - the app and activity are
+ * already in memory.
+ */
+ int SLOW_HOT_START_TIME = 11;
+
+ /**
+ * The application exceeded the maximum warm start time - the app was already in
+ * memory but the activity wasn’t created yet or was removed from memory.
+ */
+ int SLOW_WARM_START_TIME = 12;
+
+ /**
+ * The application exceeded the maximum number of syncs while in the background.
+ */
+ int EXCESSIVE_BACKGROUND_SYNCS = 13;
+
+ /**
+ * The application exceeded the maximum number of gps scans while in the background.
+ */
+ int EXCESSIVE_GPS_SCANS_IN_BACKGROUND = 14;
+
+ /**
+ * The application scheduled more than the maximum number of jobs while not charging.
+ */
+ int EXCESSIVE_JOB_SCHEDULING = 15;
+
+ /**
+ * The application exceeded the maximum amount of mobile network traffic while in
+ * the background.
+ */
+ int EXCESSIVE_MOBILE_NETWORK_IN_BACKGROUND = 16;
+
+ /**
+ * The application held the WiFi lock for more than the maximum amount of time while
+ * not charging.
+ */
+ int EXCESSIVE_WIFI_LOCK_TIME = 17;
+
+ /**
+ * The application scheduled a job that ran longer than the maximum amount of time.
+ */
+ int JOB_TIMED_OUT = 18;
+
+ /**
+ * The application did an unoptimized Bluetooth scan that exceeded the maximum
+ * time while in the background.
+ */
+ int LONG_UNOPTIMIZED_BLE_SCAN = 19;
+
+ /**
+ * The application exceeded the maximum ANR rate while in the background.
+ */
+ int BACKGROUND_ANR = 20;
+
+ /**
+ * The application exceeded the maximum crash rate while in the background.
+ */
+ int BACKGROUND_CRASH_RATE = 21;
+
+ /**
+ * The application exceeded the maximum ANR-looping rate.
+ */
+ int EXCESSIVE_ANR_LOOPING = 22;
+
+ /**
+ * The application exceeded the maximum ANR rate.
+ */
+ int EXCESSIVE_ANRS = 23;
+
+ /**
+ * The application exceeded the maximum crash rate.
+ */
+ int EXCESSIVE_CRASH_RATE = 24;
+
+ /**
+ * The application exceeded the maximum crash-looping rate.
+ */
+ int EXCESSIVE_CRASH_LOOPING = 25;
+
+ /**
+ * The application crashed because no more file descriptors were available.
+ */
+ int NUMBER_OF_OPEN_FILES = 26;
}
}
diff --git a/src/com/android/settings/gestures/PreventRingingGestureSettings.java b/src/com/android/settings/gestures/PreventRingingGestureSettings.java
index 58ff5fa..b8d157c 100644
--- a/src/com/android/settings/gestures/PreventRingingGestureSettings.java
+++ b/src/com/android/settings/gestures/PreventRingingGestureSettings.java
@@ -60,7 +60,7 @@
@Override
public int getHelpResource() {
- return 0;
+ return R.string.help_uri_prevent_ringing_gesture;
}
public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
diff --git a/src/com/android/settings/gestures/PreventRingingParentPreferenceController.java b/src/com/android/settings/gestures/PreventRingingParentPreferenceController.java
index 8814765..afb3431 100644
--- a/src/com/android/settings/gestures/PreventRingingParentPreferenceController.java
+++ b/src/com/android/settings/gestures/PreventRingingParentPreferenceController.java
@@ -16,12 +16,20 @@
package com.android.settings.gestures;
-import android.content.Context;
+import static android.provider.Settings.Secure.VOLUME_HUSH_GESTURE;
+import static android.provider.Settings.Secure.VOLUME_HUSH_MUTE;
+import static android.provider.Settings.Secure.VOLUME_HUSH_VIBRATE;
+import android.content.Context;
+import android.provider.Settings;
+
+import com.android.settings.R;
import com.android.settings.core.BasePreferenceController;
public class PreventRingingParentPreferenceController extends BasePreferenceController {
+ final String SECURE_KEY = VOLUME_HUSH_GESTURE;
+
public PreventRingingParentPreferenceController(Context context, String preferenceKey) {
super(context, preferenceKey);
}
@@ -33,4 +41,21 @@
? AVAILABLE_UNSEARCHABLE : UNSUPPORTED_ON_DEVICE;
}
+ @Override
+ public CharSequence getSummary() {
+ int value = Settings.Secure.getInt(
+ mContext.getContentResolver(), SECURE_KEY, VOLUME_HUSH_VIBRATE);
+ int summary;
+ switch (value) {
+ case VOLUME_HUSH_VIBRATE:
+ summary = R.string.prevent_ringing_option_vibrate_summary;
+ break;
+ case VOLUME_HUSH_MUTE:
+ summary = R.string.prevent_ringing_option_mute_summary;
+ break;
+ default:
+ summary = R.string.prevent_ringing_option_none_summary;
+ }
+ return mContext.getText(summary);
+ }
}
diff --git a/src/com/android/settings/gestures/PreventRingingPreferenceController.java b/src/com/android/settings/gestures/PreventRingingPreferenceController.java
index be55151..7f685e5 100644
--- a/src/com/android/settings/gestures/PreventRingingPreferenceController.java
+++ b/src/com/android/settings/gestures/PreventRingingPreferenceController.java
@@ -50,8 +50,6 @@
@VisibleForTesting
boolean mVideoPaused;
- private final String SECURE_KEY = VOLUME_HUSH_GESTURE;
-
public PreventRingingPreferenceController(Context context, String key) {
super(context, key);
}
@@ -96,24 +94,6 @@
}
@Override
- public CharSequence getSummary() {
- int value = Settings.Secure.getInt(
- mContext.getContentResolver(), SECURE_KEY, VOLUME_HUSH_VIBRATE);
- int summary;
- switch (value) {
- case VOLUME_HUSH_VIBRATE:
- summary = R.string.prevent_ringing_option_vibrate_summary;
- break;
- case VOLUME_HUSH_MUTE:
- summary = R.string.prevent_ringing_option_mute_summary;
- break;
- default:
- summary = R.string.prevent_ringing_option_none_summary;
- }
- return mContext.getString(summary);
- }
-
- @Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
mVideoPaused = savedInstanceState.getBoolean(KEY_VIDEO_PAUSED, false);
diff --git a/src/com/android/settings/location/LocationServicePreferenceController.java b/src/com/android/settings/location/LocationServicePreferenceController.java
index f865b44..9860abd 100644
--- a/src/com/android/settings/location/LocationServicePreferenceController.java
+++ b/src/com/android/settings/location/LocationServicePreferenceController.java
@@ -25,6 +25,7 @@
import androidx.preference.PreferenceScreen;
import android.util.Log;
+import com.android.settings.Utils;
import com.android.settings.widget.RestrictedAppPreference;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.core.lifecycle.LifecycleObserver;
@@ -130,8 +131,11 @@
private List<Preference> getLocationServices() {
// If location access is locked down by device policy then we only show injected settings
// for the primary profile.
+ final int profileUserId = Utils.getManagedProfileId(mUserManager, UserHandle.myUserId());
+
return mInjector.getInjectedSettings(mFragment.getPreferenceManager().getContext(),
- mLocationEnabler.isManagedProfileRestrictedByBase()
+ (profileUserId != UserHandle.USER_NULL
+ && mLocationEnabler.getShareLocationEnforcedAdmin(profileUserId) != null)
? UserHandle.myUserId() : UserHandle.USER_CURRENT);
}
}
diff --git a/src/com/android/settings/location/LocationSettings.java b/src/com/android/settings/location/LocationSettings.java
index 9f23396..638518c 100644
--- a/src/com/android/settings/location/LocationSettings.java
+++ b/src/com/android/settings/location/LocationSettings.java
@@ -21,8 +21,7 @@
import android.location.SettingInjectorService;
import android.os.Bundle;
import android.provider.SearchIndexableResource;
-import androidx.preference.Preference;
-import androidx.preference.PreferenceGroup;
+
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.R;
import com.android.settings.SettingsActivity;
@@ -42,6 +41,9 @@
import java.util.Comparator;
import java.util.List;
+import androidx.preference.Preference;
+import androidx.preference.PreferenceGroup;
+
/**
* System location settings (Settings > Location). The screen has three parts:
* <ul>
@@ -177,5 +179,12 @@
return buildPreferenceControllers(context, null /* fragment */,
null /* lifecycle */);
}
+
+ @Override
+ public List<String> getNonIndexableKeys(Context context) {
+ final List<String> niks = super.getNonIndexableKeys(context);
+ niks.add("recent_location_requests_see_all_button"); // 'See all' button
+ return niks;
+ }
};
}
diff --git a/src/com/android/settings/network/ApnSettings.java b/src/com/android/settings/network/ApnSettings.java
index e41d1b8..f80acd4 100755
--- a/src/com/android/settings/network/ApnSettings.java
+++ b/src/com/android/settings/network/ApnSettings.java
@@ -43,6 +43,7 @@
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
+import android.telephony.data.ApnSetting;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
@@ -54,7 +55,7 @@
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.TelephonyIntents;
-import com.android.internal.telephony.dataconnection.ApnSetting;
+import com.android.internal.telephony.dataconnection.ApnSettingUtils;
import com.android.internal.telephony.uicc.IccRecords;
import com.android.internal.telephony.uicc.UiccController;
import com.android.settings.R;
@@ -336,7 +337,8 @@
ArrayList<ApnPreference> mvnoList, IccRecords r, String mvnoType,
String mvnoMatchData) {
if (r != null && !TextUtils.isEmpty(mvnoType) && !TextUtils.isEmpty(mvnoMatchData)) {
- if (ApnSetting.mvnoMatches(r, mvnoType, mvnoMatchData)) {
+ if (ApnSettingUtils.mvnoMatches(r, ApnSetting.getMvnoTypeIntFromString(mvnoType),
+ mvnoMatchData)) {
mvnoList.add(pref);
// Since adding to mvno list, save mvno info
mMvnoType = mvnoType;
diff --git a/src/com/android/settings/nfc/AndroidBeamPreferenceController.java b/src/com/android/settings/nfc/AndroidBeamPreferenceController.java
index 12ab1b7..f99c47c 100644
--- a/src/com/android/settings/nfc/AndroidBeamPreferenceController.java
+++ b/src/com/android/settings/nfc/AndroidBeamPreferenceController.java
@@ -17,7 +17,6 @@
import android.content.Context;
import android.nfc.NfcAdapter;
-import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import com.android.settings.core.BasePreferenceController;
@@ -26,15 +25,12 @@
import com.android.settingslib.core.lifecycle.events.OnPause;
import com.android.settingslib.core.lifecycle.events.OnResume;
-import java.util.List;
-
public class AndroidBeamPreferenceController extends BasePreferenceController
implements LifecycleObserver, OnResume, OnPause {
public static final String KEY_ANDROID_BEAM_SETTINGS = "android_beam_settings";
private final NfcAdapter mNfcAdapter;
private AndroidBeamEnabler mAndroidBeamEnabler;
- private NfcAirplaneModeObserver mAirplaneModeObserver;
public AndroidBeamPreferenceController(Context context, String key) {
super(context, key);
@@ -52,12 +48,6 @@
final RestrictedPreference restrictedPreference =
(RestrictedPreference) screen.findPreference(getPreferenceKey());
mAndroidBeamEnabler = new AndroidBeamEnabler(mContext, restrictedPreference);
-
- // Manually set dependencies for NFC when not toggleable.
- if (!NfcPreferenceController.isToggleableInAirplaneMode(mContext)) {
- mAirplaneModeObserver = new NfcAirplaneModeObserver(mContext, mNfcAdapter,
- (Preference) restrictedPreference);
- }
}
@Override
@@ -70,9 +60,6 @@
@Override
public void onResume() {
- if (mAirplaneModeObserver != null) {
- mAirplaneModeObserver.register();
- }
if (mAndroidBeamEnabler != null) {
mAndroidBeamEnabler.resume();
}
@@ -80,9 +67,6 @@
@Override
public void onPause() {
- if (mAirplaneModeObserver != null) {
- mAirplaneModeObserver.unregister();
- }
if (mAndroidBeamEnabler != null) {
mAndroidBeamEnabler.pause();
}
diff --git a/src/com/android/settings/nfc/BaseNfcEnabler.java b/src/com/android/settings/nfc/BaseNfcEnabler.java
index 88bafb9..64c6d15 100644
--- a/src/com/android/settings/nfc/BaseNfcEnabler.java
+++ b/src/com/android/settings/nfc/BaseNfcEnabler.java
@@ -28,7 +28,7 @@
* preference. It will receive intent and update state to ensure preference show correct state.
*/
public abstract class BaseNfcEnabler {
- private final Context mContext;
+ protected final Context mContext;
protected final NfcAdapter mNfcAdapter;
private final IntentFilter mIntentFilter;
diff --git a/src/com/android/settings/nfc/NfcAirplaneModeObserver.java b/src/com/android/settings/nfc/NfcAirplaneModeObserver.java
index d0ce045..65ac655 100644
--- a/src/com/android/settings/nfc/NfcAirplaneModeObserver.java
+++ b/src/com/android/settings/nfc/NfcAirplaneModeObserver.java
@@ -70,12 +70,13 @@
}
mAirplaneMode = airplaneMode;
- boolean toggleable = mAirplaneMode != 1;
- if (toggleable) {
- mNfcAdapter.enable();
- } else {
+ if (mAirplaneMode == 1) {
+ // airplane mode is on, need to turn off NFC, and check if user can toggle it
mNfcAdapter.disable();
+ mPreference.setEnabled(NfcPreferenceController.isToggleableInAirplaneMode(mContext));
+ } else {
+ // airplane mode is off, no restriction
+ mPreference.setEnabled(true);
}
- mPreference.setEnabled(toggleable);
}
}
diff --git a/src/com/android/settings/nfc/NfcEnabler.java b/src/com/android/settings/nfc/NfcEnabler.java
index 507a053..777e7d1 100644
--- a/src/com/android/settings/nfc/NfcEnabler.java
+++ b/src/com/android/settings/nfc/NfcEnabler.java
@@ -18,8 +18,10 @@
import android.content.Context;
import android.nfc.NfcAdapter;
-import androidx.preference.SwitchPreference;
+import android.provider.Settings;
+import androidx.annotation.VisibleForTesting;
+import androidx.preference.SwitchPreference;
/**
* NfcEnabler is a helper to manage the Nfc on/off checkbox preference. It turns on/off Nfc
@@ -38,7 +40,7 @@
switch (newState) {
case NfcAdapter.STATE_OFF:
mPreference.setChecked(false);
- mPreference.setEnabled(true);
+ mPreference.setEnabled(isToggleable());
break;
case NfcAdapter.STATE_ON:
mPreference.setChecked(true);
@@ -54,4 +56,15 @@
break;
}
}
+
+ @VisibleForTesting
+ boolean isToggleable() {
+ if (NfcPreferenceController.isToggleableInAirplaneMode(mContext)
+ || !NfcPreferenceController.shouldTurnOffNFCInAirplaneMode(mContext)) {
+ return true;
+ }
+ final int airplaneMode = Settings.Global.getInt(
+ mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0);
+ return airplaneMode != 1;
+ }
}
diff --git a/src/com/android/settings/nfc/NfcPreferenceController.java b/src/com/android/settings/nfc/NfcPreferenceController.java
index e1fa1b3..0f68a9c 100644
--- a/src/com/android/settings/nfc/NfcPreferenceController.java
+++ b/src/com/android/settings/nfc/NfcPreferenceController.java
@@ -20,7 +20,7 @@
import android.nfc.NfcAdapter;
import android.provider.Settings;
-import androidx.preference.Preference;
+import androidx.annotation.VisibleForTesting;
import androidx.preference.PreferenceScreen;
import androidx.preference.SwitchPreference;
@@ -37,7 +37,8 @@
public static final String KEY_TOGGLE_NFC = "toggle_nfc";
private final NfcAdapter mNfcAdapter;
private NfcEnabler mNfcEnabler;
- private NfcAirplaneModeObserver mAirplaneModeObserver;
+ @VisibleForTesting
+ NfcAirplaneModeObserver mAirplaneModeObserver;
public NfcPreferenceController(Context context, String key) {
super(context, key);
@@ -57,10 +58,10 @@
mNfcEnabler = new NfcEnabler(mContext, switchPreference);
- // Manually set dependencies for NFC when not toggleable.
- if (!isToggleableInAirplaneMode(mContext)) {
- mAirplaneModeObserver = new NfcAirplaneModeObserver(mContext,
- mNfcAdapter, (Preference) switchPreference);
+ // Listen to airplane mode updates if NFC should be turned off when airplane mode is on
+ if (shouldTurnOffNFCInAirplaneMode(mContext) || isToggleableInAirplaneMode(mContext)) {
+ mAirplaneModeObserver =
+ new NfcAirplaneModeObserver(mContext, mNfcAdapter, switchPreference);
}
}
@@ -125,6 +126,12 @@
}
}
+ public static boolean shouldTurnOffNFCInAirplaneMode(Context context) {
+ final String airplaneModeRadios = Settings.Global.getString(context.getContentResolver(),
+ Settings.Global.AIRPLANE_MODE_RADIOS);
+ return airplaneModeRadios != null && airplaneModeRadios.contains(Settings.Global.RADIO_NFC);
+ }
+
public static boolean isToggleableInAirplaneMode(Context context) {
final String toggleable = Settings.Global.getString(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
diff --git a/src/com/android/settings/notification/NotificationPreferenceController.java b/src/com/android/settings/notification/NotificationPreferenceController.java
index 49bb08e..1ce42c2 100644
--- a/src/com/android/settings/notification/NotificationPreferenceController.java
+++ b/src/com/android/settings/notification/NotificationPreferenceController.java
@@ -138,11 +138,11 @@
protected boolean isChannelBlockable() {
if (mChannel != null && mAppRow != null) {
- if (!mAppRow.systemApp) {
- return true;
+ if (!isChannelConfigurable()) {
+ return mChannel.getImportance() == IMPORTANCE_NONE;
}
- return mChannel.isBlockableSystem()
+ return mChannel.isBlockableSystem() || !mAppRow.systemApp
|| mChannel.getImportance() == IMPORTANCE_NONE;
}
return false;
diff --git a/src/com/android/settings/notification/ZenModeSettings.java b/src/com/android/settings/notification/ZenModeSettings.java
index 240ab68..e05dabe 100644
--- a/src/com/android/settings/notification/ZenModeSettings.java
+++ b/src/com/android/settings/notification/ZenModeSettings.java
@@ -119,22 +119,22 @@
List<String> enabledCategories = getEnabledCategories(policy,
category -> PRIORITY_CATEGORY_ALARMS == category
|| PRIORITY_CATEGORY_MEDIA == category
- || PRIORITY_CATEGORY_SYSTEM == category);
+ || PRIORITY_CATEGORY_SYSTEM == category, false);
int numCategories = enabledCategories.size();
if (numCategories == 0) {
return mContext.getString(R.string.zen_sound_all_muted);
} else if (numCategories == 1) {
return mContext.getString(R.string.zen_sound_one_allowed,
- enabledCategories.get(0).toLowerCase());
+ enabledCategories.get(0));
} else if (numCategories == 2) {
return mContext.getString(R.string.zen_sound_two_allowed,
- enabledCategories.get(0).toLowerCase(),
- enabledCategories.get(1).toLowerCase());
+ enabledCategories.get(0),
+ enabledCategories.get(1));
} else if (numCategories == 3) {
return mContext.getString(R.string.zen_sound_three_allowed,
- enabledCategories.get(0).toLowerCase(),
- enabledCategories.get(1).toLowerCase(),
- enabledCategories.get(2).toLowerCase());
+ enabledCategories.get(0),
+ enabledCategories.get(1),
+ enabledCategories.get(2));
} else {
return mContext.getString(R.string.zen_sound_none_muted);
}
@@ -143,17 +143,17 @@
String getCallsSettingSummary(Policy policy) {
List<String> enabledCategories = getEnabledCategories(policy,
category -> PRIORITY_CATEGORY_CALLS == category
- || PRIORITY_CATEGORY_REPEAT_CALLERS == category);
+ || PRIORITY_CATEGORY_REPEAT_CALLERS == category, false);
int numCategories = enabledCategories.size();
if (numCategories == 0) {
return mContext.getString(R.string.zen_mode_no_exceptions);
} else if (numCategories == 1) {
return mContext.getString(R.string.zen_mode_calls_summary_one,
- enabledCategories.get(0).toLowerCase());
+ enabledCategories.get(0));
} else {
return mContext.getString(R.string.zen_mode_calls_summary_two,
- enabledCategories.get(0).toLowerCase(),
- enabledCategories.get(1).toLowerCase());
+ enabledCategories.get(0),
+ enabledCategories.get(1));
}
}
@@ -161,7 +161,7 @@
List<String> enabledCategories = getEnabledCategories(policy,
category -> PRIORITY_CATEGORY_EVENTS == category
|| PRIORITY_CATEGORY_REMINDERS == category
- || PRIORITY_CATEGORY_MESSAGES == category);
+ || PRIORITY_CATEGORY_MESSAGES == category, true);
int numCategories = enabledCategories.size();
if (numCategories == 0) {
return mContext.getString(R.string.zen_mode_no_exceptions);
@@ -169,19 +169,19 @@
return enabledCategories.get(0);
} else if (numCategories == 2) {
return mContext.getString(R.string.join_two_items, enabledCategories.get(0),
- enabledCategories.get(1).toLowerCase());
+ enabledCategories.get(1));
} else if (numCategories == 3){
final List<String> summaries = new ArrayList<>();
summaries.add(enabledCategories.get(0));
- summaries.add(enabledCategories.get(1).toLowerCase());
- summaries.add(enabledCategories.get(2).toLowerCase());
+ summaries.add(enabledCategories.get(1));
+ summaries.add(enabledCategories.get(2));
return ListFormatter.getInstance().format(summaries);
} else {
final List<String> summaries = new ArrayList<>();
summaries.add(enabledCategories.get(0));
- summaries.add(enabledCategories.get(1).toLowerCase());
- summaries.add(enabledCategories.get(2).toLowerCase());
+ summaries.add(enabledCategories.get(1));
+ summaries.add(enabledCategories.get(2));
summaries.add(mContext.getString(R.string.zen_mode_other_options));
return ListFormatter.getInstance().format(summaries);
@@ -251,48 +251,18 @@
}
private List<String> getEnabledCategories(Policy policy,
- Predicate<Integer> filteredCategories) {
+ Predicate<Integer> filteredCategories, boolean capitalizeFirstInList) {
List<String> enabledCategories = new ArrayList<>();
for (int category : ALL_PRIORITY_CATEGORIES) {
+ boolean isFirst = capitalizeFirstInList && enabledCategories.isEmpty();
if (filteredCategories.test(category) && isCategoryEnabled(policy, category)) {
- if (category == PRIORITY_CATEGORY_ALARMS) {
- enabledCategories.add(mContext.getString(R.string.zen_mode_alarms));
- } else if (category == PRIORITY_CATEGORY_MEDIA) {
- enabledCategories.add(mContext.getString(
- R.string.zen_mode_media));
- } else if (category == PRIORITY_CATEGORY_SYSTEM) {
- enabledCategories.add(mContext.getString(
- R.string.zen_mode_system));
- } else if (category == Policy.PRIORITY_CATEGORY_MESSAGES) {
- if (policy.priorityMessageSenders == Policy.PRIORITY_SENDERS_ANY) {
- enabledCategories.add(mContext.getString(
- R.string.zen_mode_all_messages));
- } else {
- enabledCategories.add(mContext.getString(
- R.string.zen_mode_selected_messages));
- }
- } else if (category == Policy.PRIORITY_CATEGORY_EVENTS) {
- enabledCategories.add(mContext.getString(R.string.zen_mode_events));
- } else if (category == Policy.PRIORITY_CATEGORY_REMINDERS) {
- enabledCategories.add(mContext.getString(R.string.zen_mode_reminders));
- } else if (category == Policy.PRIORITY_CATEGORY_CALLS) {
- if (policy.priorityCallSenders == Policy.PRIORITY_SENDERS_ANY) {
- enabledCategories.add(mContext.getString(
- R.string.zen_mode_all_callers));
- } else if (policy.priorityCallSenders == Policy.PRIORITY_SENDERS_CONTACTS){
- enabledCategories.add(mContext.getString(
- R.string.zen_mode_contacts_callers));
- } else {
- enabledCategories.add(mContext.getString(
- R.string.zen_mode_starred_callers));
- }
- } else if (category == Policy.PRIORITY_CATEGORY_REPEAT_CALLERS) {
- if (!enabledCategories.contains(mContext.getString(
- R.string.zen_mode_all_callers))) {
- enabledCategories.add(mContext.getString(
- R.string.zen_mode_repeat_callers));
- }
+ if (category == Policy.PRIORITY_CATEGORY_REPEAT_CALLERS
+ && isCategoryEnabled(policy, Policy.PRIORITY_CATEGORY_CALLS)
+ && policy.priorityCallSenders == Policy.PRIORITY_SENDERS_ANY) {
+ continue;
}
+
+ enabledCategories.add(getCategory(category, policy, isFirst));
}
}
return enabledCategories;
@@ -301,6 +271,70 @@
private boolean isCategoryEnabled(Policy policy, int categoryType) {
return (policy.priorityCategories & categoryType) != 0;
}
+
+ private String getCategory(int category, Policy policy, boolean isFirst) {
+ if (category == PRIORITY_CATEGORY_ALARMS) {
+ if (isFirst) {
+ return mContext.getString(R.string.zen_mode_alarms);
+ } else {
+ return mContext.getString(R.string.zen_mode_alarms_list);
+ }
+ } else if (category == PRIORITY_CATEGORY_MEDIA) {
+ if (isFirst) {
+ return mContext.getString(R.string.zen_mode_media);
+ } else {
+ return mContext.getString(R.string.zen_mode_media_list);
+ }
+ } else if (category == PRIORITY_CATEGORY_SYSTEM) {
+ if (isFirst) {
+ return mContext.getString(R.string.zen_mode_system);
+ } else {
+ return mContext.getString(R.string.zen_mode_system_list);
+ }
+ } else if (category == Policy.PRIORITY_CATEGORY_MESSAGES) {
+ if (policy.priorityMessageSenders == Policy.PRIORITY_SENDERS_ANY) {
+ if (isFirst) {
+ return mContext.getString(R.string.zen_mode_all_messages);
+ } else {
+ return mContext.getString(R.string.zen_mode_all_messages_list);
+ }
+ } else {
+ if (isFirst) {
+ return mContext.getString(R.string.zen_mode_selected_messages);
+ } else {
+ return mContext.getString(R.string.zen_mode_selected_messages_list);
+ }
+ }
+ } else if (category == Policy.PRIORITY_CATEGORY_EVENTS) {
+ if (isFirst) {
+ return mContext.getString(R.string.zen_mode_events);
+ } else {
+ return mContext.getString(R.string.zen_mode_events_list);
+ }
+ } else if (category == Policy.PRIORITY_CATEGORY_REMINDERS) {
+ if (isFirst) {
+ return mContext.getString(R.string.zen_mode_reminders);
+ } else {
+ return mContext.getString(R.string.zen_mode_reminders_list);
+ }
+ } else if (category == Policy.PRIORITY_CATEGORY_CALLS) {
+ if (policy.priorityCallSenders == Policy.PRIORITY_SENDERS_ANY) {
+ return mContext.getString(R.string.zen_mode_all_callers);
+ } else if (policy.priorityCallSenders == Policy.PRIORITY_SENDERS_CONTACTS){
+ return mContext.getString(R.string.zen_mode_contacts_callers);
+ } else {
+ return mContext.getString(R.string.zen_mode_starred_callers);
+ }
+ } else if (category == Policy.PRIORITY_CATEGORY_REPEAT_CALLERS) {
+ if (isFirst) {
+ return mContext.getString(R.string.zen_mode_repeat_callers);
+ } else {
+ return mContext.getString(R.string.zen_mode_repeat_callers_list);
+ }
+ }
+
+ return "";
+ }
}
/**
diff --git a/src/com/android/settings/overlay/FeatureFactoryImpl.java b/src/com/android/settings/overlay/FeatureFactoryImpl.java
index b64e540..48d563f 100644
--- a/src/com/android/settings/overlay/FeatureFactoryImpl.java
+++ b/src/com/android/settings/overlay/FeatureFactoryImpl.java
@@ -21,7 +21,6 @@
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.UserManager;
-import androidx.annotation.Keep;
import com.android.settings.accounts.AccountFeatureProvider;
import com.android.settings.accounts.AccountFeatureProviderImpl;
@@ -54,6 +53,8 @@
import com.android.settings.users.UserFeatureProviderImpl;
import com.android.settingslib.core.instrumentation.MetricsFeatureProvider;
+import androidx.annotation.Keep;
+
/**
* {@link FeatureFactory} implementation for AOSP Settings.
*/
@@ -93,7 +94,8 @@
@Override
public PowerUsageFeatureProvider getPowerUsageFeatureProvider(Context context) {
if (mPowerUsageFeatureProvider == null) {
- mPowerUsageFeatureProvider = new PowerUsageFeatureProviderImpl(context);
+ mPowerUsageFeatureProvider = new PowerUsageFeatureProviderImpl(
+ context.getApplicationContext());
}
return mPowerUsageFeatureProvider;
}
@@ -101,7 +103,8 @@
@Override
public DashboardFeatureProvider getDashboardFeatureProvider(Context context) {
if (mDashboardFeatureProvider == null) {
- mDashboardFeatureProvider = new DashboardFeatureProviderImpl(context);
+ mDashboardFeatureProvider = new DashboardFeatureProviderImpl(
+ context.getApplicationContext());
}
return mDashboardFeatureProvider;
}
@@ -117,10 +120,11 @@
@Override
public ApplicationFeatureProvider getApplicationFeatureProvider(Context context) {
if (mApplicationFeatureProvider == null) {
- mApplicationFeatureProvider = new ApplicationFeatureProviderImpl(context,
- context.getPackageManager(),
+ final Context appContext = context.getApplicationContext();
+ mApplicationFeatureProvider = new ApplicationFeatureProviderImpl(appContext,
+ appContext.getPackageManager(),
AppGlobals.getPackageManager(),
- (DevicePolicyManager) context
+ (DevicePolicyManager) appContext
.getSystemService(Context.DEVICE_POLICY_SERVICE));
}
return mApplicationFeatureProvider;
@@ -137,12 +141,14 @@
@Override
public EnterprisePrivacyFeatureProvider getEnterprisePrivacyFeatureProvider(Context context) {
if (mEnterprisePrivacyFeatureProvider == null) {
- mEnterprisePrivacyFeatureProvider = new EnterprisePrivacyFeatureProviderImpl(context,
- (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE),
- context.getPackageManager(),
- UserManager.get(context),
- (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE),
- context.getResources());
+ final Context appContext = context.getApplicationContext();
+ mEnterprisePrivacyFeatureProvider = new EnterprisePrivacyFeatureProviderImpl(appContext,
+ (DevicePolicyManager) appContext.getSystemService(
+ Context.DEVICE_POLICY_SERVICE),
+ appContext.getPackageManager(),
+ UserManager.get(appContext),
+ (ConnectivityManager) appContext.getSystemService(Context.CONNECTIVITY_SERVICE),
+ appContext.getResources());
}
return mEnterprisePrivacyFeatureProvider;
}
@@ -171,7 +177,8 @@
@Override
public SuggestionFeatureProvider getSuggestionFeatureProvider(Context context) {
if (mSuggestionFeatureProvider == null) {
- mSuggestionFeatureProvider = new SuggestionFeatureProviderImpl(context);
+ mSuggestionFeatureProvider = new SuggestionFeatureProviderImpl(
+ context.getApplicationContext());
}
return mSuggestionFeatureProvider;
}
@@ -179,7 +186,7 @@
@Override
public UserFeatureProvider getUserFeatureProvider(Context context) {
if (mUserFeatureProvider == null) {
- mUserFeatureProvider = new UserFeatureProviderImpl(context);
+ mUserFeatureProvider = new UserFeatureProviderImpl(context.getApplicationContext());
}
return mUserFeatureProvider;
}
diff --git a/src/com/android/settings/password/ChooseLockGeneric.java b/src/com/android/settings/password/ChooseLockGeneric.java
index a2d4a3a..39380ea 100644
--- a/src/com/android/settings/password/ChooseLockGeneric.java
+++ b/src/com/android/settings/password/ChooseLockGeneric.java
@@ -39,6 +39,7 @@
import android.os.UserManager;
import android.os.storage.StorageManager;
import androidx.annotation.StringRes;
+import androidx.annotation.VisibleForTesting;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;
import android.text.TextUtils;
@@ -124,7 +125,8 @@
*/
public static final String EXTRA_CHOOSE_LOCK_GENERIC_EXTRAS = "choose_lock_generic_extras";
- private static final int CONFIRM_EXISTING_REQUEST = 100;
+ @VisibleForTesting
+ static final int CONFIRM_EXISTING_REQUEST = 100;
private static final int ENABLE_ENCRYPTION_REQUEST = 101;
private static final int CHOOSE_LOCK_REQUEST = 102;
private static final int CHOOSE_LOCK_BEFORE_FINGERPRINT_REQUEST = 103;
@@ -329,7 +331,9 @@
mWaitingForConfirmation = false;
if (requestCode == CONFIRM_EXISTING_REQUEST && resultCode == Activity.RESULT_OK) {
mPasswordConfirmed = true;
- mUserPassword = data.getStringExtra(ChooseLockSettingsHelper.EXTRA_KEY_PASSWORD);
+ mUserPassword = data != null
+ ? data.getStringExtra(ChooseLockSettingsHelper.EXTRA_KEY_PASSWORD)
+ : null;
updatePreferencesOrFinish(false /* isRecreatingActivity */);
if (mForChangeCredRequiredForBoot) {
if (!TextUtils.isEmpty(mUserPassword)) {
@@ -394,7 +398,8 @@
}
}
- private void updatePreferencesOrFinish(boolean isRecreatingActivity) {
+ @VisibleForTesting
+ void updatePreferencesOrFinish(boolean isRecreatingActivity) {
Intent intent = getActivity().getIntent();
int quality = intent.getIntExtra(LockPatternUtils.PASSWORD_TYPE_KEY, -1);
if (quality == -1) {
diff --git a/src/com/android/settings/security/LockscreenDashboardFragment.java b/src/com/android/settings/security/LockscreenDashboardFragment.java
index 9669863..eaaf51d 100644
--- a/src/com/android/settings/security/LockscreenDashboardFragment.java
+++ b/src/com/android/settings/security/LockscreenDashboardFragment.java
@@ -29,7 +29,6 @@
import com.android.settings.gestures.PickupGesturePreferenceController;
import com.android.settings.notification.LockScreenNotificationPreferenceController;
import com.android.settings.search.BaseSearchIndexProvider;
-import com.android.settings.users.AddUserWhenLockedPreferenceController;
import com.android.settingslib.core.AbstractPreferenceController;
import com.android.settingslib.core.lifecycle.Lifecycle;
import com.android.settingslib.search.SearchIndexable;
@@ -109,8 +108,6 @@
KEY_LOCK_SCREEN_NOTIFICATON_WORK_PROFILE);
lifecycle.addObserver(notificationController);
controllers.add(notificationController);
- controllers.add(new AddUserWhenLockedPreferenceController(
- context, KEY_ADD_USER_FROM_LOCK_SCREEN, lifecycle));
mOwnerInfoPreferenceController =
new OwnerInfoPreferenceController(context, this, lifecycle);
controllers.add(mOwnerInfoPreferenceController);
@@ -147,8 +144,6 @@
Context context) {
final List<AbstractPreferenceController> controllers = new ArrayList<>();
controllers.add(new LockScreenNotificationPreferenceController(context));
- controllers.add(new AddUserWhenLockedPreferenceController(context,
- KEY_ADD_USER_FROM_LOCK_SCREEN, null /* lifecycle */));
controllers.add(new OwnerInfoPreferenceController(
context, null /* fragment */, null /* lifecycle */));
return controllers;
diff --git a/src/com/android/settings/sound/AudioSwitchPreferenceController.java b/src/com/android/settings/sound/AudioSwitchPreferenceController.java
index f35fd60..274819c 100644
--- a/src/com/android/settings/sound/AudioSwitchPreferenceController.java
+++ b/src/com/android/settings/sound/AudioSwitchPreferenceController.java
@@ -37,9 +37,6 @@
import android.media.MediaRouter.Callback;
import android.os.Handler;
import android.os.Looper;
-import androidx.preference.ListPreference;
-import androidx.preference.Preference;
-import androidx.preference.PreferenceScreen;
import android.text.TextUtils;
import android.util.FeatureFlagUtils;
import android.util.Log;
@@ -64,6 +61,10 @@
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
+import androidx.preference.ListPreference;
+import androidx.preference.Preference;
+import androidx.preference.PreferenceScreen;
+
/**
* Abstract class for audio switcher controller to notify subclass
* updating the current status of switcher entry. Subclasses must overwrite
@@ -74,7 +75,7 @@
implements Preference.OnPreferenceChangeListener, BluetoothCallback,
LifecycleObserver, OnStart, OnStop {
- private static final String TAG = "AudioSwitchPreferenceController";
+ private static final String TAG = "AudioSwitchPrefCtrl";
private static final int INVALID_INDEX = -1;
protected final List<BluetoothDevice> mConnectedDevices;
@@ -118,7 +119,6 @@
Log.e(TAG, "Bluetooth is not supported on this device");
return;
}
- mLocalBluetoothManager.setForegroundActivity(mContext);
mProfileManager = mLocalBluetoothManager.getProfileManager();
}
@@ -171,11 +171,21 @@
@Override
public void onStart() {
+ if (mLocalBluetoothManager == null) {
+ Log.e(TAG, "Bluetooth is not supported on this device");
+ return;
+ }
+ mLocalBluetoothManager.setForegroundActivity(mContext);
register();
}
@Override
public void onStop() {
+ if (mLocalBluetoothManager == null) {
+ Log.e(TAG, "Bluetooth is not supported on this device");
+ return;
+ }
+ mLocalBluetoothManager.setForegroundActivity(null);
unregister();
}
diff --git a/src/com/android/settings/users/AddUserWhenLockedPreferenceController.java b/src/com/android/settings/users/AddUserWhenLockedPreferenceController.java
index bebc2d7..2a61cac 100644
--- a/src/com/android/settings/users/AddUserWhenLockedPreferenceController.java
+++ b/src/com/android/settings/users/AddUserWhenLockedPreferenceController.java
@@ -16,72 +16,53 @@
package com.android.settings.users;
import android.content.Context;
-import android.provider.Settings.Global;
+import android.provider.Settings;
+
+import com.android.settings.core.TogglePreferenceController;
+import com.android.settingslib.RestrictedSwitchPreference;
+
import androidx.preference.Preference;
-import com.android.settings.core.PreferenceControllerMixin;
-import com.android.settingslib.RestrictedSwitchPreference;
-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.OnPause;
-import com.android.settingslib.core.lifecycle.events.OnResume;
+public class AddUserWhenLockedPreferenceController extends TogglePreferenceController {
-public class AddUserWhenLockedPreferenceController extends AbstractPreferenceController
- implements PreferenceControllerMixin, Preference.OnPreferenceChangeListener,
- LifecycleObserver, OnPause, OnResume {
-
- private final String mPrefKey;
private final UserCapabilities mUserCaps;
- private boolean mShouldUpdateUserList;
- public AddUserWhenLockedPreferenceController(Context context, String key, Lifecycle lifecycle) {
- super(context);
- mPrefKey = key;
+ public AddUserWhenLockedPreferenceController(Context context, String key) {
+ super(context, key);
mUserCaps = UserCapabilities.create(context);
- if (lifecycle != null) {
- lifecycle.addObserver(this);
- }
}
@Override
public void updateState(Preference preference) {
- RestrictedSwitchPreference restrictedSwitchPreference =
+ super.updateState(preference);
+ mUserCaps.updateAddUserCapabilities(mContext);
+ final RestrictedSwitchPreference restrictedSwitchPreference =
(RestrictedSwitchPreference) preference;
- int value = Global.getInt(mContext.getContentResolver(), Global.ADD_USERS_WHEN_LOCKED, 0);
- restrictedSwitchPreference.setChecked(value == 1);
restrictedSwitchPreference.setDisabledByAdmin(
mUserCaps.disallowAddUser() ? mUserCaps.getEnforcedAdmin() : null);
+ restrictedSwitchPreference.setVisible(mUserCaps.mUserSwitcherEnabled);
}
@Override
- public boolean onPreferenceChange(Preference preference, Object newValue) {
- Boolean value = (Boolean) newValue;
- Global.putInt(mContext.getContentResolver(),
- Global.ADD_USERS_WHEN_LOCKED, value != null && value ? 1 : 0);
- return true;
- }
-
- @Override
- public void onPause() {
- mShouldUpdateUserList = true;
- }
-
- @Override
- public void onResume() {
- if (mShouldUpdateUserList) {
- mUserCaps.updateAddUserCapabilities(mContext);
+ public int getAvailabilityStatus() {
+ if (!mUserCaps.isAdmin()) {
+ return DISABLED_FOR_USER;
+ } else if (mUserCaps.disallowAddUser() || mUserCaps.disallowAddUserSetByAdmin()) {
+ return DISABLED_FOR_USER;
+ } else {
+ return mUserCaps.mUserSwitcherEnabled ? AVAILABLE : CONDITIONALLY_UNAVAILABLE;
}
}
@Override
- public boolean isAvailable() {
- return mUserCaps.isAdmin() &&
- (!mUserCaps.disallowAddUser() || mUserCaps.disallowAddUserSetByAdmin());
+ public boolean isChecked() {
+ return Settings.Global.getInt(mContext.getContentResolver(),
+ Settings.Global.ADD_USERS_WHEN_LOCKED, 0) == 1;
}
@Override
- public String getPreferenceKey() {
- return mPrefKey;
+ public boolean setChecked(boolean isChecked) {
+ return Settings.Global.putInt(mContext.getContentResolver(),
+ Settings.Global.ADD_USERS_WHEN_LOCKED, isChecked ? 1 : 0);
}
}
diff --git a/src/com/android/settings/users/MultiUserFooterPreferenceController.java b/src/com/android/settings/users/MultiUserFooterPreferenceController.java
new file mode 100644
index 0000000..877df58
--- /dev/null
+++ b/src/com/android/settings/users/MultiUserFooterPreferenceController.java
@@ -0,0 +1,60 @@
+/*
+ * 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.users;
+
+import android.content.Context;
+
+import com.android.settings.R;
+import com.android.settings.core.BasePreferenceController;
+import com.android.settingslib.widget.FooterPreference;
+import com.android.settingslib.widget.FooterPreferenceMixin;
+
+import androidx.annotation.VisibleForTesting;
+import androidx.preference.Preference;
+
+public class MultiUserFooterPreferenceController extends BasePreferenceController {
+
+ @VisibleForTesting
+ final UserCapabilities mUserCaps;
+
+ private FooterPreferenceMixin mFooterMixin;
+
+ public MultiUserFooterPreferenceController(Context context) {
+ super(context, "dummy_key");
+ mUserCaps = UserCapabilities.create(context);
+ }
+
+ public MultiUserFooterPreferenceController setFooterMixin(FooterPreferenceMixin footerMixin) {
+ mFooterMixin = footerMixin;
+ return this;
+ }
+
+ @Override
+ public int getAvailabilityStatus() {
+ return (mUserCaps.mEnabled && !mUserCaps.mUserSwitcherEnabled)
+ ? AVAILABLE_UNSEARCHABLE
+ : DISABLED_FOR_USER;
+ }
+
+ @Override
+ public void updateState(Preference preference) {
+ mUserCaps.updateAddUserCapabilities(mContext);
+ final FooterPreference pref = mFooterMixin.createFooterPreference();
+ pref.setTitle(R.string.user_settings_footer_text);
+ pref.setVisible(isAvailable());
+ }
+}
diff --git a/src/com/android/settings/users/MultiUserSwitchBarController.java b/src/com/android/settings/users/MultiUserSwitchBarController.java
new file mode 100644
index 0000000..9588f71
--- /dev/null
+++ b/src/com/android/settings/users/MultiUserSwitchBarController.java
@@ -0,0 +1,73 @@
+/*
+ * 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.users;
+
+import android.content.Context;
+import android.provider.Settings;
+import android.util.Log;
+
+import com.android.settings.widget.SwitchWidgetController;
+import com.android.settingslib.core.lifecycle.LifecycleObserver;
+import com.android.settingslib.core.lifecycle.events.OnStart;
+import com.android.settingslib.core.lifecycle.events.OnStop;
+
+public class MultiUserSwitchBarController implements SwitchWidgetController.OnSwitchChangeListener,
+ LifecycleObserver, OnStart, OnStop {
+
+ interface OnMultiUserSwitchChangedListener {
+ void onMultiUserSwitchChanged(boolean newState);
+ }
+
+ private static final String TAG = "MultiUserSwitchBarCtrl";
+ private final Context mContext;
+ private final SwitchWidgetController mSwitchBar;
+ private final UserCapabilities mUserCapabilities;
+ private final OnMultiUserSwitchChangedListener mListener;
+
+ MultiUserSwitchBarController(Context context, SwitchWidgetController switchBar,
+ OnMultiUserSwitchChangedListener listener) {
+ mContext = context;
+ mSwitchBar = switchBar;
+ mListener = listener;
+ mUserCapabilities = UserCapabilities.create(context);
+ mSwitchBar.setChecked(mUserCapabilities.mUserSwitcherEnabled);
+ mSwitchBar.setEnabled(!mUserCapabilities.mDisallowSwitchUser
+ && !mUserCapabilities.mIsGuest && mUserCapabilities.isAdmin());
+ mSwitchBar.setListener(this);
+ }
+
+ @Override
+ public void onStart() {
+ mSwitchBar.startListening();
+ }
+
+ @Override
+ public void onStop() {
+ mSwitchBar.stopListening();
+ }
+
+ @Override
+ public boolean onSwitchToggled(boolean isChecked) {
+ Log.d(TAG, "Toggling multi-user feature enabled state to: " + isChecked);
+ final boolean success = Settings.Global.putInt(mContext.getContentResolver(),
+ Settings.Global.USER_SWITCHER_ENABLED, isChecked ? 1 : 0);
+ if (success && mListener != null) {
+ mListener.onMultiUserSwitchChanged(isChecked);
+ }
+ return success;
+ }
+}
diff --git a/src/com/android/settings/users/UserCapabilities.java b/src/com/android/settings/users/UserCapabilities.java
index f1bfae9..b9a2228 100644
--- a/src/com/android/settings/users/UserCapabilities.java
+++ b/src/com/android/settings/users/UserCapabilities.java
@@ -22,6 +22,7 @@
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
+
import com.android.settings.Utils;
import com.android.settingslib.RestrictedLockUtils;
@@ -31,13 +32,15 @@
boolean mCanAddRestrictedProfile = true;
boolean mIsAdmin;
boolean mIsGuest;
+ boolean mUserSwitcherEnabled;
boolean mCanAddGuest;
boolean mDisallowAddUser;
boolean mDisallowAddUserSetByAdmin;
boolean mDisallowSwitchUser;
RestrictedLockUtils.EnforcedAdmin mEnforcedAdmin;
- private UserCapabilities() {}
+ private UserCapabilities() {
+ }
public static UserCapabilities create(Context context) {
UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
@@ -62,14 +65,15 @@
}
public void updateAddUserCapabilities(Context context) {
+ final UserManager userManager =
+ (UserManager) context.getSystemService(Context.USER_SERVICE);
mEnforcedAdmin = RestrictedLockUtils.checkIfRestrictionEnforced(context,
UserManager.DISALLOW_ADD_USER, UserHandle.myUserId());
final boolean hasBaseUserRestriction = RestrictedLockUtils.hasBaseUserRestriction(
context, UserManager.DISALLOW_ADD_USER, UserHandle.myUserId());
- mDisallowAddUserSetByAdmin =
- mEnforcedAdmin != null && !hasBaseUserRestriction;
- mDisallowAddUser =
- (mEnforcedAdmin != null || hasBaseUserRestriction);
+ mDisallowAddUserSetByAdmin = mEnforcedAdmin != null && !hasBaseUserRestriction;
+ mDisallowAddUser = (mEnforcedAdmin != null || hasBaseUserRestriction);
+ mUserSwitcherEnabled = userManager.isUserSwitcherEnabled();
mCanAddUser = true;
if (!mIsAdmin || UserManager.getMaxSupportedUsers() < 2
|| !UserManager.supportsMultipleUsers()
@@ -81,7 +85,6 @@
context.getContentResolver(), Settings.Global.ADD_USERS_WHEN_LOCKED, 0) == 1;
mCanAddGuest = !mIsGuest && !mDisallowAddUser && canAddUsersWhenLocked;
- UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
mDisallowSwitchUser = userManager.hasUserRestriction(UserManager.DISALLOW_USER_SWITCH);
}
diff --git a/src/com/android/settings/users/UserSettings.java b/src/com/android/settings/users/UserSettings.java
index a33561b..c57d959 100644
--- a/src/com/android/settings/users/UserSettings.java
+++ b/src/com/android/settings/users/UserSettings.java
@@ -48,13 +48,13 @@
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
-import android.view.View.OnClickListener;
import android.widget.SimpleAdapter;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.util.UserIcons;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.R;
+import com.android.settings.SettingsActivity;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.Utils;
import com.android.settings.core.SubSettingLauncher;
@@ -62,6 +62,8 @@
import com.android.settings.password.ChooseLockGeneric;
import com.android.settings.search.BaseSearchIndexProvider;
import com.android.settings.search.Indexable;
+import com.android.settings.widget.SwitchBar;
+import com.android.settings.widget.SwitchBarController;
import com.android.settingslib.RestrictedLockUtils;
import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
import com.android.settingslib.RestrictedPreference;
@@ -78,7 +80,6 @@
import androidx.annotation.VisibleForTesting;
import androidx.annotation.WorkerThread;
import androidx.preference.Preference;
-import androidx.preference.Preference.OnPreferenceClickListener;
import androidx.preference.PreferenceGroup;
import androidx.preference.PreferenceScreen;
@@ -92,7 +93,9 @@
*/
@SearchIndexable
public class UserSettings extends SettingsPreferenceFragment
- implements OnPreferenceClickListener, OnClickListener, DialogInterface.OnDismissListener,
+ implements Preference.OnPreferenceClickListener, View.OnClickListener,
+ MultiUserSwitchBarController.OnMultiUserSwitchChangedListener,
+ DialogInterface.OnDismissListener,
EditUserInfoController.OnContentChangedCallback, Indexable {
private static final String TAG = "UserSettings";
@@ -155,8 +158,10 @@
private SparseArray<Bitmap> mUserIcons = new SparseArray<>();
private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<>();
+ private MultiUserSwitchBarController mSwitchBarController;
private EditUserInfoController mEditUserInfoController = new EditUserInfoController();
private AddUserWhenLockedPreferenceController mAddUserWhenLockedPreferenceController;
+ private MultiUserFooterPreferenceController mMultiUserFooterPreferenceController;
// A place to cache the generated default avatar
private Drawable mDefaultIconDrawable;
@@ -199,19 +204,36 @@
}
@Override
+ public void onActivityCreated(Bundle savedInstanceState) {
+ super.onActivityCreated(savedInstanceState);
+ // Assume we are in a SettingsActivity. This is only safe because we currently use
+ // SettingsActivity as base for all preference fragments.
+ final SettingsActivity activity = (SettingsActivity) getActivity();
+ final SwitchBar switchBar = activity.getSwitchBar();
+ mSwitchBarController = new MultiUserSwitchBarController(activity,
+ new SwitchBarController(switchBar), this /* listener */);
+ getLifecycle().addObserver(mSwitchBarController);
+ switchBar.show();
+ }
+
+ @Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
addPreferencesFromResource(R.xml.user_settings);
final Activity activity = getActivity();
- if (!Utils.isDeviceProvisioned(getActivity())) {
+ if (!Utils.isDeviceProvisioned(activity)) {
activity.finish();
return;
}
mAddUserWhenLockedPreferenceController = new AddUserWhenLockedPreferenceController(
- activity, KEY_ADD_USER_WHEN_LOCKED, getLifecycle());
+ activity, KEY_ADD_USER_WHEN_LOCKED);
+ mMultiUserFooterPreferenceController = new MultiUserFooterPreferenceController(activity)
+ .setFooterMixin(mFooterPreferenceMixin);
+
final PreferenceScreen screen = getPreferenceScreen();
mAddUserWhenLockedPreferenceController.displayPreference(screen);
+ mMultiUserFooterPreferenceController.displayPreference(screen);
screen.findPreference(mAddUserWhenLockedPreferenceController.getPreferenceKey())
.setOnPreferenceChangeListener(mAddUserWhenLockedPreferenceController);
@@ -246,7 +268,7 @@
mAddUser = (RestrictedPreference) findPreference(KEY_ADD_USER);
mAddUser.useAdminDisabledSummary(false);
// Determine if add user/profile button should be visible
- if (mUserCaps.mCanAddUser && Utils.isDeviceProvisioned(getActivity())) {
+ if (mUserCaps.mCanAddUser && Utils.isDeviceProvisioned(activity)) {
mAddUser.setVisible(true);
mAddUser.setOnPreferenceClickListener(this);
// change label to only mention user, if restricted profiles are not supported
@@ -260,8 +282,7 @@
activity.registerReceiverAsUser(
mUserChangeReceiver, UserHandle.ALL, USER_REMOVED_INTENT_FILTER, null, mHandler);
- loadProfile();
- updateUserList();
+ updateUI();
mShouldUpdateUserList = false;
}
@@ -280,9 +301,7 @@
}
if (mShouldUpdateUserList) {
- mUserCaps.updateAddUserCapabilities(getActivity());
- loadProfile();
- updateUserList();
+ updateUI();
}
}
@@ -343,6 +362,17 @@
}
}
+ @Override
+ public void onMultiUserSwitchChanged(boolean newState) {
+ updateUI();
+ }
+
+ private void updateUI() {
+ mUserCaps.updateAddUserCapabilities(getActivity());
+ loadProfile();
+ updateUserList();
+ }
+
/**
* Loads profile information for the current user.
*/
@@ -909,8 +939,6 @@
loadIconsAsync(missingIcons);
}
- // Remove everything from mUserListCategory and add new users.
- mUserListCategory.removeAll();
// If profiles are supported, mUserListCategory will have a special title
if (mUserCaps.mCanAddRestrictedProfile) {
mUserListCategory.setTitle(R.string.user_list_title);
@@ -918,6 +946,20 @@
mUserListCategory.setTitle(null);
}
+ // Remove everything from mUserListCategory and add new users.
+ mUserListCategory.removeAll();
+
+ // If multi-user is disabled, just show footer and return.
+ final Preference addUserOnLockScreen = getPreferenceScreen().findPreference(
+ mAddUserWhenLockedPreferenceController.getPreferenceKey());
+ mAddUserWhenLockedPreferenceController.updateState(addUserOnLockScreen);
+ mMultiUserFooterPreferenceController.updateState(null /* preference */);
+ mAddUser.setVisible(mUserCaps.mUserSwitcherEnabled);
+ mUserListCategory.setVisible(mUserCaps.mUserSwitcherEnabled);
+ if (!mUserCaps.mUserSwitcherEnabled) {
+ return;
+ }
+
for (UserPreference userPreference : userPreferences) {
userPreference.setOrder(Preference.DEFAULT_ORDER);
mUserListCategory.addPreference(userPreference);
@@ -925,7 +967,7 @@
// Append Add user to the end of the list
if ((mUserCaps.mCanAddUser || mUserCaps.mDisallowAddUserSetByAdmin) &&
- Utils.isDeviceProvisioned(getActivity())) {
+ Utils.isDeviceProvisioned(context)) {
boolean moreUsers = mUserManager.canAddMoreUsers();
mAddUser.setEnabled(moreUsers && !mAddingUser);
if (!moreUsers) {
@@ -938,7 +980,6 @@
mUserCaps.mDisallowAddUser ? mUserCaps.mEnforcedAdmin : null);
}
}
-
}
private int getMaxRealUsers() {
@@ -1190,8 +1231,7 @@
@Override
public List<String> getNonIndexableKeysFromXml(Context context, int xmlResId) {
final List<String> niks = super.getNonIndexableKeysFromXml(context, xmlResId);
- new AddUserWhenLockedPreferenceController(
- context, KEY_ADD_USER_WHEN_LOCKED, null /* lifecycle */)
+ new AddUserWhenLockedPreferenceController(context, KEY_ADD_USER_WHEN_LOCKED)
.updateNonIndexableKeys(niks);
new AutoSyncDataPreferenceController(context, null /* parent */)
.updateNonIndexableKeys(niks);
diff --git a/src/com/android/settings/vpn2/VpnUtils.java b/src/com/android/settings/vpn2/VpnUtils.java
index 4528180..38c56c5 100644
--- a/src/com/android/settings/vpn2/VpnUtils.java
+++ b/src/com/android/settings/vpn2/VpnUtils.java
@@ -38,7 +38,8 @@
private static final String TAG = "VpnUtils";
public static String getLockdownVpn() {
- final byte[] value = KeyStore.getInstance().get(Credentials.LOCKDOWN_VPN);
+ final byte[] value = KeyStore.getInstance().get(
+ Credentials.LOCKDOWN_VPN, true /* suppressKeyNotFoundWarning */);
return value == null ? null : new String(value);
}
diff --git a/src/com/android/settings/graph/BottomLabelLayout.java b/src/com/android/settings/widget/BottomLabelLayout.java
similarity index 98%
rename from src/com/android/settings/graph/BottomLabelLayout.java
rename to src/com/android/settings/widget/BottomLabelLayout.java
index 20d97e5..dca528f 100644
--- a/src/com/android/settings/graph/BottomLabelLayout.java
+++ b/src/com/android/settings/widget/BottomLabelLayout.java
@@ -1,5 +1,6 @@
/*
* 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
@@ -11,11 +12,9 @@
* 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.graph;
+package com.android.settings.widget;
import android.annotation.Nullable;
import android.content.Context;
diff --git a/src/com/android/settings/graph/UsageGraph.java b/src/com/android/settings/widget/UsageGraph.java
similarity index 93%
rename from src/com/android/settings/graph/UsageGraph.java
rename to src/com/android/settings/widget/UsageGraph.java
index b9d517d..7238e5d 100644
--- a/src/com/android/settings/graph/UsageGraph.java
+++ b/src/com/android/settings/widget/UsageGraph.java
@@ -1,18 +1,20 @@
/*
* 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
+ * 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.
+ * 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.graph;
+package com.android.settings.widget;
import android.annotation.Nullable;
import android.content.Context;
@@ -253,9 +255,15 @@
return;
}
+ canvas.save();
+ if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
+ // Flip the canvas along the y-axis of the center of itself before drawing paths.
+ canvas.scale(-1, 1, canvas.getWidth() * 0.5f, 0);
+ }
drawLinePath(canvas, mLocalProjectedPaths, mDottedPaint);
drawFilledPath(canvas, mLocalPaths, mFillPaint);
drawLinePath(canvas, mLocalPaths, mLinePaint);
+ canvas.restore();
BatteryUtils.logRuntime(LOG_TAG, "onDraw", startTime);
}
diff --git a/src/com/android/settings/graph/UsageView.java b/src/com/android/settings/widget/UsageView.java
similarity index 92%
rename from src/com/android/settings/graph/UsageView.java
rename to src/com/android/settings/widget/UsageView.java
index bcf0441..54e75b3 100644
--- a/src/com/android/settings/graph/UsageView.java
+++ b/src/com/android/settings/widget/UsageView.java
@@ -1,18 +1,20 @@
/*
* 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
+ * 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.
+ * 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.graph;
+package com.android.settings.widget;
import android.content.Context;
import android.content.res.TypedArray;
@@ -24,6 +26,7 @@
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
+
import com.android.settingslib.R;
public class UsageView extends FrameLayout {
diff --git a/src/com/android/settings/wifi/WifiUtils.java b/src/com/android/settings/wifi/WifiUtils.java
index 1e8308b..ff8570e 100644
--- a/src/com/android/settings/wifi/WifiUtils.java
+++ b/src/com/android/settings/wifi/WifiUtils.java
@@ -26,6 +26,8 @@
import android.provider.Settings;
import android.text.TextUtils;
+import java.nio.charset.StandardCharsets;
+
public class WifiUtils {
private static final int SSID_ASCII_MIN_LENGTH = 1;
@@ -38,7 +40,7 @@
if (TextUtils.isEmpty(ssid)) {
return false;
}
- return ssid.length() > SSID_ASCII_MAX_LENGTH;
+ return ssid.getBytes(StandardCharsets.UTF_8).length > SSID_ASCII_MAX_LENGTH;
}
public static boolean isSSIDTooShort(String ssid) {
@@ -59,8 +61,9 @@
/**
* This method is a stripped and negated version of WifiConfigStore.canModifyNetwork.
+ *
* @param context Context of caller
- * @param config The WiFi config.
+ * @param config The WiFi config.
* @return true if Settings cannot modify the config due to lockDown.
*/
public static boolean isNetworkLockedDown(Context context, WifiConfiguration config) {
diff --git a/tests/robotests/assets/grandfather_invalid_base_preference_controller_constructor b/tests/robotests/assets/grandfather_invalid_base_preference_controller_constructor
index c2b3da9..a2be681 100644
--- a/tests/robotests/assets/grandfather_invalid_base_preference_controller_constructor
+++ b/tests/robotests/assets/grandfather_invalid_base_preference_controller_constructor
@@ -1,4 +1,4 @@
-com.android.settings.applications.appinfo.AppActionButtonPreferenceController
+com.android.settings.applications.appinfo.AppButtonsPreferenceController
com.android.settings.applications.appinfo.AppBatteryPreferenceController
com.android.settings.applications.appinfo.AppHeaderViewPreferenceController
com.android.settings.applications.appinfo.AppMemoryPreferenceController
diff --git a/tests/robotests/src/com/android/settings/applications/AppStateNotificationBridgeTest.java b/tests/robotests/src/com/android/settings/applications/AppStateNotificationBridgeTest.java
index 9437a00..8e3bb42 100644
--- a/tests/robotests/src/com/android/settings/applications/AppStateNotificationBridgeTest.java
+++ b/tests/robotests/src/com/android/settings/applications/AppStateNotificationBridgeTest.java
@@ -36,17 +36,21 @@
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import android.app.usage.IUsageStatsManager;
import android.app.usage.UsageEvents;
import android.app.usage.UsageEvents.Event;
-import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Looper;
import android.os.Parcel;
+import android.os.RemoteException;
+import android.os.UserHandle;
+import android.os.UserManager;
import android.view.ViewGroup;
import android.widget.Switch;
@@ -79,7 +83,9 @@
@Mock
private ApplicationsState mState;
@Mock
- private UsageStatsManager mUsageStats;
+ private IUsageStatsManager mUsageStats;
+ @Mock
+ private UserManager mUserManager;
@Mock
private NotificationBackend mBackend;
private Context mContext;
@@ -92,10 +98,12 @@
when(mState.getBackgroundLooper()).thenReturn(mock(Looper.class));
when(mBackend.getNotificationsBanned(anyString(), anyInt())).thenReturn(true);
when(mBackend.isSystemApp(any(), any())).thenReturn(true);
+ // most tests assume no work profile
+ when(mUserManager.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[]{});
mContext = RuntimeEnvironment.application.getApplicationContext();
mBridge = new AppStateNotificationBridge(mContext, mState,
- mock(AppStateBaseBridge.Callback.class), mUsageStats, mBackend);
+ mock(AppStateBaseBridge.Callback.class), mUsageStats, mUserManager, mBackend);
}
private AppEntry getMockAppEntry(String pkg) {
@@ -115,14 +123,15 @@
}
@Test
- public void testGetAggregatedUsageEvents_noEvents() {
- when(mUsageStats.queryEvents(anyLong(), anyLong())).thenReturn(mock(UsageEvents.class));
+ public void testGetAggregatedUsageEvents_noEvents() throws Exception {
+ when(mUsageStats.queryEventsForUser(anyLong(), anyLong(), anyInt(), anyString()))
+ .thenReturn(mock(UsageEvents.class));
assertThat(mBridge.getAggregatedUsageEvents()).isEmpty();
}
@Test
- public void testGetAggregatedUsageEvents_onlyNotificationEvents() {
+ public void testGetAggregatedUsageEvents_onlyNotificationEvents() throws Exception {
List<Event> events = new ArrayList<>();
Event good = new Event();
good.mEventType = Event.NOTIFICATION_INTERRUPTION;
@@ -136,14 +145,15 @@
events.add(bad);
UsageEvents usageEvents = getUsageEvents(events);
- when(mUsageStats.queryEvents(anyLong(), anyLong())).thenReturn(usageEvents);
+ when(mUsageStats.queryEventsForUser(anyLong(), anyLong(), anyInt(), anyString()))
+ .thenReturn(usageEvents);
Map<String, NotificationsSentState> map = mBridge.getAggregatedUsageEvents();
- assertThat(map.get(PKG1).sentCount).isEqualTo(1);
+ assertThat(map.get(mBridge.getKey(0, PKG1)).sentCount).isEqualTo(1);
}
@Test
- public void testGetAggregatedUsageEvents_multipleEventsAgg() {
+ public void testGetAggregatedUsageEvents_multipleEventsAgg() throws Exception {
List<Event> events = new ArrayList<>();
Event good = new Event();
good.mEventType = Event.NOTIFICATION_INTERRUPTION;
@@ -157,15 +167,16 @@
events.add(good1);
UsageEvents usageEvents = getUsageEvents(events);
- when(mUsageStats.queryEvents(anyLong(), anyLong())).thenReturn(usageEvents);
+ when(mUsageStats.queryEventsForUser(anyLong(), anyLong(), anyInt(), anyString()))
+ .thenReturn(usageEvents);
Map<String, NotificationsSentState> map = mBridge.getAggregatedUsageEvents();
- assertThat(map.get(PKG1).sentCount).isEqualTo(2);
- assertThat(map.get(PKG1).lastSent).isEqualTo(6);
+ assertThat(map.get(mBridge.getKey(0, PKG1)).sentCount).isEqualTo(2);
+ assertThat(map.get(mBridge.getKey(0, PKG1)).lastSent).isEqualTo(6);
}
@Test
- public void testGetAggregatedUsageEvents_multiplePkgs() {
+ public void testGetAggregatedUsageEvents_multiplePkgs() throws Exception {
List<Event> events = new ArrayList<>();
Event good = new Event();
good.mEventType = Event.NOTIFICATION_INTERRUPTION;
@@ -179,19 +190,21 @@
events.add(good1);
UsageEvents usageEvents = getUsageEvents(events);
- when(mUsageStats.queryEvents(anyLong(), anyLong())).thenReturn(usageEvents);
+ when(mUsageStats.queryEventsForUser(anyLong(), anyLong(), anyInt(), anyString()))
+ .thenReturn(usageEvents);
Map<String, NotificationsSentState> map
= mBridge.getAggregatedUsageEvents();
- assertThat(map.get(PKG1).sentCount).isEqualTo(1);
- assertThat(map.get(PKG2).sentCount).isEqualTo(1);
- assertThat(map.get(PKG1).lastSent).isEqualTo(6);
- assertThat(map.get(PKG2).lastSent).isEqualTo(1);
+ assertThat(map.get(mBridge.getKey(0, PKG1)).sentCount).isEqualTo(1);
+ assertThat(map.get(mBridge.getKey(0, PKG2)).sentCount).isEqualTo(1);
+ assertThat(map.get(mBridge.getKey(0, PKG1)).lastSent).isEqualTo(6);
+ assertThat(map.get(mBridge.getKey(0, PKG2)).lastSent).isEqualTo(1);
}
@Test
- public void testLoadAllExtraInfo_noEvents() {
- when(mUsageStats.queryEvents(anyLong(), anyLong())).thenReturn(mock(UsageEvents.class));
+ public void testLoadAllExtraInfo_noEvents() throws RemoteException {
+ when(mUsageStats.queryEventsForUser(anyLong(), anyLong(), anyInt(), anyString()))
+ .thenReturn(mock(UsageEvents.class));
ArrayList<AppEntry> apps = new ArrayList<>();
apps.add(getMockAppEntry(PKG1));
when(mSession.getAllApps()).thenReturn(apps);
@@ -201,7 +214,7 @@
}
@Test
- public void testLoadAllExtraInfo_multipleEventsAgg() {
+ public void testLoadAllExtraInfo_multipleEventsAgg() throws RemoteException {
List<Event> events = new ArrayList<>();
for (int i = 0; i < 7; i++) {
Event good = new Event();
@@ -212,7 +225,8 @@
}
UsageEvents usageEvents = getUsageEvents(events);
- when(mUsageStats.queryEvents(anyLong(), anyLong())).thenReturn(usageEvents);
+ when(mUsageStats.queryEventsForUser(anyLong(), anyLong(), anyInt(), anyString()))
+ .thenReturn(usageEvents);
ArrayList<AppEntry> apps = new ArrayList<>();
apps.add(getMockAppEntry(PKG1));
@@ -229,7 +243,7 @@
}
@Test
- public void testLoadAllExtraInfo_multiplePkgs() {
+ public void testLoadAllExtraInfo_multiplePkgs() throws RemoteException {
List<Event> events = new ArrayList<>();
for (int i = 0; i < 8; i++) {
Event good = new Event();
@@ -245,7 +259,8 @@
events.add(good1);
UsageEvents usageEvents = getUsageEvents(events);
- when(mUsageStats.queryEvents(anyLong(), anyLong())).thenReturn(usageEvents);
+ when(mUsageStats.queryEventsForUser(anyLong(), anyLong(), anyInt(), anyString()))
+ .thenReturn(usageEvents);
ArrayList<AppEntry> apps = new ArrayList<>();
apps.add(getMockAppEntry(PKG1));
@@ -265,8 +280,66 @@
}
@Test
- public void testUpdateExtraInfo_noEvents() {
- when(mUsageStats.queryEvents(anyLong(), anyLong())).thenReturn(mock(UsageEvents.class));
+ public void testLoadAllExtraInfo_multipleUsers() throws RemoteException {
+ // has work profile
+ when(mUserManager.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[]{1});
+ mBridge = new AppStateNotificationBridge(mContext, mState,
+ mock(AppStateBaseBridge.Callback.class), mUsageStats, mUserManager, mBackend);
+
+ List<Event> eventsProfileOwner = new ArrayList<>();
+ for (int i = 0; i < 8; i++) {
+ Event good = new Event();
+ good.mEventType = Event.NOTIFICATION_INTERRUPTION;
+ good.mPackage = PKG1;
+ good.mTimeStamp = i;
+ eventsProfileOwner.add(good);
+ }
+
+ List<Event> eventsProfile = new ArrayList<>();
+ for (int i = 0; i < 4; i++) {
+ Event good = new Event();
+ good.mEventType = Event.NOTIFICATION_INTERRUPTION;
+ good.mPackage = PKG1;
+ good.mTimeStamp = i;
+ eventsProfile.add(good);
+ }
+
+ UsageEvents usageEventsOwner = getUsageEvents(eventsProfileOwner);
+ when(mUsageStats.queryEventsForUser(anyLong(), anyLong(), eq(0), anyString()))
+ .thenReturn(usageEventsOwner);
+
+ UsageEvents usageEventsProfile = getUsageEvents(eventsProfile);
+ when(mUsageStats.queryEventsForUser(anyLong(), anyLong(), eq(1), anyString()))
+ .thenReturn(usageEventsProfile);
+
+ ArrayList<AppEntry> apps = new ArrayList<>();
+ AppEntry owner = getMockAppEntry(PKG1);
+ owner.info.uid = 1;
+ apps.add(owner);
+
+ AppEntry profile = getMockAppEntry(PKG1);
+ profile.info.uid = UserHandle.PER_USER_RANGE + 1;
+ apps.add(profile);
+ when(mSession.getAllApps()).thenReturn(apps);
+
+ mBridge.loadAllExtraInfo();
+
+ assertThat(((NotificationsSentState) apps.get(0).extraInfo).sentCount).isEqualTo(8);
+ assertThat(((NotificationsSentState) apps.get(0).extraInfo).lastSent).isEqualTo(7);
+ assertThat(((NotificationsSentState) apps.get(0).extraInfo).avgSentWeekly).isEqualTo(0);
+ assertThat(((NotificationsSentState) apps.get(0).extraInfo).avgSentDaily).isEqualTo(1);
+
+ assertThat(((NotificationsSentState) apps.get(1).extraInfo).sentCount).isEqualTo(4);
+ assertThat(((NotificationsSentState) apps.get(1).extraInfo).lastSent).isEqualTo(3);
+ assertThat(((NotificationsSentState) apps.get(1).extraInfo).avgSentWeekly).isEqualTo(4);
+ assertThat(((NotificationsSentState) apps.get(1).extraInfo).avgSentDaily).isEqualTo(1);
+ }
+
+ @Test
+ public void testUpdateExtraInfo_noEvents() throws RemoteException {
+ when(mUsageStats.queryEventsForPackageForUser(
+ anyLong(), anyLong(), anyInt(), anyString(), anyString()))
+ .thenReturn(mock(UsageEvents.class));
AppEntry entry = getMockAppEntry(PKG1);
mBridge.updateExtraInfo(entry, "", 0);
@@ -274,7 +347,7 @@
}
@Test
- public void testUpdateExtraInfo_multipleEventsAgg() {
+ public void testUpdateExtraInfo_multipleEventsAgg() throws RemoteException {
List<Event> events = new ArrayList<>();
for (int i = 0; i < 13; i++) {
Event good = new Event();
@@ -285,7 +358,8 @@
}
UsageEvents usageEvents = getUsageEvents(events);
- when(mUsageStats.queryEvents(anyLong(), anyLong())).thenReturn(usageEvents);
+ when(mUsageStats.queryEventsForPackageForUser(
+ anyLong(), anyLong(), anyInt(), anyString(), anyString())).thenReturn(usageEvents);
AppEntry entry = getMockAppEntry(PKG1);
mBridge.updateExtraInfo(entry, "", 0);
diff --git a/tests/robotests/src/com/android/settings/applications/SpecialAccessSettingsTest.java b/tests/robotests/src/com/android/settings/applications/SpecialAccessSettingsTest.java
deleted file mode 100644
index fd71af7..0000000
--- a/tests/robotests/src/com/android/settings/applications/SpecialAccessSettingsTest.java
+++ /dev/null
@@ -1,79 +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.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.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)
-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/AppActionButtonPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/applications/appinfo/AppActionButtonPreferenceControllerTest.java
deleted file mode 100644
index cf423f7..0000000
--- a/tests/robotests/src/com/android/settings/applications/appinfo/AppActionButtonPreferenceControllerTest.java
+++ /dev/null
@@ -1,360 +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.applications.appinfo;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.argThat;
-import static org.mockito.ArgumentMatchers.nullable;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.app.admin.DevicePolicyManager;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.UserInfo;
-import android.content.res.Resources;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.UserHandle;
-import android.os.UserManager;
-import androidx.preference.PreferenceScreen;
-
-import com.android.settings.R;
-import com.android.settings.testutils.FakeFeatureFactory;
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settings.widget.ActionButtonPreference;
-import com.android.settings.widget.ActionButtonPreferenceTest;
-import com.android.settingslib.Utils;
-import com.android.settingslib.applications.AppUtils;
-import com.android.settingslib.applications.ApplicationsState;
-import com.android.settingslib.applications.instantapps.InstantAppDataProvider;
-
-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.annotation.Implementation;
-import org.robolectric.annotation.Implements;
-import org.robolectric.util.ReflectionHelpers;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-
-@RunWith(SettingsRobolectricTestRunner.class)
-public class AppActionButtonPreferenceControllerTest {
-
- @Mock
- private UserManager mUserManager;
- @Mock
- private DevicePolicyManager mDevicePolicyManager;
- @Mock
- private AppInfoDashboardFragment mFragment;
- @Mock
- private ApplicationInfo mAppInfo;
- @Mock
- private PackageManager mPackageManager;
-
- private Context mContext;
- private AppActionButtonPreferenceController mController;
- private FakeFeatureFactory mFeatureFactory;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- mFeatureFactory = FakeFeatureFactory.setupForTest();
- mContext = spy(RuntimeEnvironment.application);
- mController = spy(new AppActionButtonPreferenceController(mContext, mFragment, "Package1"));
- mController.mActionButtons = ActionButtonPreferenceTest.createMock();
- ReflectionHelpers.setField(mController, "mUserManager", mUserManager);
- ReflectionHelpers.setField(mController, "mDpm", mDevicePolicyManager);
- ReflectionHelpers.setField(mController, "mApplicationFeatureProvider",
- mFeatureFactory.applicationFeatureProvider);
- ReflectionHelpers.setField(mController, "mPm", mPackageManager);
- when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
- when(mContext.getPackageManager()).thenReturn(mPackageManager);
- final PackageInfo packageInfo = mock(PackageInfo.class);
- packageInfo.applicationInfo = mAppInfo;
- when(mFragment.getPackageInfo()).thenReturn(packageInfo);
- }
-
- @Test
- public void getAvailabilityStatus_notInstantApp_shouldReturnAvailable() {
- ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
- (InstantAppDataProvider) (i -> false));
-
- assertThat(mController.getAvailabilityStatus()).isEqualTo(mController.AVAILABLE);
- }
-
- @Test
- public void getAvailabilityStatus_isInstantApp_shouldReturnDisabled() {
- ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
- (InstantAppDataProvider) (i -> true));
-
- assertThat(mController.getAvailabilityStatus()).isEqualTo(mController.DISABLED_FOR_USER);
- }
-
- @Test
- public void displayPreference_shouldInitializeForceStopButton() {
- final PreferenceScreen screen = mock(PreferenceScreen.class);
- final ActionButtonPreference preference = spy(new ActionButtonPreference(mContext));
- when(screen.findPreference(mController.getPreferenceKey())).thenReturn(preference);
-
- mController.displayPreference(screen);
-
- verify(preference).setButton2Positive(false);
- verify(preference).setButton2Text(R.string.force_stop);
- verify(preference).setButton2Enabled(false);
- }
-
- @Test
- public void refreshUi_shouldRefreshButton() {
- final PackageInfo packageInfo = mock(PackageInfo.class);
- final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
- final ApplicationInfo info = new ApplicationInfo();
- appEntry.info = info;
- doNothing().when(mController).checkForceStop(appEntry, packageInfo);
- doNothing().when(mController).initUninstallButtons(appEntry, packageInfo);
- when(mFragment.getAppEntry()).thenReturn(appEntry);
- when(mFragment.getPackageInfo()).thenReturn(packageInfo);
-
- mController.refreshUi();
-
- verify(mController).checkForceStop(appEntry, packageInfo);
- verify(mController).initUninstallButtons(appEntry, packageInfo);
- }
-
- @Test
- public void initUninstallButtonForUserApp_shouldSetNegativeButton() {
- final ApplicationInfo info = new ApplicationInfo();
- info.flags = ApplicationInfo.FLAG_INSTALLED;
- info.enabled = true;
- final PackageInfo packageInfo = mock(PackageInfo.class);
- packageInfo.applicationInfo = info;
- when(mFragment.getPackageInfo()).thenReturn(packageInfo);
-
- assertThat(mController.initUninstallButtonForUserApp()).isTrue();
- verify(mController.mActionButtons).setButton1Positive(false);
- }
-
- // Tests that we don't show the uninstall button for instant apps"
- @Test
- public void initUninstallButtonForUserApp_instantApps_noUninstallButton() {
- // Make this app appear to be instant.
- ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
- (InstantAppDataProvider) (i -> true));
- final ApplicationInfo info = new ApplicationInfo();
- info.flags = ApplicationInfo.FLAG_INSTALLED;
- info.enabled = true;
- final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
- appEntry.info = info;
- final PackageInfo packageInfo = mock(PackageInfo.class);
- packageInfo.applicationInfo = info;
- when(mFragment.getPackageInfo()).thenReturn(packageInfo);
-
- assertThat(mController.initUninstallButtonForUserApp()).isFalse();
- verify(mController.mActionButtons).setButton1Visible(false);
- }
-
- @Test
- public void initUninstallButtonForUserApp_notInstalledForCurrentUser_shouldDisableButton() {
- final ApplicationInfo info = new ApplicationInfo();
- info.enabled = true;
- final PackageInfo packageInfo = mock(PackageInfo.class);
- packageInfo.applicationInfo = info;
- when(mFragment.getPackageInfo()).thenReturn(packageInfo);
- final int userID1 = 1;
- final int userID2 = 2;
- final List<UserInfo> userInfos = new ArrayList<>();
- userInfos.add(new UserInfo(userID1, "User1", UserInfo.FLAG_PRIMARY));
- userInfos.add(new UserInfo(userID2, "User2", UserInfo.FLAG_GUEST));
- when(mUserManager.getUsers(true)).thenReturn(userInfos);
-
- assertThat(mController.initUninstallButtonForUserApp()).isFalse();
- }
-
- // Tests that we don't show the force stop button for instant apps (they aren't allowed to run
- // when they aren't in the foreground).
- @Test
- public void checkForceStop_instantApps_shouldNotShowForceStop() {
- // Make this app appear to be instant.
- ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
- (InstantAppDataProvider) (i -> true));
- final PackageInfo packageInfo = mock(PackageInfo.class);
- final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
- final ApplicationInfo info = new ApplicationInfo();
- appEntry.info = info;
-
- mController.checkForceStop(appEntry, packageInfo);
-
- verify(mController.mActionButtons).setButton2Visible(false);
- }
-
- @Test
- public void checkForceStop_isStateProtected_shouldDisableForceStop() {
- ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
- (InstantAppDataProvider) (i -> false));
- final String packageName = "Package1";
- final PackageInfo packageInfo = new PackageInfo();
- packageInfo.packageName = packageName;
- final ApplicationInfo appInfo = new ApplicationInfo();
- appInfo.uid = 42;
- appInfo.sourceDir = "source";
- final ApplicationsState.AppEntry appEntry = new ApplicationsState.AppEntry(
- mContext, appInfo, 0);
- when(mPackageManager.isPackageStateProtected(packageName, 0)).thenReturn(true);
-
- mController.checkForceStop(appEntry, packageInfo);
-
- verify(mController.mActionButtons).setButton2Enabled(false);
- }
-
- @Test
- public void checkForceStop_hasActiveAdmin_shouldDisableForceStop() {
- ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
- (InstantAppDataProvider) (i -> false));
- final String packageName = "Package1";
- final PackageInfo packageInfo = new PackageInfo();
- packageInfo.packageName = packageName;
- final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
- when(mDevicePolicyManager.packageHasActiveAdmins(packageName)).thenReturn(true);
-
- mController.checkForceStop(appEntry, packageInfo);
-
- verify(mController.mActionButtons).setButton2Enabled(false);
- }
-
- @Test
- public void checkForceStop_appRunning_shouldEnableForceStop() {
- ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
- (InstantAppDataProvider) (i -> false));
- final PackageInfo packageInfo = mock(PackageInfo.class);
- final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
- final ApplicationInfo info = new ApplicationInfo();
- appEntry.info = info;
-
- mController.checkForceStop(appEntry, packageInfo);
-
- verify(mController.mActionButtons).setButton2Enabled(true);
- }
-
- @Test
- public void checkForceStop_appStopped_shouldQueryPackageRestart() {
- ReflectionHelpers.setStaticField(AppUtils.class, "sInstantAppDataProvider",
- (InstantAppDataProvider) (i -> false));
- final PackageInfo packageInfo = mock(PackageInfo.class);
- final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
- final ApplicationInfo info = new ApplicationInfo();
- appEntry.info = info;
- info.flags = ApplicationInfo.FLAG_STOPPED;
- info.packageName = "com.android.setting";
-
- mController.checkForceStop(appEntry, packageInfo);
-
- verify(mContext).sendOrderedBroadcastAsUser(argThat(intent -> intent != null
- && intent.getAction().equals(Intent.ACTION_QUERY_PACKAGE_RESTART)),
- any(UserHandle.class), nullable(String.class), any(BroadcastReceiver.class),
- nullable(Handler.class), anyInt(), nullable(String.class), nullable(Bundle.class));
- }
-
- @Test
- public void handleDisableable_appIsHomeApp_buttonShouldNotWork() {
- final ApplicationInfo info = new ApplicationInfo();
- info.packageName = "pkg";
- info.enabled = true;
- final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
- appEntry.info = info;
- final HashSet<String> homePackages = new HashSet<>();
- homePackages.add(info.packageName);
- ReflectionHelpers.setField(mController, "mHomePackages", homePackages);
-
- assertThat(mController.handleDisableable(appEntry, mock(PackageInfo.class))).isFalse();
- verify(mController.mActionButtons).setButton1Text(R.string.disable_text);
- }
-
- @Test
- @Config(shadows = ShadowUtils.class)
- public void handleDisableable_appIsEnabled_buttonShouldWork() {
- final ApplicationInfo info = new ApplicationInfo();
- info.packageName = "pkg";
- info.enabled = true;
- info.enabledSetting = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
- final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
- appEntry.info = info;
- when(mFeatureFactory.applicationFeatureProvider.getKeepEnabledPackages())
- .thenReturn(new HashSet<>());
-
- assertThat(mController.handleDisableable(appEntry, mock(PackageInfo.class))).isTrue();
- verify(mController.mActionButtons).setButton1Text(R.string.disable_text);
- }
-
- @Test
- @Config(shadows = ShadowUtils.class)
- public void handleDisableable_appIsDisabled_buttonShouldShowEnable() {
- final ApplicationInfo info = new ApplicationInfo();
- info.packageName = "pkg";
- info.enabled = false;
- info.enabledSetting = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
- final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
- appEntry.info = info;
- when(mFeatureFactory.applicationFeatureProvider.getKeepEnabledPackages())
- .thenReturn(new HashSet<>());
-
- assertThat(mController.handleDisableable(appEntry, mock(PackageInfo.class))).isTrue();
- verify(mController.mActionButtons).setButton1Text(R.string.enable_text);
- verify(mController.mActionButtons).setButton1Positive(true);
- }
-
- @Test
- @Config(shadows = ShadowUtils.class)
- public void handleDisableable_appIsEnabledAndInKeepEnabledWhitelist_buttonShouldNotWork() {
- final ApplicationInfo info = new ApplicationInfo();
- info.packageName = "pkg";
- info.enabled = true;
- info.enabledSetting = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
- final ApplicationsState.AppEntry appEntry = mock(ApplicationsState.AppEntry.class);
- appEntry.info = info;
- final HashSet<String> packages = new HashSet<>();
- packages.add(info.packageName);
- when(mFeatureFactory.applicationFeatureProvider.getKeepEnabledPackages())
- .thenReturn(packages);
-
- assertThat(mController.handleDisableable(appEntry, mock(PackageInfo.class))).isFalse();
- verify(mController.mActionButtons).setButton1Text(R.string.disable_text);
- }
-
- @Implements(Utils.class)
- public static class ShadowUtils {
- @Implementation
- public static boolean isSystemPackage(Resources resources, PackageManager pm,
- PackageInfo pkg) {
- return false;
- }
- }
-}
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/AppButtonsPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/applications/appinfo/AppButtonsPreferenceControllerTest.java
similarity index 93%
rename from tests/robotests/src/com/android/settings/fuelgauge/AppButtonsPreferenceControllerTest.java
rename to tests/robotests/src/com/android/settings/applications/appinfo/AppButtonsPreferenceControllerTest.java
index 551cb3e..24579ef 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/AppButtonsPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/appinfo/AppButtonsPreferenceControllerTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.settings.fuelgauge;
+package com.android.settings.applications.appinfo;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Matchers.any;
@@ -44,6 +44,8 @@
import com.android.settings.R;
import com.android.settings.SettingsActivity;
+import com.android.settings.applications.appinfo.AppButtonsPreferenceController;
+import com.android.settings.applications.appinfo.ButtonActionDialogFragment;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.widget.ActionButtonPreference;
import com.android.settings.widget.ActionButtonPreferenceTest;
@@ -107,6 +109,7 @@
MockitoAnnotations.initMocks(this);
FakeFeatureFactory.setupForTest();
+ doReturn(mDpm).when(mSettingsActivity).getSystemService(Context.DEVICE_POLICY_SERVICE);
doReturn(mUserManager).when(mSettingsActivity).getSystemService(Context.USER_SERVICE);
doReturn(mPackageManger).when(mSettingsActivity).getPackageManager();
doReturn(mAm).when(mSettingsActivity).getSystemService(Context.ACTIVITY_SERVICE);
@@ -115,8 +118,7 @@
when(mSettingsActivity.getResources().getString(anyInt())).thenReturn(RESOURCE_STRING);
mController = spy(new AppButtonsPreferenceController(mSettingsActivity, mFragment,
- mLifecycle, PACKAGE_NAME, mState, mDpm, mUserManager, mPackageManger,
- REQUEST_UNINSTALL, REQUEST_REMOVE_DEVICE_ADMIN));
+ mLifecycle, PACKAGE_NAME, mState, REQUEST_UNINSTALL, REQUEST_REMOVE_DEVICE_ADMIN));
doReturn(false).when(mController).isFallbackPackage(anyString());
mAppEntry.info = mAppInfo;
@@ -335,6 +337,15 @@
}
@Test
+ public void handleActivityResult_packageUninstalled_shouldFinishPrefernecePanel() {
+ doReturn(false).when(mController).refreshUi();
+
+ mController.handleActivityResult(REQUEST_UNINSTALL, 0, mock(Intent.class));
+
+ verify(mSettingsActivity).finishPreferencePanel(anyInt(), any(Intent.class));
+ }
+
+ @Test
public void refreshUi_packageNull_shouldNotCrash() {
mController.mPackageName = null;
@@ -344,7 +355,7 @@
@Test
public void onPackageListChanged_available_shouldRefreshUi() {
- doReturn(true).when(mController).isAvailable();
+ doReturn(mController.AVAILABLE).when(mController).getAvailabilityStatus();
doReturn(true).when(mController).refreshUi();
mController.onPackageListChanged();
@@ -354,7 +365,7 @@
@Test
public void onPackageListChanged_notAvailable_shouldNotRefreshUiAndNoCrash() {
- doReturn(false).when(mController).isAvailable();
+ doReturn(mController.DISABLED_FOR_USER).when(mController).getAvailabilityStatus();
mController.onPackageListChanged();
diff --git a/tests/robotests/src/com/android/settings/applications/appinfo/AppInfoDashboardFragmentTest.java b/tests/robotests/src/com/android/settings/applications/appinfo/AppInfoDashboardFragmentTest.java
index 3128f30..8314cb7 100644
--- a/tests/robotests/src/com/android/settings/applications/appinfo/AppInfoDashboardFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/applications/appinfo/AppInfoDashboardFragmentTest.java
@@ -233,15 +233,6 @@
}
@Test
- public void onActivityResult_packageUninstalled_shouldFinishAndRemoveTask() {
- doReturn(false).when(mFragment).refreshUi();
-
- mFragment.onActivityResult(mFragment.REQUEST_UNINSTALL, 0, mock(Intent.class));
-
- verify(mActivity).finishAndRemoveTask();
- }
-
- @Test
public void getPreferenceControllers_noPackageInfo_shouldReturnNull() {
doNothing().when(mFragment).retrieveAppEntry();
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/ButtonActionDialogFragmentTest.java b/tests/robotests/src/com/android/settings/applications/appinfo/ButtonActionDialogFragmentTest.java
similarity index 97%
rename from tests/robotests/src/com/android/settings/fuelgauge/ButtonActionDialogFragmentTest.java
rename to tests/robotests/src/com/android/settings/applications/appinfo/ButtonActionDialogFragmentTest.java
index 83d8f7a..ae6ba1d 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/ButtonActionDialogFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/applications/appinfo/ButtonActionDialogFragmentTest.java
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.android.settings.fuelgauge;
+package com.android.settings.applications.appinfo;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Matchers.anyInt;
@@ -128,7 +128,7 @@
/**
* Test fragment that used as the target fragment, it must implement the
- * {@link com.android.settings.fuelgauge.ButtonActionDialogFragment.AppButtonsDialogListener}
+ * {@link ButtonActionDialogFragment.AppButtonsDialogListener}
*/
public static class TestFragment extends Fragment implements
ButtonActionDialogFragment.AppButtonsDialogListener {
diff --git a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPickerTest.java b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPickerTest.java
index bdf249d..3aa83a8 100644
--- a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPickerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPickerTest.java
@@ -16,8 +16,6 @@
package com.android.settings.applications.defaultapps;
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
@@ -25,20 +23,11 @@
import android.app.Activity;
import android.content.Context;
-import android.content.Intent;
-import android.content.pm.ActivityInfo;
-import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
-import android.content.pm.PackageManager.NameNotFoundException;
-import android.content.pm.ResolveInfo;
import android.os.UserManager;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settingslib.applications.DefaultAppInfo;
-
-import java.util.ArrayList;
-import java.util.List;
import org.junit.Before;
import org.junit.Test;
@@ -85,39 +74,4 @@
mPicker.getDefaultKey();
verify(mPackageManager).getDefaultBrowserPackageNameAsUser(anyInt());
}
-
- @Test
- public void getCandidates_shouldNotIncludeDuplicatePackageName() throws NameNotFoundException {
- final List<ResolveInfo> resolveInfos = new ArrayList<>();
- final String PACKAGE_ONE = "com.first.package";
- final String PACKAGE_TWO = "com.second.package";
- resolveInfos.add(createResolveInfo(PACKAGE_ONE));
- resolveInfos.add(createResolveInfo(PACKAGE_TWO));
- resolveInfos.add(createResolveInfo(PACKAGE_ONE));
- resolveInfos.add(createResolveInfo(PACKAGE_TWO));
- when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
- .thenReturn(resolveInfos);
- when(mPackageManager.getApplicationInfoAsUser(eq(PACKAGE_ONE), anyInt(), anyInt()))
- .thenReturn(createApplicationInfo(PACKAGE_ONE));
- when(mPackageManager.getApplicationInfoAsUser(eq(PACKAGE_TWO), anyInt(), anyInt()))
- .thenReturn(createApplicationInfo(PACKAGE_TWO));
-
- final List<DefaultAppInfo> defaultBrowserInfo = mPicker.getCandidates();
-
- assertThat(defaultBrowserInfo.size()).isEqualTo(2);
- }
-
- private ResolveInfo createResolveInfo(String packageName) {
- final ResolveInfo info = new ResolveInfo();
- info.handleAllWebDataURI = true;
- info.activityInfo = new ActivityInfo();
- info.activityInfo.packageName = packageName;
- return info;
- }
-
- private ApplicationInfo createApplicationInfo(String packageName) {
- final ApplicationInfo info = new ApplicationInfo();
- info.packageName = packageName;
- return info;
- }
}
diff --git a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceControllerTest.java
index 6bf6ac4..d4c4115 100644
--- a/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/defaultapps/DefaultBrowserPreferenceControllerTest.java
@@ -17,15 +17,21 @@
package com.android.settings.applications.defaultapps;
import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.Intent;
+import android.content.pm.ActivityInfo;
+import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.UserManager;
import androidx.preference.Preference;
@@ -33,6 +39,8 @@
import com.android.settings.R;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import java.util.ArrayList;
+import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -73,8 +81,11 @@
@Test
public void isAvailable_hasBrowser_shouldReturnTrue() {
+ final ResolveInfo info = new ResolveInfo();
+ info.activityInfo = new ActivityInfo();
+ info.handleAllWebDataURI = true;
when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
- .thenReturn(Collections.singletonList(new ResolveInfo()));
+ .thenReturn(Collections.singletonList(info));
assertThat(mController.isAvailable()).isTrue();
}
@@ -89,6 +100,28 @@
}
@Test
+ public void getDefaultAppLabel_hasAppWithMultipleResolvedInfo_shouldReturnLabel()
+ throws NameNotFoundException {
+ DefaultBrowserPreferenceController spyController = spy(mController);
+ doReturn(null).when(spyController).getDefaultAppIcon();
+ final List<ResolveInfo> resolveInfos = new ArrayList<>();
+ final CharSequence PACKAGE_NAME = "com.test.package";
+ final ResolveInfo info1 = spy(createResolveInfo(PACKAGE_NAME.toString()));
+ when(info1.loadLabel(mPackageManager)).thenReturn(PACKAGE_NAME);
+ resolveInfos.add(info1);
+ resolveInfos.add(createResolveInfo(PACKAGE_NAME.toString()));
+ when(mPackageManager.getDefaultBrowserPackageNameAsUser(anyInt())).thenReturn(null);
+ when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
+ .thenReturn(resolveInfos);
+ when(mPackageManager.getApplicationInfoAsUser(
+ eq(PACKAGE_NAME.toString()), anyInt(), anyInt()))
+ .thenReturn(createApplicationInfo(PACKAGE_NAME.toString()));
+ final Preference pref = mock(Preference.class);
+
+ assertThat(spyController.getDefaultAppLabel()).isEqualTo(PACKAGE_NAME);
+ }
+
+ @Test
public void getDefaultApp_shouldGetDefaultBrowserPackage() {
mController.getDefaultAppInfo();
@@ -103,4 +136,40 @@
assertThat(mController.isBrowserDefault("pkg", 0)).isTrue();
}
+
+ @Test
+ public void getCandidates_shouldNotIncludeDuplicatePackageName() throws NameNotFoundException {
+ final List<ResolveInfo> resolveInfos = new ArrayList<>();
+ final String PACKAGE_ONE = "com.first.package";
+ final String PACKAGE_TWO = "com.second.package";
+ resolveInfos.add(createResolveInfo(PACKAGE_ONE));
+ resolveInfos.add(createResolveInfo(PACKAGE_TWO));
+ resolveInfos.add(createResolveInfo(PACKAGE_ONE));
+ resolveInfos.add(createResolveInfo(PACKAGE_TWO));
+ when(mPackageManager.queryIntentActivitiesAsUser(any(Intent.class), anyInt(), anyInt()))
+ .thenReturn(resolveInfos);
+ when(mPackageManager.getApplicationInfoAsUser(eq(PACKAGE_ONE), anyInt(), anyInt()))
+ .thenReturn(createApplicationInfo(PACKAGE_ONE));
+ when(mPackageManager.getApplicationInfoAsUser(eq(PACKAGE_TWO), anyInt(), anyInt()))
+ .thenReturn(createApplicationInfo(PACKAGE_TWO));
+
+ final List<ResolveInfo> defaultBrowserInfo =
+ mController.getCandidates(mPackageManager, 0 /* userId */);
+
+ assertThat(defaultBrowserInfo.size()).isEqualTo(2);
+ }
+
+ private ResolveInfo createResolveInfo(String packageName) {
+ final ResolveInfo info = new ResolveInfo();
+ info.handleAllWebDataURI = true;
+ info.activityInfo = new ActivityInfo();
+ info.activityInfo.packageName = packageName;
+ return info;
+ }
+
+ private ApplicationInfo createApplicationInfo(String packageName) {
+ final ApplicationInfo info = new ApplicationInfo();
+ info.packageName = packageName;
+ return info;
+ }
}
diff --git a/tests/robotests/src/com/android/settings/applications/manageapplications/ManageApplicationsTest.java b/tests/robotests/src/com/android/settings/applications/manageapplications/ManageApplicationsTest.java
index af297c4..8943d72 100644
--- a/tests/robotests/src/com/android/settings/applications/manageapplications/ManageApplicationsTest.java
+++ b/tests/robotests/src/com/android/settings/applications/manageapplications/ManageApplicationsTest.java
@@ -16,14 +16,14 @@
package com.android.settings.applications.manageapplications;
-import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_DRAGGING;
-import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE;
-import static com.android.settings.applications.manageapplications.AppFilterRegistry.FILTER_APPS_ALL;
-import static com.android.settings.applications.manageapplications.ManageApplications.LIST_TYPE_MAIN;
-import static com.android.settings.applications.manageapplications.ManageApplications.LIST_TYPE_NOTIFICATION;
-import static com.google.common.truth.Truth.assertThat;
+import static com.android.settings.applications.manageapplications.AppFilterRegistry
+ .FILTER_APPS_ALL;
+import static com.android.settings.applications.manageapplications.ManageApplications
+ .LIST_TYPE_MAIN;
+import static com.android.settings.applications.manageapplications.ManageApplications
+ .LIST_TYPE_NOTIFICATION;
-import static junit.framework.Assert.assertEquals;
+import static com.google.common.truth.Truth.assertThat;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Matchers.any;
@@ -36,11 +36,14 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_DRAGGING;
+import static androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE;
+
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
-import androidx.recyclerview.widget.RecyclerView;
+import android.os.UserManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
@@ -63,6 +66,8 @@
import java.util.ArrayList;
+import androidx.recyclerview.widget.RecyclerView;
+
@RunWith(SettingsRobolectricTestRunner.class)
public class ManageApplicationsTest {
@@ -272,6 +277,10 @@
@Test
public void applicationsAdapter_onBindViewHolder_updateSwitch_notifications() {
ManageApplications manageApplications = mock(ManageApplications.class);
+ when(manageApplications.getActivity()).thenReturn(mock(Activity.class));
+ UserManager um = mock(UserManager.class);
+ when(um.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[]{});
+ ReflectionHelpers.setField(manageApplications, "mUserManager", um);
manageApplications.mListType = LIST_TYPE_NOTIFICATION;
ApplicationViewHolder holder = mock(ApplicationViewHolder.class);
ReflectionHelpers.setField(holder, "itemView", mock(View.class));
@@ -293,6 +302,9 @@
manageApplications.mListType = LIST_TYPE_MAIN;
ApplicationViewHolder holder = mock(ApplicationViewHolder.class);
ReflectionHelpers.setField(holder, "itemView", mock(View.class));
+ UserManager um = mock(UserManager.class);
+ when(um.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[]{});
+ ReflectionHelpers.setField(manageApplications, "mUserManager", um);
ManageApplications.ApplicationsAdapter adapter =
new ManageApplications.ApplicationsAdapter(mState,
manageApplications, mock(AppFilterItem.class),
@@ -308,6 +320,10 @@
@Test
public void sortOrderSavedOnRebuild() {
ManageApplications manageApplications = mock(ManageApplications.class);
+ when(manageApplications.getActivity()).thenReturn(mock(Activity.class));
+ UserManager um = mock(UserManager.class);
+ when(um.getProfileIdsWithDisabled(anyInt())).thenReturn(new int[]{});
+ ReflectionHelpers.setField(manageApplications, "mUserManager", um);
manageApplications.mListType = LIST_TYPE_NOTIFICATION;
manageApplications.mSortOrder = -1;
ManageApplications.ApplicationsAdapter adapter =
diff --git a/tests/robotests/src/com/android/settings/applications/DataSaverControllerTest.java b/tests/robotests/src/com/android/settings/applications/specialaccess/DataSaverControllerTest.java
similarity index 92%
rename from tests/robotests/src/com/android/settings/applications/DataSaverControllerTest.java
rename to tests/robotests/src/com/android/settings/applications/specialaccess/DataSaverControllerTest.java
index 22140bb..c632d08 100644
--- a/tests/robotests/src/com/android/settings/applications/DataSaverControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/specialaccess/DataSaverControllerTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.settings.applications;
+package com.android.settings.applications.specialaccess;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.spy;
@@ -40,7 +40,7 @@
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application.getApplicationContext());
- mController = new DataSaverController(mContext);
+ mController = new DataSaverController(mContext, "key");
}
@Test
diff --git a/tests/robotests/src/com/android/settings/applications/DeviceAdministratorsControllerTest.java b/tests/robotests/src/com/android/settings/applications/specialaccess/DeviceAdministratorsControllerTest.java
similarity index 96%
rename from tests/robotests/src/com/android/settings/applications/DeviceAdministratorsControllerTest.java
rename to tests/robotests/src/com/android/settings/applications/specialaccess/DeviceAdministratorsControllerTest.java
index ad7e615..efa7846 100644
--- a/tests/robotests/src/com/android/settings/applications/DeviceAdministratorsControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/specialaccess/DeviceAdministratorsControllerTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.settings.applications;
+package com.android.settings.applications.specialaccess;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.spy;
@@ -40,7 +40,7 @@
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application.getApplicationContext());
- mController = new DeviceAdministratorsController(mContext);
+ mController = new DeviceAdministratorsController(mContext, "key");
}
@Test
diff --git a/tests/robotests/src/com/android/settings/applications/EnabledVrListenersControllerTest.java b/tests/robotests/src/com/android/settings/applications/specialaccess/EnabledVrListenersControllerTest.java
similarity index 66%
rename from tests/robotests/src/com/android/settings/applications/EnabledVrListenersControllerTest.java
rename to tests/robotests/src/com/android/settings/applications/specialaccess/EnabledVrListenersControllerTest.java
index b364720..7963fd4 100644
--- a/tests/robotests/src/com/android/settings/applications/EnabledVrListenersControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/specialaccess/EnabledVrListenersControllerTest.java
@@ -14,10 +14,9 @@
* limitations under the License.
*/
-package com.android.settings.applications;
+package com.android.settings.applications.specialaccess;
import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.spy;
import android.content.Context;
@@ -26,31 +25,39 @@
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 org.robolectric.shadow.api.Shadow;
+import org.robolectric.shadows.ShadowActivityManager;
@RunWith(SettingsRobolectricTestRunner.class)
public class EnabledVrListenersControllerTest {
private Context mContext;
private EnabledVrListenersController mController;
+ private ShadowActivityManager mActivityManager;
@Before
public void setUp() {
- MockitoAnnotations.initMocks(this);
- mContext = spy(RuntimeEnvironment.application.getApplicationContext());
- mController = new EnabledVrListenersController(mContext);
+ mContext = RuntimeEnvironment.application;
+ mController = new EnabledVrListenersController(mContext, "key");
+ mActivityManager = Shadow.extract(mContext.getSystemService(Context.ACTIVITY_SERVICE));
}
@Test
- public void testEnabledVrListeners_byDefault_shouldBeShown() {
+ public void isAvailable_byDefault_true() {
+ assertThat(mController.isAvailable()).isTrue();
+ }
+
+ @Test
+ public void isAvailable_lowMemory_false() {
+ mActivityManager.setIsLowRamDevice(true);
assertThat(mController.isAvailable()).isTrue();
}
@Test
@Config(qualifiers = "mcc999")
- public void testEnabledVrListeners_ifDisabled_shouldNotBeShown() {
+ public void isAvailable_disabled_false() {
assertThat(mController.isAvailable()).isFalse();
}
}
diff --git a/tests/robotests/src/com/android/settings/applications/HighPowerAppsControllerTest.java b/tests/robotests/src/com/android/settings/applications/specialaccess/HighPowerAppsControllerTest.java
similarity index 92%
rename from tests/robotests/src/com/android/settings/applications/HighPowerAppsControllerTest.java
rename to tests/robotests/src/com/android/settings/applications/specialaccess/HighPowerAppsControllerTest.java
index 6dfaa7c..4713be2 100644
--- a/tests/robotests/src/com/android/settings/applications/HighPowerAppsControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/specialaccess/HighPowerAppsControllerTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.settings.applications;
+package com.android.settings.applications.specialaccess;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.spy;
@@ -40,7 +40,7 @@
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application.getApplicationContext());
- mController = new HighPowerAppsController(mContext);
+ mController = new HighPowerAppsController(mContext, "key");
}
@Test
diff --git a/tests/robotests/src/com/android/settings/applications/PremiumSmsControllerTest.java b/tests/robotests/src/com/android/settings/applications/specialaccess/PremiumSmsControllerTest.java
similarity index 92%
rename from tests/robotests/src/com/android/settings/applications/PremiumSmsControllerTest.java
rename to tests/robotests/src/com/android/settings/applications/specialaccess/PremiumSmsControllerTest.java
index cad4100..8f16da7 100644
--- a/tests/robotests/src/com/android/settings/applications/PremiumSmsControllerTest.java
+++ b/tests/robotests/src/com/android/settings/applications/specialaccess/PremiumSmsControllerTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.settings.applications;
+package com.android.settings.applications.specialaccess;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.spy;
@@ -40,7 +40,7 @@
public void setUp() {
MockitoAnnotations.initMocks(this);
mContext = spy(RuntimeEnvironment.application.getApplicationContext());
- mController = new PremiumSmsController(mContext);
+ mController = new PremiumSmsController(mContext, "key");
}
@Test
diff --git a/tests/robotests/src/com/android/settings/applications/specialaccess/ZenAccessControllerTest.java b/tests/robotests/src/com/android/settings/applications/specialaccess/ZenAccessControllerTest.java
new file mode 100644
index 0000000..205de10
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/applications/specialaccess/ZenAccessControllerTest.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.applications.specialaccess;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.Context;
+
+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.shadow.api.Shadow;
+import org.robolectric.shadows.ShadowActivityManager;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+public class ZenAccessControllerTest {
+
+ private Context mContext;
+ private ZenAccessController mController;
+ private ShadowActivityManager mActivityManager;
+
+ @Before
+ public void setUp() {
+ mContext = RuntimeEnvironment.application;
+ mController = new ZenAccessController(mContext, "key");
+ mActivityManager = Shadow.extract(mContext.getSystemService(Context.ACTIVITY_SERVICE));
+ }
+
+ @Test
+ public void isAvailable_byDefault_true() {
+ assertThat(mController.isAvailable()).isTrue();
+ }
+
+ @Test
+ public void isAvailable_lowMemory_false() {
+ mActivityManager.setIsLowRamDevice(true);
+ assertThat(mController.isAvailable()).isTrue();
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/bluetooth/AvailableMediaBluetoothDeviceUpdaterTest.java b/tests/robotests/src/com/android/settings/bluetooth/AvailableMediaBluetoothDeviceUpdaterTest.java
index ced8fc4..0b1311d 100644
--- a/tests/robotests/src/com/android/settings/bluetooth/AvailableMediaBluetoothDeviceUpdaterTest.java
+++ b/tests/robotests/src/com/android/settings/bluetooth/AvailableMediaBluetoothDeviceUpdaterTest.java
@@ -204,6 +204,33 @@
}
@Test
+ public void onProfileConnectionStateChanged_hearingAidDeviceConnected_notInCall_addPreference()
+ {
+ mShadowAudioManager.setMode(AudioManager.MODE_NORMAL);
+ when(mBluetoothDeviceUpdater.
+ isDeviceConnected(any(CachedBluetoothDevice.class))).thenReturn(true);
+ when(mCachedBluetoothDevice.isConnectedHearingAidDevice()).thenReturn(true);
+
+ mBluetoothDeviceUpdater.onProfileConnectionStateChanged(mCachedBluetoothDevice,
+ BluetoothProfile.STATE_CONNECTED, BluetoothProfile.HEARING_AID);
+
+ verify(mBluetoothDeviceUpdater).addPreference(mCachedBluetoothDevice);
+ }
+
+ @Test
+ public void onProfileConnectionStateChanged_hearingAidDeviceConnected_inCall_addPreference() {
+ mShadowAudioManager.setMode(AudioManager.MODE_IN_CALL);
+ when(mBluetoothDeviceUpdater.
+ isDeviceConnected(any(CachedBluetoothDevice.class))).thenReturn(true);
+ when(mCachedBluetoothDevice.isConnectedHearingAidDevice()).thenReturn(true);
+
+ mBluetoothDeviceUpdater.onProfileConnectionStateChanged(mCachedBluetoothDevice,
+ BluetoothProfile.STATE_CONNECTED, BluetoothProfile.HEARING_AID);
+
+ verify(mBluetoothDeviceUpdater).addPreference(mCachedBluetoothDevice);
+ }
+
+ @Test
public void onProfileConnectionStateChanged_deviceDisconnected_removePreference() {
mBluetoothDeviceUpdater.onProfileConnectionStateChanged(mCachedBluetoothDevice,
BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.A2DP);
diff --git a/tests/robotests/src/com/android/settings/bluetooth/ConnectedBluetoothDeviceUpdaterTest.java b/tests/robotests/src/com/android/settings/bluetooth/ConnectedBluetoothDeviceUpdaterTest.java
index 483df01..8120d91 100644
--- a/tests/robotests/src/com/android/settings/bluetooth/ConnectedBluetoothDeviceUpdaterTest.java
+++ b/tests/robotests/src/com/android/settings/bluetooth/ConnectedBluetoothDeviceUpdaterTest.java
@@ -205,6 +205,34 @@
}
@Test
+ public void onProfileConnectionStateChanged_hearingAidDeviceConnected_inCall_removePreference()
+ {
+ mShadowAudioManager.setMode(AudioManager.MODE_IN_CALL);
+ when(mBluetoothDeviceUpdater.
+ isDeviceConnected(any(CachedBluetoothDevice.class))).thenReturn(true);
+ when(mCachedBluetoothDevice.isConnectedHearingAidDevice()).thenReturn(true);
+
+ mBluetoothDeviceUpdater.onProfileConnectionStateChanged(mCachedBluetoothDevice,
+ BluetoothProfile.STATE_CONNECTED, BluetoothProfile.HEARING_AID);
+
+ verify(mBluetoothDeviceUpdater).removePreference(mCachedBluetoothDevice);
+ }
+
+ @Test
+ public void onProfileConnectionStateChanged_hearingAidDeviceConnected_notInCall_removePreference
+ () {
+ mShadowAudioManager.setMode(AudioManager.MODE_NORMAL);
+ when(mBluetoothDeviceUpdater.
+ isDeviceConnected(any(CachedBluetoothDevice.class))).thenReturn(true);
+ when(mCachedBluetoothDevice.isConnectedHearingAidDevice()).thenReturn(true);
+
+ mBluetoothDeviceUpdater.onProfileConnectionStateChanged(mCachedBluetoothDevice,
+ BluetoothProfile.STATE_CONNECTED, BluetoothProfile.HEARING_AID);
+
+ verify(mBluetoothDeviceUpdater).removePreference(mCachedBluetoothDevice);
+ }
+
+ @Test
public void onProfileConnectionStateChanged_deviceDisconnected_removePreference() {
mBluetoothDeviceUpdater.onProfileConnectionStateChanged(mCachedBluetoothDevice,
BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.A2DP);
diff --git a/tests/robotests/src/com/android/settings/core/BasePreferenceControllerSignatureInspector.java b/tests/robotests/src/com/android/settings/core/BasePreferenceControllerSignatureInspector.java
index a9b4f5d..ce438b0 100644
--- a/tests/robotests/src/com/android/settings/core/BasePreferenceControllerSignatureInspector.java
+++ b/tests/robotests/src/com/android/settings/core/BasePreferenceControllerSignatureInspector.java
@@ -67,7 +67,7 @@
}
assertWithMessage("All BasePreferenceController (and subclasses) constructor must either"
- + "only take Context, or (Context, String). No other types are allowed")
+ + " only take Context, or (Context, String). No other types are allowed")
.that(badClasses.toString())
.isEmpty();
diff --git a/tests/robotests/src/com/android/settings/dashboard/conditional/BackgroundDataConditionTest.java b/tests/robotests/src/com/android/settings/dashboard/conditional/BackgroundDataConditionTest.java
index 9b5bec3..725be79 100644
--- a/tests/robotests/src/com/android/settings/dashboard/conditional/BackgroundDataConditionTest.java
+++ b/tests/robotests/src/com/android/settings/dashboard/conditional/BackgroundDataConditionTest.java
@@ -22,10 +22,8 @@
import android.content.Context;
import android.content.Intent;
-import android.util.FeatureFlagUtils;
import com.android.settings.Settings;
-import com.android.settings.core.FeatureFlags;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import org.junit.Before;
@@ -51,9 +49,7 @@
}
@Test
- public void onPrimaryClick_v2enabled_shouldReturn2SummaryActivity() {
- FeatureFlagUtils.setEnabled(mContext, FeatureFlags.DATA_USAGE_SETTINGS_V2, true);
-
+ public void onPrimaryClick_shouldReturn2SummaryActivity() {
final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
BackgroundDataCondition backgroundDataCondition
= new BackgroundDataCondition(mConditionManager);
@@ -64,19 +60,4 @@
assertThat(intent.getComponent().getClassName()).isEqualTo(
Settings.DataUsageSummaryActivity.class.getName());
}
-
- @Test
- public void onPrimaryClick_v2disabled_shouldReturnLegacySummaryActivity() {
- FeatureFlagUtils.setEnabled(mContext, FeatureFlags.DATA_USAGE_SETTINGS_V2, false);
-
- final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
- BackgroundDataCondition backgroundDataCondition
- = new BackgroundDataCondition(mConditionManager);
- backgroundDataCondition.onPrimaryClick();
- verify(mContext).startActivity(argumentCaptor.capture());
- Intent intent = argumentCaptor.getValue();
-
- assertThat(intent.getComponent().getClassName()).isEqualTo(
- Settings.DataUsageSummaryLegacyActivity.class.getName());
- }
}
diff --git a/tests/robotests/src/com/android/settings/datausage/BillingCycleSettingsTest.java b/tests/robotests/src/com/android/settings/datausage/BillingCycleSettingsTest.java
index e4ed8bf..2d44628 100644
--- a/tests/robotests/src/com/android/settings/datausage/BillingCycleSettingsTest.java
+++ b/tests/robotests/src/com/android/settings/datausage/BillingCycleSettingsTest.java
@@ -31,12 +31,7 @@
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
-import androidx.preference.Preference;
-import androidx.preference.PreferenceManager;
-import androidx.preference.SwitchPreference;
-import android.util.FeatureFlagUtils;
-import com.android.settings.core.FeatureFlags;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settingslib.NetworkPolicyEditor;
@@ -47,6 +42,10 @@
import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
+import androidx.preference.Preference;
+import androidx.preference.PreferenceManager;
+import androidx.preference.SwitchPreference;
+
@RunWith(SettingsRobolectricTestRunner.class)
public class BillingCycleSettingsTest {
@@ -108,14 +107,12 @@
}
@Test
- public void testDataUsageSummary_shouldBeNullWithV2() {
+ public void testDataUsageSummary_shouldBeNull() {
final BillingCycleSettings billingCycleSettings = spy(new BillingCycleSettings());
when(billingCycleSettings.getContext()).thenReturn(mContext);
billingCycleSettings.setUpForTest(mNetworkPolicyEditor, mBillingCycle,
mDataLimit, mDataWarning, mEnableDataLimit, mEnableDataWarning);
- FeatureFlagUtils.setEnabled(mContext, FeatureFlags.DATA_USAGE_SETTINGS_V2, true);
-
doReturn("some-string").when(billingCycleSettings).getString(anyInt(), anyInt());
when(mNetworkPolicyEditor.getPolicyCycleDay(anyObject())).thenReturn(CYCLE_NONE + 1);
when(mNetworkPolicyEditor.getPolicyLimitBytes(anyObject())).thenReturn(2000L);
diff --git a/tests/robotests/src/com/android/settings/datausage/ChartDataUsagePreferenceTest.java b/tests/robotests/src/com/android/settings/datausage/ChartDataUsagePreferenceTest.java
index 00d02a3..e053e16 100644
--- a/tests/robotests/src/com/android/settings/datausage/ChartDataUsagePreferenceTest.java
+++ b/tests/robotests/src/com/android/settings/datausage/ChartDataUsagePreferenceTest.java
@@ -25,8 +25,10 @@
import android.net.NetworkStatsHistory;
import android.net.NetworkStatsHistory.Entry;
import android.util.SparseIntArray;
-import com.android.settings.graph.UsageView;
+
import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settings.widget.UsageView;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -65,7 +67,7 @@
when(mNetworkStatsHistory.getIndexAfter(end)).thenReturn(7);
final UsageView usageView = mock(UsageView.class);
final ArgumentCaptor<SparseIntArray> pointsCaptor =
- ArgumentCaptor.forClass(SparseIntArray.class);
+ ArgumentCaptor.forClass(SparseIntArray.class);
mPreference.calcPoints(usageView);
@@ -84,7 +86,7 @@
when(mNetworkStatsHistory.getIndexAfter(end)).thenReturn(5);
final UsageView usageView = mock(UsageView.class);
final ArgumentCaptor<SparseIntArray> pointsCaptor =
- ArgumentCaptor.forClass(SparseIntArray.class);
+ ArgumentCaptor.forClass(SparseIntArray.class);
mPreference.calcPoints(usageView);
@@ -113,9 +115,10 @@
* Create a network entry to be used to calculate the usage chart. In the calculation, we only
* need bucketStart, total bytes (rx + tx), and bucketDuration (which is set when we create
* the NetworkStatsHistory object). Other fields are ignored, so we don't initialize here.
+ *
* @param start the timestamp when this entry begins
- * @param rx the total number of received bytes
- * @param tx the total number of transmitted bytes
+ * @param rx the total number of received bytes
+ * @param tx the total number of transmitted bytes
* @return the network entry with the corresponding start time and data usage
*/
private Entry createEntry(long start, long rx, long tx) {
diff --git a/tests/robotests/src/com/android/settings/datausage/DataUsageSummaryLegacyTest.java b/tests/robotests/src/com/android/settings/datausage/DataUsageSummaryLegacyTest.java
deleted file mode 100644
index 2216792..0000000
--- a/tests/robotests/src/com/android/settings/datausage/DataUsageSummaryLegacyTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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
- */
-
-package com.android.settings.datausage;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Mockito.when;
-
-import android.content.Context;
-import android.net.ConnectivityManager;
-import android.text.format.Formatter;
-
-import com.android.settings.R;
-import com.android.settings.testutils.SettingsRobolectricTestRunner;
-import com.android.settings.testutils.shadow.SettingsShadowResources;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.robolectric.shadows.ShadowApplication;
-
-@RunWith(SettingsRobolectricTestRunner.class)
-public class DataUsageSummaryLegacyTest {
-
- @Mock
- private ConnectivityManager mManager;
- private Context mContext;
-
- /**
- * This set up is contrived to get a passing test so that the build doesn't block without tests.
- * These tests should be updated as code gets refactored to improve testability.
- */
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- ShadowApplication shadowContext = ShadowApplication.getInstance();
- shadowContext.setSystemService(Context.CONNECTIVITY_SERVICE, mManager);
- mContext = shadowContext.getApplicationContext();
- when(mManager.isNetworkSupported(anyInt())).thenReturn(true);
- }
-
- @Test
- public void formatUsage_shouldLookLikeFormatFileSize() {
- SettingsShadowResources
- .overrideResource(com.android.internal.R.string.fileSizeSuffix, "%1$s %2$s");
- final long usage = 2147483648L; // 2GB
- final String formattedUsage =
- DataUsageSummaryLegacy.formatUsage(mContext, "^1", usage).toString();
- final String formattedAsFileSize = Formatter.formatFileSize(mContext, usage);
- assertThat(formattedUsage).isEqualTo(formattedAsFileSize);
- }
-}
diff --git a/tests/robotests/src/com/android/settings/development/qstile/DevelopmentTilesTest.java b/tests/robotests/src/com/android/settings/development/qstile/DevelopmentTilesTest.java
index 85c1cb5..8367fd3 100644
--- a/tests/robotests/src/com/android/settings/development/qstile/DevelopmentTilesTest.java
+++ b/tests/robotests/src/com/android/settings/development/qstile/DevelopmentTilesTest.java
@@ -19,7 +19,10 @@
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import android.content.ComponentName;
+import android.content.pm.PackageManager;
import android.service.quicksettings.Tile;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
@@ -37,6 +40,9 @@
@Mock
private Tile mTile;
+ @Mock
+ private PackageManager mPackageManager;
+
private DevelopmentTiles mService;
@Before
@@ -48,11 +54,18 @@
@Test
public void refresh_devOptionIsDisabled_shouldResetTileValue() {
+ final ComponentName cn = new ComponentName(
+ mService.getPackageName(), mService.getClass().getName());
+ doReturn(mPackageManager).when(mService).getPackageManager();
+
DevelopmentSettingsEnabler.setDevelopmentSettingsEnabled(mService, false);
mService.setIsEnabled(true);
mService.refresh();
+ verify(mPackageManager).setComponentEnabledSetting(cn,
+ PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
+ PackageManager.DONT_KILL_APP);
assertThat(mService.isEnabled()).isFalse();
}
}
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/imei/ImeiInfoDialogControllerTest.java b/tests/robotests/src/com/android/settings/deviceinfo/imei/ImeiInfoDialogControllerTest.java
index 658a60a..349eddc 100644
--- a/tests/robotests/src/com/android/settings/deviceinfo/imei/ImeiInfoDialogControllerTest.java
+++ b/tests/robotests/src/com/android/settings/deviceinfo/imei/ImeiInfoDialogControllerTest.java
@@ -128,4 +128,19 @@
verify(mDialog).setText(eq(ID_IMEI_SV_VALUE), any());
verify(mDialog).removeViewFromScreen(ID_CDMA_SETTINGS);
}
+
+ @Test
+ public void populateImeiInfo_emptyImei_shouldSetMeid_imeiSetToEmptyString() {
+ doReturn(true).when(mController).isCdmaLteEnabled();
+ when(mTelephonyManager.getPhoneType()).thenReturn(TelephonyManager.PHONE_TYPE_CDMA);
+ when(mTelephonyManager.getImei(anyInt())).thenReturn(null);
+
+ mController.populateImeiInfo();
+
+ verify(mDialog).setText(ID_MEID_NUMBER_VALUE, MEID_NUMBER);
+ verify(mDialog).setText(ID_MIN_NUMBER_VALUE, MIN_NUMBER);
+ verify(mDialog).setText(ID_PRL_VERSION_VALUE, PRL_VERSION);
+ verify(mDialog).setText(eq(ID_IMEI_VALUE), eq(""));
+ verify(mDialog).setText(eq(ID_IMEI_SV_VALUE), any());
+ }
}
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
index a4107f5..c8ed42e 100644
--- a/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/deviceinfo/storage/StorageItemPreferenceControllerTest.java
@@ -19,6 +19,7 @@
import static com.android.settings.applications.manageapplications.ManageApplications.EXTRA_WORK_ONLY;
import static com.android.settings.utils.FileSizeFormatter.MEGABYTE_IN_BYTES;
import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
@@ -123,7 +124,8 @@
mController.handlePreferenceTreeClick(mPreference);
final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mActivity).startActivityAsUser(argumentCaptor.capture(), nullable(UserHandle.class));
+ verify(mActivity).startActivityForResultAsUser(argumentCaptor.capture(), anyInt(),
+ nullable(UserHandle.class));
final Intent intent = argumentCaptor.getValue();
assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -140,8 +142,8 @@
mController.handlePreferenceTreeClick(mPreference);
final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mFragment.getActivity())
- .startActivityAsUser(argumentCaptor.capture(), nullable(UserHandle.class));
+ verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+ anyInt(), nullable(UserHandle.class));
final Intent intent = argumentCaptor.getValue();
assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -167,8 +169,8 @@
mController.handlePreferenceTreeClick(mPreference);
final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
- nullable(UserHandle.class));
+ verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+ anyInt(), nullable(UserHandle.class));
final Intent intent = argumentCaptor.getValue();
assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -186,8 +188,8 @@
mController.handlePreferenceTreeClick(mPreference);
final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mFragment.getActivity())
- .startActivityAsUser(argumentCaptor.capture(), nullable(UserHandle.class));
+ verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+ anyInt(), nullable(UserHandle.class));
Intent intent = argumentCaptor.getValue();
assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -223,8 +225,8 @@
.isTrue();
final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
- nullable(UserHandle.class));
+ verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+ anyInt(), nullable(UserHandle.class));
Intent intent = argumentCaptor.getValue();
Intent browseIntent = mVolume.buildBrowseIntent();
@@ -240,8 +242,8 @@
mController.handlePreferenceTreeClick(mPreference);
final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
- nullable(UserHandle.class));
+ verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+ anyInt(), nullable(UserHandle.class));
Intent intent = argumentCaptor.getValue();
assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
@@ -258,8 +260,8 @@
mController.handlePreferenceTreeClick(mPreference);
final ArgumentCaptor<Intent> argumentCaptor = ArgumentCaptor.forClass(Intent.class);
- verify(mFragment.getActivity()).startActivityAsUser(argumentCaptor.capture(),
- nullable(UserHandle.class));
+ verify(mFragment.getActivity()).startActivityForResultAsUser(argumentCaptor.capture(),
+ anyInt(), nullable(UserHandle.class));
Intent intent = argumentCaptor.getValue();
assertThat(intent.getAction()).isEqualTo(Intent.ACTION_MAIN);
diff --git a/tests/robotests/src/com/android/settings/display/ColorModePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/display/ColorModePreferenceControllerTest.java
index c7b6535..83343fe 100644
--- a/tests/robotests/src/com/android/settings/display/ColorModePreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/display/ColorModePreferenceControllerTest.java
@@ -16,13 +16,12 @@
package com.android.settings.display;
+import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
-import androidx.preference.Preference;
import com.android.internal.app.ColorDisplayController;
import com.android.settings.R;
@@ -35,63 +34,69 @@
import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
+import androidx.preference.Preference;
+
@RunWith(SettingsRobolectricTestRunner.class)
public class ColorModePreferenceControllerTest {
@Mock
- private Preference mPreference;
- @Mock
private ColorDisplayController mColorDisplayController;
private Context mContext;
+ private Preference mPreference;
private ColorModePreferenceController mController;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mContext = RuntimeEnvironment.application;
- mController = spy(new ColorModePreferenceController(mContext));
+ mController = spy(new ColorModePreferenceController(mContext, "test"));
+ mPreference = new Preference(mContext);
doReturn(mColorDisplayController).when(mController).getColorDisplayController();
}
@Test
public void updateState_colorModeAutomatic_shouldSetSummaryToAutomatic() {
when(mColorDisplayController.getColorMode())
- .thenReturn(ColorDisplayController.COLOR_MODE_AUTOMATIC);
+ .thenReturn(ColorDisplayController.COLOR_MODE_AUTOMATIC);
mController.updateState(mPreference);
- verify(mPreference).setSummary(mContext.getString(R.string.color_mode_option_automatic));
+ assertThat(mPreference.getSummary())
+ .isEqualTo(mContext.getText(R.string.color_mode_option_automatic));
}
@Test
public void updateState_colorModeSaturated_shouldSetSummaryToSaturated() {
when(mColorDisplayController.getColorMode())
- .thenReturn(ColorDisplayController.COLOR_MODE_SATURATED);
+ .thenReturn(ColorDisplayController.COLOR_MODE_SATURATED);
mController.updateState(mPreference);
- verify(mPreference).setSummary(mContext.getString(R.string.color_mode_option_saturated));
+ assertThat(mPreference.getSummary())
+ .isEqualTo(mContext.getText(R.string.color_mode_option_saturated));
}
@Test
public void updateState_colorModeBoosted_shouldSetSummaryToBoosted() {
when(mColorDisplayController.getColorMode())
- .thenReturn(ColorDisplayController.COLOR_MODE_BOOSTED);
+ .thenReturn(ColorDisplayController.COLOR_MODE_BOOSTED);
mController.updateState(mPreference);
- verify(mPreference).setSummary(mContext.getString(R.string.color_mode_option_boosted));
+ assertThat(mPreference.getSummary())
+ .isEqualTo(mContext.getText(R.string.color_mode_option_boosted));
}
@Test
public void updateState_colorModeNatural_shouldSetSummaryToNatural() {
when(mColorDisplayController.getColorMode())
- .thenReturn(ColorDisplayController.COLOR_MODE_NATURAL);
+ .thenReturn(ColorDisplayController.COLOR_MODE_NATURAL);
mController.updateState(mPreference);
- verify(mPreference).setSummary(mContext.getString(R.string.color_mode_option_natural));
+ assertThat(mPreference.getSummary())
+ .isEqualTo(mContext.getText(R.string.color_mode_option_natural));
}
}
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BackgroundActivityPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BackgroundActivityPreferenceControllerTest.java
index d5f3e2b..3dee0a6 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/BackgroundActivityPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/BackgroundActivityPreferenceControllerTest.java
@@ -32,7 +32,6 @@
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.UserManager;
-import androidx.preference.Preference;
import com.android.settings.R;
import com.android.settings.testutils.FakeFeatureFactory;
@@ -50,6 +49,8 @@
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
+import androidx.preference.Preference;
+
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {SettingsShadowResources.SettingsShadowTheme.class, ShadowFragment.class})
public class BackgroundActivityPreferenceControllerTest {
@@ -89,6 +90,7 @@
mShadowContext = RuntimeEnvironment.application;
FakeFeatureFactory.setupForTest();
+ when(mContext.getApplicationContext()).thenReturn(mContext);
when(mContext.getPackageManager()).thenReturn(mPackageManager);
when(mContext.getSystemService(Context.APP_OPS_SERVICE)).thenReturn(mAppOpsManager);
when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
@@ -118,7 +120,7 @@
@Test
public void testHandlePreferenceTreeClick_restrictApp_showDialog() {
doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
- .checkOpNoThrow(anyInt(), anyInt(), anyString());
+ .checkOpNoThrow(anyInt(), anyInt(), anyString());
mController.handlePreferenceTreeClick(mPreference);
@@ -128,7 +130,7 @@
@Test
public void testHandlePreferenceTreeClick_unRestrictApp_showDialog() {
doReturn(AppOpsManager.MODE_IGNORED).when(mAppOpsManager)
- .checkOpNoThrow(anyInt(), anyInt(), anyString());
+ .checkOpNoThrow(anyInt(), anyInt(), anyString());
mController.handlePreferenceTreeClick(mPreference);
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BatteryHistoryPreferenceTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BatteryHistoryPreferenceTest.java
index 0da118a..d9e5bc0 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/BatteryHistoryPreferenceTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/BatteryHistoryPreferenceTest.java
@@ -23,15 +23,14 @@
import static org.mockito.Mockito.when;
import android.content.Context;
-import androidx.preference.PreferenceViewHolder;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.android.settings.R;
-import com.android.settings.graph.UsageView;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.SettingsShadowResources;
+import com.android.settings.widget.UsageView;
import org.junit.Before;
import org.junit.Test;
@@ -41,6 +40,8 @@
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
+import androidx.preference.PreferenceViewHolder;
+
@RunWith(SettingsRobolectricTestRunner.class)
@Config(shadows = SettingsShadowResources.SettingsShadowTheme.class)
public class BatteryHistoryPreferenceTest {
@@ -63,7 +64,7 @@
MockitoAnnotations.initMocks(this);
final Context context = RuntimeEnvironment.application;
final View itemView =
- LayoutInflater.from(context).inflate(R.layout.battery_usage_graph, null);
+ LayoutInflater.from(context).inflate(R.layout.battery_usage_graph, null);
mBatteryHistoryPreference = new BatteryHistoryPreference(context, null);
mBatteryHistoryPreference.mBatteryInfo = mBatteryInfo;
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BatteryInfoTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BatteryInfoTest.java
index 99967f7..44486f8 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/BatteryInfoTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/BatteryInfoTest.java
@@ -36,12 +36,11 @@
import android.os.SystemClock;
import android.util.SparseIntArray;
-import com.android.settings.graph.UsageView;
import com.android.settings.testutils.BatteryTestUtils;
import com.android.settings.testutils.FakeFeatureFactory;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settings.widget.UsageView;
import com.android.settingslib.R;
-import com.android.settingslib.utils.PowerUtil;
import org.junit.Before;
import org.junit.Test;
@@ -172,7 +171,8 @@
}
@Test
- public void testGetBatteryInfo_basedOnUsageTrueBetweenSevenAndFifteenMinutes_usesCorrectString() {
+ public void
+ testGetBatteryInfo_basedOnUsageTrueBetweenSevenAndFifteenMinutes_usesCorrectString() {
Estimate estimate = new Estimate(Duration.ofMinutes(10).toMillis(),
true /* isBasedOnUsage */,
1000 /* averageDischargeTime */);
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceControllerTest.java
index 9457f09..e1cf196 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/batterysaver/AutoBatterySeekBarPreferenceControllerTest.java
@@ -18,6 +18,7 @@
import static com.google.common.truth.Truth.assertThat;
import androidx.lifecycle.LifecycleOwner;
+
import android.content.Context;
import android.provider.Settings;
@@ -39,6 +40,7 @@
private static final int TRIGGER_LEVEL = 20;
private static final int DEFAULT_LEVEL = 15;
+ private static final int INTERVAL = 5;
private AutoBatterySeekBarPreferenceController mController;
private Context mContext;
@@ -85,15 +87,16 @@
assertThat(mPreference.isVisible()).isTrue();
assertThat(mPreference.getTitle()).isEqualTo("At 20%");
- assertThat(mPreference.getProgress()).isEqualTo(TRIGGER_LEVEL);
+ assertThat(mPreference.getProgress()).isEqualTo(TRIGGER_LEVEL / INTERVAL);
}
+
@Test
public void testOnPreferenceChange_updateValue() {
Settings.Global.putInt(mContext.getContentResolver(),
Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0);
- mController.onPreferenceChange(mPreference, TRIGGER_LEVEL);
+ mController.onPreferenceChange(mPreference, TRIGGER_LEVEL / INTERVAL);
assertThat(Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0)).isEqualTo(TRIGGER_LEVEL);
@@ -106,7 +109,7 @@
mController.updateState(mPreference);
- assertThat(mPreference.getMax()).isEqualTo(50);
+ assertThat(mPreference.getMax()).isEqualTo(50 / INTERVAL);
}
@Test
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobServiceTest.java b/tests/robotests/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobServiceTest.java
index b55bf6b..adee433 100644
--- a/tests/robotests/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobServiceTest.java
+++ b/tests/robotests/src/com/android/settings/fuelgauge/batterytip/AnomalyDetectionJobServiceTest.java
@@ -178,7 +178,7 @@
verify(mFeatureFactory.metricsFeatureProvider).action(mContext,
MetricsProto.MetricsEvent.ACTION_ANOMALY_IGNORED,
SYSTEM_PACKAGE,
- Pair.create(MetricsProto.MetricsEvent.FIELD_CONTEXT, ANOMALY_TYPE),
+ Pair.create(MetricsProto.MetricsEvent.FIELD_ANOMALY_TYPE, ANOMALY_TYPE),
Pair.create(MetricsProto.MetricsEvent.FIELD_APP_VERSION_CODE, VERSION_CODE));
}
diff --git a/tests/robotests/src/com/android/settings/gestures/PreventRingingParentPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/gestures/PreventRingingParentPreferenceControllerTest.java
index 33a00fa..bffc847 100644
--- a/tests/robotests/src/com/android/settings/gestures/PreventRingingParentPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/gestures/PreventRingingParentPreferenceControllerTest.java
@@ -16,14 +16,25 @@
package com.android.settings.gestures;
+import static android.provider.Settings.Secure.VOLUME_HUSH_GESTURE;
+import static android.provider.Settings.Secure.VOLUME_HUSH_MUTE;
+import static android.provider.Settings.Secure.VOLUME_HUSH_OFF;
+import static android.provider.Settings.Secure.VOLUME_HUSH_VIBRATE;
+
import static com.android.settings.core.BasePreferenceController.AVAILABLE_UNSEARCHABLE;
+
import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.content.res.Resources;
+import android.provider.Settings;
+import com.android.settings.R;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import org.junit.Before;
@@ -41,18 +52,20 @@
private Context mContext;
private PreventRingingParentPreferenceController mController;
+ private final String VIBRATE_SUMMARY = "On (vibrate)";
+ private final String MUTE_SUMMARY = "On (mute)";
+ private final String NONE_SUMMARY = "Off";
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
- mContext = spy(RuntimeEnvironment.application);
- when(mContext.getResources()).thenReturn(mResources);
-
+ mContext = spy(RuntimeEnvironment.application.getApplicationContext());
mController = new PreventRingingParentPreferenceController(mContext, "test_key");
}
@Test
public void testIsAvailable_configIsTrue_shouldAvailableUnSearchable() {
+ when(mContext.getResources()).thenReturn(mResources);
when(mResources.getBoolean(
com.android.internal.R.bool.config_volumeHushGestureEnabled)).thenReturn(true);
@@ -61,9 +74,28 @@
@Test
public void testIsAvailable_configIsFalse_shouldReturnFalse() {
+ when(mContext.getResources()).thenReturn(mResources);
when(mResources.getBoolean(
com.android.internal.R.bool.config_volumeHushGestureEnabled)).thenReturn(false);
assertThat(mController.isAvailable()).isFalse();
}
+
+ @Test
+ public void updateState_summaryUpdated() {
+ Settings.Secure.putInt(mContext.getContentResolver(), VOLUME_HUSH_GESTURE,
+ VOLUME_HUSH_MUTE);
+ assertThat(mController.getSummary()).isEqualTo(mContext.getResources().getText(
+ R.string.prevent_ringing_option_mute_summary));
+
+ Settings.Secure.putInt(mContext.getContentResolver(), VOLUME_HUSH_GESTURE,
+ VOLUME_HUSH_VIBRATE);
+ assertThat(mController.getSummary()).isEqualTo(mContext.getResources().getText(
+ R.string.prevent_ringing_option_vibrate_summary));
+
+ Settings.Secure.putInt(mContext.getContentResolver(), VOLUME_HUSH_GESTURE,
+ VOLUME_HUSH_OFF);
+ assertThat(mController.getSummary()).isEqualTo(mContext.getResources().getText(
+ R.string.prevent_ringing_option_none_summary));
+ }
}
diff --git a/tests/robotests/src/com/android/settings/gestures/PreventRingingPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/gestures/PreventRingingPreferenceControllerTest.java
index 833a09d..514bb58 100644
--- a/tests/robotests/src/com/android/settings/gestures/PreventRingingPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/gestures/PreventRingingPreferenceControllerTest.java
@@ -88,29 +88,6 @@
}
@Test
- public void testGetSummary_mute() {
- Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.VOLUME_HUSH_GESTURE,
- Settings.Secure.VOLUME_HUSH_MUTE);
- assertEquals(mContext.getString(R.string.prevent_ringing_option_mute_summary),
- mController.getSummary());
- }
-
- @Test
- public void testGetSummary_vibrate() {
- Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.VOLUME_HUSH_GESTURE,
- Settings.Secure.VOLUME_HUSH_VIBRATE);
- assertEquals(mContext.getString(R.string.prevent_ringing_option_vibrate_summary),
- mController.getSummary());
- }
- @Test
- public void testGetSummary_other() {
- Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.VOLUME_HUSH_GESTURE,
- 7);
- assertEquals(mContext.getString(R.string.prevent_ringing_option_none_summary),
- mController.getSummary());
- }
-
- @Test
public void testUpdateState_mute() {
ListPreference pref = mock(ListPreference.class);
Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.VOLUME_HUSH_GESTURE,
diff --git a/tests/robotests/src/com/android/settings/location/LocationServicePreferenceControllerTest.java b/tests/robotests/src/com/android/settings/location/LocationServicePreferenceControllerTest.java
index f3958f4..a6059a9 100644
--- a/tests/robotests/src/com/android/settings/location/LocationServicePreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/location/LocationServicePreferenceControllerTest.java
@@ -16,6 +16,7 @@
package com.android.settings.location;
import static com.google.common.truth.Truth.assertThat;
+
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
@@ -25,24 +26,17 @@
import static org.mockito.Mockito.when;
import android.app.admin.DevicePolicyManager;
-import androidx.lifecycle.LifecycleOwner;
import android.content.ComponentName;
import android.content.Context;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
-import androidx.preference.Preference;
-import androidx.preference.PreferenceCategory;
-import androidx.preference.PreferenceScreen;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settings.widget.RestrictedAppPreference;
import com.android.settingslib.core.lifecycle.Lifecycle;
-import java.util.ArrayList;
-import java.util.List;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -52,6 +46,14 @@
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
+import java.util.ArrayList;
+import java.util.List;
+
+import androidx.lifecycle.LifecycleOwner;
+import androidx.preference.Preference;
+import androidx.preference.PreferenceCategory;
+import androidx.preference.PreferenceScreen;
+
@RunWith(SettingsRobolectricTestRunner.class)
@Config(
shadows = {
@@ -133,6 +135,8 @@
doReturn(preferences)
.when(mSettingsInjector).getInjectedSettings(any(Context.class), anyInt());
when(mFragment.getPreferenceManager().getContext()).thenReturn(mContext);
+ ShadowUserManager.getShadow().setProfileIdsWithDisabled(new int[]{UserHandle.myUserId()});
+
mController.displayPreference(mScreen);
mController.updateState(mCategory);
@@ -143,6 +147,50 @@
}
@Test
+ public void workProfileDisallowShareLocationOn_getParentUserLocationServicesOnly() {
+ final int fakeWorkProfileId = 123;
+ ShadowUserManager.getShadow().setProfileIdsWithDisabled(
+ new int[]{UserHandle.myUserId(), fakeWorkProfileId});
+
+ // Mock RestrictedLockUtils.checkIfRestrictionEnforced and let it return non-null.
+ final List<UserManager.EnforcingUser> enforcingUsers = new ArrayList<>();
+ enforcingUsers.add(new UserManager.EnforcingUser(fakeWorkProfileId,
+ UserManager.RESTRICTION_SOURCE_DEVICE_OWNER));
+ final ComponentName componentName = new ComponentName("test", "test");
+ // Ensure that RestrictedLockUtils.checkIfRestrictionEnforced doesn't return null.
+ ShadowUserManager.getShadow().setUserRestrictionSources(
+ UserManager.DISALLOW_SHARE_LOCATION,
+ UserHandle.of(fakeWorkProfileId),
+ enforcingUsers);
+ when(mDevicePolicyManager.getDeviceOwnerComponentOnAnyUser()).thenReturn(componentName);
+
+ mController.displayPreference(mScreen);
+ mController.updateState(mCategory);
+ verify(mSettingsInjector).getInjectedSettings(
+ any(Context.class), eq(UserHandle.myUserId()));
+ }
+
+ @Test
+ public void workProfileDisallowShareLocationOff_getAllUserLocationServices() {
+ final int fakeWorkProfileId = 123;
+ ShadowUserManager.getShadow().setProfileIdsWithDisabled(
+ new int[]{UserHandle.myUserId(), fakeWorkProfileId});
+
+ // Mock RestrictedLockUtils.checkIfRestrictionEnforced and let it return null.
+ // Empty enforcing users.
+ final List<UserManager.EnforcingUser> enforcingUsers = new ArrayList<>();
+ ShadowUserManager.getShadow().setUserRestrictionSources(
+ UserManager.DISALLOW_SHARE_LOCATION,
+ UserHandle.of(fakeWorkProfileId),
+ enforcingUsers);
+
+ mController.displayPreference(mScreen);
+ mController.updateState(mCategory);
+ verify(mSettingsInjector).getInjectedSettings(
+ any(Context.class), eq(UserHandle.USER_CURRENT));
+ }
+
+ @Test
public void onLocationModeChanged_shouldRequestReloadInjectedSettigns() {
mController.onLocationModeChanged(Settings.Secure.LOCATION_MODE_BATTERY_SAVING, false);
@@ -158,8 +206,9 @@
preferences.add(pref);
doReturn(preferences).when(mSettingsInjector)
.getInjectedSettings(any(Context.class), anyInt());
+ ShadowUserManager.getShadow().setProfileIdsWithDisabled(new int[]{UserHandle.myUserId()});
- int userId = UserHandle.myUserId();
+ final int userId = UserHandle.myUserId();
List<UserManager.EnforcingUser> enforcingUsers = new ArrayList<>();
enforcingUsers.add(new UserManager.EnforcingUser(userId,
UserManager.RESTRICTION_SOURCE_DEVICE_OWNER));
diff --git a/tests/robotests/src/com/android/settings/nfc/NfcAirplaneModeObserverTest.java b/tests/robotests/src/com/android/settings/nfc/NfcAirplaneModeObserverTest.java
index 5efa94a..c5e38a6 100644
--- a/tests/robotests/src/com/android/settings/nfc/NfcAirplaneModeObserverTest.java
+++ b/tests/robotests/src/com/android/settings/nfc/NfcAirplaneModeObserverTest.java
@@ -18,11 +18,12 @@
import static com.google.common.truth.Truth.assertThat;
+import android.content.ContentResolver;
import android.content.Context;
import android.nfc.NfcAdapter;
import android.provider.Settings;
-import androidx.preference.Preference;
+import android.provider.Settings.Global;
import androidx.preference.SwitchPreference;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
@@ -52,8 +53,8 @@
mNfcPreference = new SwitchPreference(RuntimeEnvironment.application);
- mNfcAirplaneModeObserver = new NfcAirplaneModeObserver(mContext, mNfcAdapter,
- (Preference) mNfcPreference);
+ mNfcAirplaneModeObserver =
+ new NfcAirplaneModeObserver(mContext, mNfcAdapter, mNfcPreference);
}
@Test
@@ -67,20 +68,51 @@
NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
assertThat(mNfcAdapter.isEnabled()).isFalse();
+ }
+
+ @Test
+ public void NfcAirplaneModeObserver_airplaneModeOnNfcToggleable_shouldEnablePreference() {
+ ReflectionHelpers.setField(mNfcAirplaneModeObserver, "mAirplaneMode", 0);
+ final ContentResolver contentResolver = mContext.getContentResolver();
+ Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
+ Settings.Global.putString(contentResolver,
+ Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Settings.Global.RADIO_NFC);
+
+ mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
+
+ assertThat(mNfcPreference.isEnabled()).isTrue();
+ }
+
+ @Test
+ public void NfcAirplaneModeObserver_airplaneModeOnNfcNotToggleable_shouldDisablePreference() {
+ ReflectionHelpers.setField(mNfcAirplaneModeObserver, "mAirplaneMode", 0);
+ final ContentResolver contentResolver = mContext.getContentResolver();
+ Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
+ Settings.Global.putString(contentResolver,
+ Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Global.RADIO_WIFI);
+
+ mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
+
assertThat(mNfcPreference.isEnabled()).isFalse();
}
@Test
- public void NfcAirplaneModeObserver_airplaneOff_shouldEnableNfc() {
- ReflectionHelpers.setField(mNfcAirplaneModeObserver,
- "mAirplaneMode", 1);
- Settings.Global.putInt(mContext.getContentResolver(),
- Settings.Global.AIRPLANE_MODE_ON, 0);
+ public void NfcAirplaneModeObserver_airplaneModeOff_shouldEnablePreference() {
+ ReflectionHelpers.setField(mNfcAirplaneModeObserver, "mAirplaneMode", 1);
+ Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0);
- mNfcAirplaneModeObserver.onChange(false,
- NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
+ mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
- assertThat(mNfcAdapter.isEnabled()).isTrue();
assertThat(mNfcPreference.isEnabled()).isTrue();
}
+
+ @Test
+ public void NfcAirplaneModeObserver_airplaneModeOff_shouldNotEnableNfcAutomatically() {
+ ReflectionHelpers.setField(mNfcAirplaneModeObserver, "mAirplaneMode", 1);
+ Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0);
+
+ mNfcAirplaneModeObserver.onChange(false, NfcAirplaneModeObserver.AIRPLANE_MODE_URI);
+
+ assertThat(mNfcAdapter.isEnabled()).isFalse();
+ }
}
diff --git a/tests/robotests/src/com/android/settings/nfc/NfcEnablerTest.java b/tests/robotests/src/com/android/settings/nfc/NfcEnablerTest.java
new file mode 100644
index 0000000..a10c27a
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/nfc/NfcEnablerTest.java
@@ -0,0 +1,106 @@
+/*
+ * 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.nfc;
+
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+
+import android.content.ContentResolver;
+import android.content.Context;
+import android.nfc.NfcAdapter;
+import android.provider.Settings;
+import androidx.preference.SwitchPreference;
+
+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;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+public class NfcEnablerTest {
+
+ @Mock
+ private SwitchPreference mNfcPreference;
+
+ private Context mContext;
+ private NfcEnabler mNfcEnabler;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+ mContext = RuntimeEnvironment.application;
+ mNfcEnabler = spy(new NfcEnabler(mContext, mNfcPreference));
+ }
+
+ @Test
+ public void isToggleable_AirplaneModeOff_shouldReturnTrue() {
+ final ContentResolver contentResolver = mContext.getContentResolver();
+ Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 0);
+ Settings.Global.putString(contentResolver,
+ Settings.Global.AIRPLANE_MODE_RADIOS, Settings.Global.RADIO_NFC);
+ Settings.Global.putString(contentResolver,
+ Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Settings.Global.RADIO_NFC);
+
+ assertThat(mNfcEnabler.isToggleable()).isTrue();
+ }
+
+ @Test
+ public void isToggleable_AirplaneModeOnNfcNotInAirplaneModeRadio_shouldReturnTrue() {
+ final ContentResolver contentResolver = mContext.getContentResolver();
+ Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
+ Settings.Global.putString(contentResolver, Settings.Global.AIRPLANE_MODE_RADIOS, "");
+
+ assertThat(mNfcEnabler.isToggleable()).isTrue();
+ }
+
+ @Test
+ public void isToggleable_AirplaneModeOnNfcToggleable_shouldReturnTrue() {
+ final ContentResolver contentResolver = mContext.getContentResolver();
+ Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
+ Settings.Global.putString(contentResolver,
+ Settings.Global.AIRPLANE_MODE_RADIOS, Settings.Global.RADIO_NFC);
+ Settings.Global.putString(contentResolver,
+ Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Settings.Global.RADIO_NFC);
+
+ assertThat(mNfcEnabler.isToggleable()).isTrue();
+ }
+
+ @Test
+ public void isToggleable_AirplaneModeOnNfcNotToggleable_shouldReturnFalse() {
+ final ContentResolver contentResolver = mContext.getContentResolver();
+ Settings.Global.putInt(contentResolver, Settings.Global.AIRPLANE_MODE_ON, 1);
+ Settings.Global.putString(contentResolver,
+ Settings.Global.AIRPLANE_MODE_RADIOS, Settings.Global.RADIO_NFC);
+ Settings.Global.putString(contentResolver,
+ Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, "");
+
+ assertThat(mNfcEnabler.isToggleable()).isFalse();
+ }
+
+ @Test
+ public void handleNfcStateChanged_stateOff_shouldCheckIfPreferenceEnableState() {
+ mNfcEnabler.handleNfcStateChanged(NfcAdapter.STATE_OFF);
+
+ verify(mNfcEnabler).isToggleable();
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/nfc/NfcPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/nfc/NfcPreferenceControllerTest.java
index eaf6425..758f72c 100644
--- a/tests/robotests/src/com/android/settings/nfc/NfcPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/nfc/NfcPreferenceControllerTest.java
@@ -75,15 +75,6 @@
mNfcPreference = new SwitchPreference(RuntimeEnvironment.application);
when(mScreen.findPreference(mNfcController.getPreferenceKey())).thenReturn(mNfcPreference);
-
- Settings.Global.putString(mContext.getContentResolver(),
- Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS,
- Settings.Global.RADIO_NFC);
-
- Settings.Global.putInt(mContext.getContentResolver(),
- Settings.Global.AIRPLANE_MODE_ON,
- 0);
- mNfcController.displayPreference(mScreen);
}
@Test
@@ -102,6 +93,7 @@
@Test
public void isNfcEnable_nfcStateNotTurning_shouldReturnTrue() {
+ mNfcController.displayPreference(mScreen);
when(mNfcAdapter.getAdapterState()).thenReturn(NfcAdapter.STATE_ON);
mNfcController.onResume();
assertThat(mNfcPreference.isEnabled()).isTrue();
@@ -113,6 +105,7 @@
@Test
public void isNfcEnable_nfcStateTurning_shouldReturnFalse() {
+ mNfcController.displayPreference(mScreen);
when(mNfcAdapter.getAdapterState()).thenReturn(NfcAdapter.STATE_TURNING_ON);
mNfcController.onResume();
assertThat(mNfcPreference.isEnabled()).isFalse();
@@ -124,6 +117,7 @@
@Test
public void isNfcChecked_nfcStateOn_shouldReturnTrue() {
+ mNfcController.displayPreference(mScreen);
when(mNfcAdapter.getAdapterState()).thenReturn(NfcAdapter.STATE_ON);
mNfcController.onResume();
assertThat(mNfcPreference.isChecked()).isTrue();
@@ -205,4 +199,52 @@
assertThat(NfcPreferenceController.isToggleableInAirplaneMode(mContext)).isFalse();
}
+
+ @Test
+ public void shouldTurnOffNFCInAirplaneMode_airplaneModeRadiosContainsNfc_shouldReturnTrue() {
+ Settings.Global.putString(mContext.getContentResolver(),
+ Settings.Global.AIRPLANE_MODE_RADIOS, Settings.Global.RADIO_NFC);
+
+ assertThat(NfcPreferenceController.shouldTurnOffNFCInAirplaneMode(mContext)).isTrue();
+ }
+
+ @Test
+ public void shouldTurnOffNFCInAirplaneMode_airplaneModeRadiosWithoutNfc_shouldReturnFalse() {
+ Settings.Global.putString(mContext.getContentResolver(),
+ Settings.Global.AIRPLANE_MODE_RADIOS, "");
+
+ assertThat(NfcPreferenceController.shouldTurnOffNFCInAirplaneMode(mContext)).isFalse();
+ }
+
+ @Test
+ public void displayPreference_airplaneModeRadiosContainsNfc_shouldCreateAirplaneModeObserver() {
+ Settings.Global.putString(mContext.getContentResolver(),
+ Settings.Global.AIRPLANE_MODE_RADIOS, Settings.Global.RADIO_NFC);
+
+ mNfcController.displayPreference(mScreen);
+
+ assertThat(mNfcController.mAirplaneModeObserver).isNotNull();
+ }
+
+ @Test
+ public void displayPreference_nfcToggleableInAirplaneMode_shouldCreateAirplaneModeObserver() {
+ Settings.Global.putString(mContext.getContentResolver(),
+ Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, Settings.Global.RADIO_NFC);
+
+ mNfcController.displayPreference(mScreen);
+
+ assertThat(mNfcController.mAirplaneModeObserver).isNotNull();
+ }
+
+ @Test
+ public void displayPreference_nfcNotAffectByAirplaneMode_shouldNotCreateAirplaneModeObserver() {
+ Settings.Global.putString(mContext.getContentResolver(),
+ Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS, "");
+ Settings.Global.putString(mContext.getContentResolver(),
+ Settings.Global.AIRPLANE_MODE_RADIOS, "");
+
+ mNfcController.displayPreference(mScreen);
+
+ assertThat(mNfcController.mAirplaneModeObserver).isNull();
+ }
}
diff --git a/tests/robotests/src/com/android/settings/notification/BlockPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/notification/BlockPreferenceControllerTest.java
index a13946e..bdc7d69 100644
--- a/tests/robotests/src/com/android/settings/notification/BlockPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/notification/BlockPreferenceControllerTest.java
@@ -138,6 +138,7 @@
public void testIsAvailable_nonSystemApp() {
NotificationBackend.AppRow appRow = new NotificationBackend.AppRow();
appRow.systemApp = false;
+ appRow.lockedChannelId = "not this";
NotificationChannel channel = mock(NotificationChannel.class);
when(channel.getImportance()).thenReturn(IMPORTANCE_HIGH);
mController.onResume(appRow, channel, null, null);
diff --git a/tests/robotests/src/com/android/settings/notification/NotificationPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/notification/NotificationPreferenceControllerTest.java
index 7eeee98..38790b3 100644
--- a/tests/robotests/src/com/android/settings/notification/NotificationPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/notification/NotificationPreferenceControllerTest.java
@@ -262,6 +262,34 @@
}
@Test
+ public void testIsChannelBlockable_notConfigurable() {
+ String sameId = "apples";
+ NotificationBackend.AppRow appRow = new NotificationBackend.AppRow();
+ appRow.systemApp = false;
+ appRow.lockedChannelId = sameId;
+ NotificationChannel channel = mock(NotificationChannel.class);
+ when(channel.getId()).thenReturn(sameId);
+ when(channel.getImportance()).thenReturn(IMPORTANCE_DEFAULT);
+
+ mController.onResume(appRow, channel, null, null);
+ assertFalse(mController.isChannelBlockable());
+ }
+
+ @Test
+ public void testIsChannelBlockable_notConfigurableButBlocked() {
+ String sameId = "apples";
+ NotificationBackend.AppRow appRow = new NotificationBackend.AppRow();
+ appRow.systemApp = false;
+ appRow.lockedChannelId = sameId;
+ NotificationChannel channel = mock(NotificationChannel.class);
+ when(channel.getId()).thenReturn(sameId);
+ when(channel.getImportance()).thenReturn(IMPORTANCE_NONE);
+
+ mController.onResume(appRow, channel, null, null);
+ assertTrue(mController.isChannelBlockable());
+ }
+
+ @Test
public void testIsChannelGroupBlockable_nonSystemBlockable() {
NotificationBackend.AppRow appRow = new NotificationBackend.AppRow();
appRow.systemApp = false;
diff --git a/tests/robotests/src/com/android/settings/password/ChooseLockGenericTest.java b/tests/robotests/src/com/android/settings/password/ChooseLockGenericTest.java
new file mode 100644
index 0000000..c66373b
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/password/ChooseLockGenericTest.java
@@ -0,0 +1,42 @@
+/*
+ * 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.password;
+
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.spy;
+
+import android.app.Activity;
+import com.android.settings.password.ChooseLockGeneric.ChooseLockGenericFragment;
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+public class ChooseLockGenericTest {
+
+ @Test
+ public void onActivityResult_nullIntentData_shouldNotCrash() {
+ ChooseLockGenericFragment fragment = spy(new ChooseLockGenericFragment());
+ doNothing().when(fragment).updatePreferencesOrFinish(anyBoolean());
+
+ fragment.onActivityResult(
+ fragment.CONFIRM_EXISTING_REQUEST, Activity.RESULT_OK, null /* data */);
+ // no crash
+ }
+
+}
diff --git a/tests/robotests/src/com/android/settings/sound/AudioOutputSwitchPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/sound/AudioOutputSwitchPreferenceControllerTest.java
index 56a5aa7..ebcf4c1 100644
--- a/tests/robotests/src/com/android/settings/sound/AudioOutputSwitchPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/sound/AudioOutputSwitchPreferenceControllerTest.java
@@ -186,6 +186,8 @@
AudioSwitchPreferenceController controller = new AudioSwitchPreferenceControllerTestable(
mContext, TEST_KEY);
+ controller.onStart();
+ controller.onStop();
assertThat(mLocalBluetoothManager).isNull();
}
@@ -230,6 +232,7 @@
verify(mLocalBluetoothManager.getEventManager()).registerCallback(
any(BluetoothCallback.class));
verify(mContext).registerReceiver(any(BroadcastReceiver.class), any(IntentFilter.class));
+ verify(mLocalBluetoothManager).setForegroundActivity(mContext);
}
@Test
@@ -240,6 +243,7 @@
verify(mLocalBluetoothManager.getEventManager()).unregisterCallback(
any(BluetoothCallback.class));
verify(mContext).unregisterReceiver(any(BroadcastReceiver.class));
+ verify(mLocalBluetoothManager).setForegroundActivity(null);
}
@Test
diff --git a/tests/robotests/src/com/android/settings/testutils/SettingsRobolectricTestRunner.java b/tests/robotests/src/com/android/settings/testutils/SettingsRobolectricTestRunner.java
index f071f17..0b29af5 100644
--- a/tests/robotests/src/com/android/settings/testutils/SettingsRobolectricTestRunner.java
+++ b/tests/robotests/src/com/android/settings/testutils/SettingsRobolectricTestRunner.java
@@ -84,9 +84,9 @@
paths.add(new ResourcePath(null,
Fs.fromURL(new URL("file:frameworks/opt/setupwizard/library/recyclerview/res")), null));
paths.add(new ResourcePath(null,
- Fs.fromURL(new URL("file:frameworks/support/v7/appcompat/res")), null));
+ Fs.fromURL(new URL("file:frameworks/support/appcompat/res")), null));
paths.add(new ResourcePath(null,
- Fs.fromURL(new URL("file:frameworks/support/v7/cardview/res")), null));
+ Fs.fromURL(new URL("file:frameworks/support/cardview/res")), null));
} catch (MalformedURLException e) {
throw new RuntimeException("SettingsRobolectricTestRunner failure", e);
}
diff --git a/tests/robotests/src/com/android/settings/testutils/shadow/ShadowUserManager.java b/tests/robotests/src/com/android/settings/testutils/shadow/ShadowUserManager.java
index d83c814..753d159 100644
--- a/tests/robotests/src/com/android/settings/testutils/shadow/ShadowUserManager.java
+++ b/tests/robotests/src/com/android/settings/testutils/shadow/ShadowUserManager.java
@@ -30,6 +30,7 @@
import org.robolectric.shadow.api.Shadow;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -45,6 +46,9 @@
private final List<UserInfo> mUserProfileInfos = new ArrayList<>();
private final Set<Integer> mManagedProfiles = new HashSet<>();
private boolean mIsQuietModeEnabled = false;
+ private int[] profileIdsForUser;
+ private boolean mUserSwitchEnabled;
+
@Resetter
public void reset() {
@@ -54,6 +58,7 @@
mRestrictionSources.clear();
mManagedProfiles.clear();
mIsQuietModeEnabled = false;
+ mUserSwitchEnabled = false;
}
public void setUserInfo(int userHandle, UserInfo userInfo) {
@@ -96,7 +101,11 @@
@Implementation
public List<EnforcingUser> getUserRestrictionSources(
String restrictionKey, UserHandle userHandle) {
- return mRestrictionSources.get(restrictionKey + userHandle.getIdentifier());
+ // Return empty list when there is no enforcing user, otherwise might trigger
+ // NullPointer Exception in RestrictedLockUtils.checkIfRestrictionEnforced.
+ List<EnforcingUser> enforcingUsers =
+ mRestrictionSources.get(restrictionKey + userHandle.getIdentifier());
+ return enforcingUsers == null ? Collections.emptyList() : enforcingUsers;
}
public void setUserRestrictionSources(
@@ -121,4 +130,22 @@
public void setQuietModeEnabled(boolean enabled) {
mIsQuietModeEnabled = enabled;
}
+
+ @Implementation
+ public int[] getProfileIdsWithDisabled(@UserIdInt int userId) {
+ return profileIdsForUser;
+ }
+
+ public void setProfileIdsWithDisabled(int[] profileIds) {
+ profileIdsForUser = profileIds;
+ }
+
+ @Implementation
+ public boolean isUserSwitcherEnabled() {
+ return mUserSwitchEnabled;
+ }
+
+ public void setUserSwitcherEnabled(boolean userSwitchEnabled) {
+ mUserSwitchEnabled = userSwitchEnabled;
+ }
}
diff --git a/tests/robotests/src/com/android/settings/users/AddUserWhenLockedPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/users/AddUserWhenLockedPreferenceControllerTest.java
index 10b2acb..c2b1c9f 100644
--- a/tests/robotests/src/com/android/settings/users/AddUserWhenLockedPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/users/AddUserWhenLockedPreferenceControllerTest.java
@@ -17,58 +17,59 @@
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Answers.RETURNS_DEEP_STUBS;
-import static org.mockito.Matchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import androidx.lifecycle.LifecycleOwner;
import android.content.Context;
import android.content.pm.UserInfo;
-import android.os.UserManager;
import android.provider.Settings.Global;
-import androidx.preference.PreferenceScreen;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settings.testutils.shadow.ShadowUserManager;
import com.android.settingslib.RestrictedSwitchPreference;
-import com.android.settingslib.core.lifecycle.Lifecycle;
+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.annotation.Config;
import org.robolectric.shadows.ShadowApplication;
+import androidx.preference.PreferenceScreen;
+
@RunWith(SettingsRobolectricTestRunner.class)
+@Config(shadows = {ShadowUserManager.class})
public class AddUserWhenLockedPreferenceControllerTest {
@Mock(answer = RETURNS_DEEP_STUBS)
private PreferenceScreen mScreen;
@Mock(answer = RETURNS_DEEP_STUBS)
private UserInfo mUserInfo;
- @Mock(answer = RETURNS_DEEP_STUBS)
- private UserManager mUserManager;
- private LifecycleOwner mLifecycleOwner;
- private Lifecycle mLifecycle;
private Context mContext;
+ private ShadowUserManager mUserManager;
private AddUserWhenLockedPreferenceController mController;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
ShadowApplication shadowContext = ShadowApplication.getInstance();
- shadowContext.setSystemService(Context.USER_SERVICE, mUserManager);
+ mUserManager = ShadowUserManager.getShadow();
mContext = shadowContext.getApplicationContext();
- mLifecycleOwner = () -> mLifecycle;
- mLifecycle = new Lifecycle(mLifecycleOwner);
- mController = new AddUserWhenLockedPreferenceController(mContext, "fake_key", mLifecycle);
+ mController = new AddUserWhenLockedPreferenceController(mContext, "fake_key");
+ }
+
+ @After
+ public void tearDown() {
+ mUserManager.reset();
}
@Test
public void displayPref_NotAdmin_shouldNotDisplay() {
- when(mUserManager.getUserInfo(anyInt())).thenReturn(mUserInfo);
+ mUserManager.setUserInfo(0, mUserInfo);
when(mUserInfo.isAdmin()).thenReturn(false);
final RestrictedSwitchPreference preference = mock(RestrictedSwitchPreference.class);
when(preference.getKey()).thenReturn(mController.getPreferenceKey());
diff --git a/tests/robotests/src/com/android/settings/users/MultiUserFooterPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/users/MultiUserFooterPreferenceControllerTest.java
new file mode 100644
index 0000000..f74de7a
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/users/MultiUserFooterPreferenceControllerTest.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.users;
+
+import static com.android.settings.core.BasePreferenceController.AVAILABLE_UNSEARCHABLE;
+import static com.android.settings.core.BasePreferenceController.DISABLED_FOR_USER;
+import static com.google.common.truth.Truth.assertThat;
+
+import android.content.Context;
+
+import com.android.settings.testutils.SettingsRobolectricTestRunner;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.robolectric.RuntimeEnvironment;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+public class MultiUserFooterPreferenceControllerTest {
+
+ private Context mContext;
+ private MultiUserFooterPreferenceController mController;
+
+ @Before
+ public void setUp() {
+ mContext = RuntimeEnvironment.application;
+ mController = new MultiUserFooterPreferenceController(mContext);
+ }
+
+ @Test
+ public void getAvailabilityStatus_multiUserOff_shouldReturnEnabled() {
+ mController.mUserCaps.mEnabled = true;
+ mController.mUserCaps.mUserSwitcherEnabled = false;
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(AVAILABLE_UNSEARCHABLE);
+ }
+
+ @Test
+ public void getAvailabilityStatus_multiUserOn_shouldReturnDisabled() {
+ mController.mUserCaps.mEnabled = true;
+ mController.mUserCaps.mUserSwitcherEnabled = true;
+
+ assertThat(mController.getAvailabilityStatus()).isEqualTo(DISABLED_FOR_USER);
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/users/UserCapabilitiesTest.java b/tests/robotests/src/com/android/settings/users/UserCapabilitiesTest.java
index d85f2fa..c8d3685 100644
--- a/tests/robotests/src/com/android/settings/users/UserCapabilitiesTest.java
+++ b/tests/robotests/src/com/android/settings/users/UserCapabilitiesTest.java
@@ -17,36 +17,43 @@
package com.android.settings.users;
import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.when;
import android.content.Context;
+import android.os.UserHandle;
import android.os.UserManager;
import com.android.settings.testutils.SettingsRobolectricTestRunner;
+import com.android.settings.testutils.shadow.ShadowUserManager;
+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(shadows = {ShadowUserManager.class})
public class UserCapabilitiesTest {
- @Mock
private Context mContext;
- @Mock
- private UserManager mUserManager;
+ private ShadowUserManager mUserManager;
@Before
public void setUp() {
- MockitoAnnotations.initMocks(this);
- when(mContext.getSystemService(Context.USER_SERVICE)).thenReturn(mUserManager);
+ mContext = RuntimeEnvironment.application;
+ mUserManager = ShadowUserManager.getShadow();
+ }
+
+ @After
+ public void tearDown() {
+ mUserManager.reset();
}
@Test
- public void disallowUserSwitchWhenRestrictionIsSet() {
- when(mUserManager.hasUserRestriction(UserManager.DISALLOW_USER_SWITCH)).thenReturn(true);
+ public void disallowUserSwitch_restrictionIsSet_true() {
+ mUserManager.setUserRestriction(UserHandle.of(UserHandle.myUserId()),
+ UserManager.DISALLOW_USER_SWITCH, true);
UserCapabilities userCapabilities = UserCapabilities.create(mContext);
userCapabilities.updateAddUserCapabilities(mContext);
@@ -55,12 +62,33 @@
}
@Test
- public void allowUserSwitchWhenRestrictionIsNotSet() {
- when(mUserManager.hasUserRestriction(UserManager.DISALLOW_USER_SWITCH)).thenReturn(false);
+ public void disallowUserSwitch_restrictionIsNotSet_false() {
+ mUserManager.setUserRestriction(UserHandle.of(UserHandle.myUserId()),
+ UserManager.DISALLOW_USER_SWITCH, false);
UserCapabilities userCapabilities = UserCapabilities.create(mContext);
userCapabilities.updateAddUserCapabilities(mContext);
assertThat(userCapabilities.mDisallowSwitchUser).isFalse();
}
+
+ @Test
+ public void userSwitchEnabled_off() {
+ mUserManager.setUserSwitcherEnabled(false);
+
+ final UserCapabilities userCapabilities = UserCapabilities.create(mContext);
+ userCapabilities.updateAddUserCapabilities(mContext);
+
+ assertThat(userCapabilities.mUserSwitcherEnabled).isFalse();
+ }
+
+ @Test
+ public void userSwitchEnabled_on() {
+ mUserManager.setUserSwitcherEnabled(true);
+
+ final UserCapabilities userCapabilities = UserCapabilities.create(mContext);
+ userCapabilities.updateAddUserCapabilities(mContext);
+
+ assertThat(userCapabilities.mUserSwitcherEnabled).isTrue();
+ }
}
diff --git a/tests/robotests/src/com/android/settings/graph/BottomLabelLayoutTest.java b/tests/robotests/src/com/android/settings/widget/BottomLabelLayoutTest.java
similarity index 97%
rename from tests/robotests/src/com/android/settings/graph/BottomLabelLayoutTest.java
rename to tests/robotests/src/com/android/settings/widget/BottomLabelLayoutTest.java
index 6ba22d1..ea0d89a 100644
--- a/tests/robotests/src/com/android/settings/graph/BottomLabelLayoutTest.java
+++ b/tests/robotests/src/com/android/settings/widget/BottomLabelLayoutTest.java
@@ -1,5 +1,6 @@
/*
* 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
@@ -11,11 +12,9 @@
* 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.graph;
+package com.android.settings.widget;
import static com.google.common.truth.Truth.assertThat;
diff --git a/tests/robotests/src/com/android/settings/graph/UsageGraphTest.java b/tests/robotests/src/com/android/settings/widget/UsageGraphTest.java
similarity index 99%
rename from tests/robotests/src/com/android/settings/graph/UsageGraphTest.java
rename to tests/robotests/src/com/android/settings/widget/UsageGraphTest.java
index 788d130..15658d5 100644
--- a/tests/robotests/src/com/android/settings/graph/UsageGraphTest.java
+++ b/tests/robotests/src/com/android/settings/widget/UsageGraphTest.java
@@ -1,5 +1,6 @@
/*
* 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
@@ -11,11 +12,9 @@
* 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.graph;
+package com.android.settings.widget;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.doReturn;
diff --git a/tests/robotests/src/com/android/settings/wifi/WifiUtilsTest.java b/tests/robotests/src/com/android/settings/wifi/WifiUtilsTest.java
index 1f49654..806399d 100644
--- a/tests/robotests/src/com/android/settings/wifi/WifiUtilsTest.java
+++ b/tests/robotests/src/com/android/settings/wifi/WifiUtilsTest.java
@@ -29,7 +29,7 @@
@Test
public void testSSID() {
assertThat(WifiUtils.isSSIDTooLong("123")).isFalse();
- assertThat(WifiUtils.isSSIDTooLong("☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎")).isTrue();
+ assertThat(WifiUtils.isSSIDTooLong("☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎☎")).isTrue();
assertThat(WifiUtils.isSSIDTooShort("123")).isFalse();
assertThat(WifiUtils.isSSIDTooShort("")).isTrue();
diff --git a/tests/uitests/src/com/android/settings/ui/inputmethods/DataSaverSummaryUITest.java b/tests/uitests/src/com/android/settings/ui/inputmethods/DataSaverSummaryUITest.java
index f6f5d43..45f757c 100644
--- a/tests/uitests/src/com/android/settings/ui/inputmethods/DataSaverSummaryUITest.java
+++ b/tests/uitests/src/com/android/settings/ui/inputmethods/DataSaverSummaryUITest.java
@@ -44,7 +44,7 @@
mInstrumentation = InstrumentationRegistry.getInstrumentation();
mUiDevice = UiDevice.getInstance(mInstrumentation);
mIntent = new Intent().setClassName("com.android.settings",
- "com.android.settings.Settings$DataUsageSummaryLegacyActivity")
+ "com.android.settings.Settings$DataUsageSummaryActivity")
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}