Merge "Update Network & internet->Wi-Fi to use MasterSwitchPreference."
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 05e95f0..0de7a4e 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -2700,6 +2700,22 @@
android:value="com.android.settings.notification.AppNotificationSettings" />
</activity>
+ <!-- Show channel-level notification settings (channel passed in as extras) -->
+ <activity android:name="Settings$ChannelNotificationSettingsActivity"
+ android:label="@string/app_notifications_title"
+ android:exported="true">
+ <intent-filter android:priority="1">
+ <action android:name="android.settings.CHANNEL_NOTIFICATION_SETTINGS" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.DEFAULT" />
+ </intent-filter>
+ <meta-data android:name="com.android.settings.FRAGMENT_CLASS"
+ android:value="com.android.settings.notification.ChannelNotificationSettings" />
+ </activity>
+
<!-- Show Manual (from settings item) -->
<activity android:name="ManualDisplayActivity"
android:label="@string/manual"
diff --git a/res/layout/preference_tts_engine.xml b/res/layout/preference_tts_engine.xml
index 8f4036b..19401f0 100644
--- a/res/layout/preference_tts_engine.xml
+++ b/res/layout/preference_tts_engine.xml
@@ -31,17 +31,4 @@
android:maxLines="2"
android:textAppearance="?android:attr/textAppearanceListItem"
android:ellipsize="marquee"/>
-
- <ImageView
- android:id="@+id/tts_engine_settings"
- android:layout_width="wrap_content"
- android:layout_height="match_parent"
- android:paddingStart="?android:attr/listPreferredItemPaddingStart"
- android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
- android:src="@drawable/ic_settings"
- android:contentDescription="@string/tts_engine_settings_button"
- android:layout_centerVertical="true"
- android:clickable="true"
- android:focusable="true"
- android:background="?android:attr/selectableItemBackground"/>
</LinearLayout>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 0e572a6..cc40094 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -752,6 +752,8 @@
<string name="security_passwords_title">Passwords</string>
<!-- Summary for settings preference disabled by administrator [CHAR LIMIT=50] -->
<string name="disabled_by_administrator_summary">Disabled by administrator</string>
+ <!-- In the security screen, the header title for security statuses -->
+ <string name="security_status_title">Security status</string>
<!-- Fingerprint enrollment and settings --><skip />
<!-- Title shown for menu item that launches fingerprint settings or enrollment [CHAR LIMIT=22] -->
@@ -3974,6 +3976,8 @@
<string name="talkback_title">Talkback</string>
<!-- Summary for the Talkback Accessibility Service. Lets the user know that Talkback is a screenreader and that it is usually most helpful to blind and low vision users and whether the service is on. [CHAR_LIMIT=none] -->
<string name="talkback_summary">Screen reader primarily for people with blindness and low vision</string>
+ <!-- Summary for the Select to Speak Accessibility Service. [CHAR_LIMIT=none] -->
+ <string name="select_to_speak_summary">Tap items on your screen to hear them read aloud</string>
<!-- Title for the accessibility preference category of system related preferences. [CHAR LIMIT=25] -->
<string name="accessibility_system_title">System</string>
<!-- Title for the accessibility preference category of display related preferences. [CHAR LIMIT=25] -->
@@ -4624,9 +4628,20 @@
behalf. It comes from the <xliff:g id="voice_input_service_app_name">%s</xliff:g>
application. Enable the use of this service?</string>
- <!-- On main TTS Settings screen, in default settings section, reset speech rate for synthesized voice to 1x speech rate.-->
+ <!-- [CHAR LIMIT=50] The text for the settings section that is used to set a preferred text to speech engine -->
+ <string name="tts_engine_preference_title">Preferred engine</string>
+ <!-- [CHAR LIMIT=50] The text for a settings screen of the currently set text to speech engine -->
+ <string name="tts_engine_settings_title">Engine settings</string>
+ <!-- [CHAR LIMIT=50] The text for a button that goes to the speech rate and pitch settings for text to speech. -->
+ <string name="tts_sliders_title">Speech rate & pitch</string>
+ <!-- [CHAR LIMIT=50] Name for the general text to speech settings section. -->
+ <string name="tts_engine_section_title">Engine</string>
+ <!-- [CHAR LIMIT=50] Name for the button that goes to the voice selection screen. -->
+ <string name="tts_install_voice_title">Voices</string>
+
+ <!-- Reset speech rate for synthesized voice to 1x speech rate in the text to speech settings.-->
<string name="tts_reset_speech_rate_title">Reset speech rate</string>
- <!-- On main TTS Settings screen, summary for reset speech rate for synthesized voice -->
+ <!-- Summary for reset speech rate for synthesized voice in the text to speech settings.-->
<string name="tts_reset_speech_rate_summary">Reset the speed at which the text is spoken to normal.</string>
<!-- Power Control Widget -->
@@ -8150,4 +8165,11 @@
Make <xliff:g id="app_name">%1$s</xliff:g> your autofill app? <xliff:g id="app_name">%1$s</xliff:g> will be able to read your screen and fill fields in other apps.
</string>
+ <!-- Name of setting for switching device theme [CHAR LIMIT=60] -->
+ <string name="device_theme">Device theme</string>
+ <!-- Name of default device theme [CHAR LIMIT=60] -->
+ <string name="default_theme">Default</string>
+ <!-- Temporary reboot string, will be removed -->
+ <string name="change_theme_reboot" translatable="false">Changing the theme requires a restart.</string>
+
</resources>
diff --git a/res/xml/accessibility_settings_for_setup_wizard.xml b/res/xml/accessibility_settings_for_setup_wizard.xml
index c938f24..42b137b 100644
--- a/res/xml/accessibility_settings_for_setup_wizard.xml
+++ b/res/xml/accessibility_settings_for_setup_wizard.xml
@@ -46,6 +46,13 @@
<Preference
android:fragment=
+ "com.android.settings.accessibility.ToggleSelectToSpeakPreferenceFragmentForSetupWizard"
+ android:key="select_to_speak_preference"
+ android:summary="@string/select_to_speak_summary"
+ android:persistent="true" />
+
+ <Preference
+ android:fragment=
"com.android.settings.accessibility.ToggleScreenReaderPreferenceFragmentForSetupWizard"
android:key="screen_reader_preference"
android:summary="@string/talkback_summary"
diff --git a/res/xml/ia_display_settings.xml b/res/xml/ia_display_settings.xml
index 946466b..ed026f1 100644
--- a/res/xml/ia_display_settings.xml
+++ b/res/xml/ia_display_settings.xml
@@ -105,6 +105,11 @@
android:title="@string/tap_to_wake"
android:summary="@string/tap_to_wake_summary" />
+ <ListPreference
+ android:key="theme"
+ android:title="@string/device_theme"
+ android:summary="%s" />
+
<Preference
android:key="wifi_display"
android:title="@string/wifi_display_settings_title"
diff --git a/res/xml/power_usage_summary.xml b/res/xml/power_usage_summary.xml
index 4607c48..b4ac7e2 100644
--- a/res/xml/power_usage_summary.xml
+++ b/res/xml/power_usage_summary.xml
@@ -27,7 +27,8 @@
android:key="power_management"
android:title="@string/battery_power_management">
- <com.android.settings.fuelgauge.BatterySaverPreference
+ <com.android.settings.widget.MasterSwitchPreference
+ android:key="battery_saver"
android:title="@string/battery_saver"
android:fragment="com.android.settings.fuelgauge.BatterySaverSettings"/>
diff --git a/res/xml/security_settings_status.xml b/res/xml/security_settings_status.xml
new file mode 100644
index 0000000..06930f9
--- /dev/null
+++ b/res/xml/security_settings_status.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2017 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
+ android:title="@string/security_settings_title">
+
+ <PreferenceCategory
+ android:key="security_status"
+ android:title="@string/security_status_title"/>
+
+</PreferenceScreen>
diff --git a/res/xml/tts_engine_picker.xml b/res/xml/tts_engine_picker.xml
new file mode 100644
index 0000000..61e3e7e
--- /dev/null
+++ b/res/xml/tts_engine_picker.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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"
+ android:title="@string/tts_settings_title">
+
+ <PreferenceCategory android:key="tts_engine_preference_category"
+ android:title="@string/tts_engine_preference_title"/>
+
+</PreferenceScreen>
diff --git a/res/xml/tts_engine_settings.xml b/res/xml/tts_engine_settings.xml
deleted file mode 100644
index d00c102..0000000
--- a/res/xml/tts_engine_settings.xml
+++ /dev/null
@@ -1,36 +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.
--->
-
-<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:title="">
- <ListPreference
- android:key="tts_default_lang"
- android:title="@string/tts_default_lang_title"
- android:summary="@string/tts_default_lang_summary"
- android:order="100" />
-
- <Preference
- android:key="tts_engine_settings"
- android:persistent="false"
- android:title="@string/tts_engine_settings_title"
- android:order="200" />
-
- <Preference
- android:key="tts_install_data"
- android:persistent="false"
- android:title="@string/tts_install_data_title"
- android:summary="@string/tts_install_data_summary"
- android:order="300" />
-</PreferenceScreen>
diff --git a/res/xml/tts_settings.xml b/res/xml/tts_settings.xml
index 31d2b17..b02a749 100644
--- a/res/xml/tts_settings.xml
+++ b/res/xml/tts_settings.xml
@@ -17,38 +17,40 @@
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/tts_settings_title">
- <!-- The contents of this category are filled in by the Java code
- based on the list of available engines. -->
- <PreferenceCategory android:key="tts_engine_preference_section"
- android:title="@string/tts_engine_preference_section_title" />
+ <PreferenceCategory android:key="tts_engine_section"
+ android:title="@string/tts_engine_section_title">
+
+ <com.android.settingslib.RestrictedPreference android:key="tts_engine_preference"
+ android:title="@string/tts_engine_preference_title"
+ android:fragment="com.android.settings.tts.TtsEnginePreferenceFragment"/>
+
+ <Preference
+ android:key="tts_engine_settings"
+ android:persistent="false"
+ android:title="@string/tts_engine_settings_title"
+ android:order="200" />
+
+ <Preference
+ android:key="tts_install_data"
+ android:persistent="false"
+ android:title="@string/tts_install_voice_title"
+ android:order="300" />
+
+ </PreferenceCategory>
<PreferenceCategory android:key="tts_general_section"
android:title="@string/tts_general_section_title">
- <!-- The max value for seek bars here should be kept in sync
- with the max value specified in TextToSpeechSettings class. -->
- <com.android.settings.SeekBarPreference
- android:key="tts_default_rate"
- android:title="@string/tts_default_rate_title"
- android:summary="@string/tts_default_rate_summary"
- android:defaultValue="50"
- android:max="600"/>
- <com.android.settings.SeekBarPreference
- android:key="tts_default_pitch"
- android:title="@string/tts_default_pitch_title"
- android:summary="@string/tts_default_pitch_summary"
- android:defaultValue="100"
- android:max="400"/>
+ <com.android.settingslib.RestrictedPreference
+ android:key="tts_sliders"
+ android:title="@string/tts_sliders_title"
+ android:fragment="com.android.settings.tts.TtsSlidersFragment"/>
- <Preference android:key="reset_speech_rate"
- android:persistent="false"
- android:title="@string/tts_reset_speech_rate_title"
- android:summary="@string/tts_reset_speech_rate_summary" />
-
- <Preference android:key="reset_speech_pitch"
- android:persistent="false"
- android:title="@string/tts_reset_speech_pitch_title"
- android:summary="@string/tts_reset_speech_pitch_summary" />
+ <ListPreference
+ android:key="tts_default_lang"
+ android:title="@string/tts_default_lang_title"
+ android:summary="@string/tts_default_lang_summary"
+ android:persistent="false" />
<Preference android:key="tts_play_example"
android:persistent="false"
diff --git a/res/xml/tts_sliders.xml b/res/xml/tts_sliders.xml
new file mode 100644
index 0000000..3c767b0
--- /dev/null
+++ b/res/xml/tts_sliders.xml
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2009 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"
+ android:title="@string/tts_settings_title">
+
+ <!-- The max value for seek bars here should be kept in sync
+ with the max value specified in TextToSpeechSettings class. -->
+ <com.android.settings.SeekBarPreference
+ android:key="tts_default_rate"
+ android:title="@string/tts_default_rate_title"
+ android:summary="@string/tts_default_rate_summary"
+ android:defaultValue="50"
+ android:max="600"/>
+
+ <com.android.settings.SeekBarPreference
+ android:key="tts_default_pitch"
+ android:title="@string/tts_default_pitch_title"
+ android:summary="@string/tts_default_pitch_summary"
+ android:defaultValue="100"
+ android:max="400"/>
+
+ <Preference android:key="reset_speech_rate"
+ android:persistent="false"
+ android:title="@string/tts_reset_speech_rate_title"
+ android:summary="@string/tts_reset_speech_rate_summary" />
+
+ <Preference android:key="reset_speech_pitch"
+ android:persistent="false"
+ android:title="@string/tts_reset_speech_pitch_title"
+ android:summary="@string/tts_reset_speech_pitch_summary" />
+
+</PreferenceScreen>
diff --git a/src/com/android/settings/BackupSettingsActivity.java b/src/com/android/settings/BackupSettingsActivity.java
index c0456b2..a4cc4b7 100644
--- a/src/com/android/settings/BackupSettingsActivity.java
+++ b/src/com/android/settings/BackupSettingsActivity.java
@@ -17,13 +17,19 @@
package com.android.settings;
import android.app.Activity;
-import android.content.ComponentName;
+import android.app.backup.BackupManager;
+import android.app.backup.IBackupManager;
+import android.content.Context;
import android.content.Intent;
-import android.content.pm.PackageManager;
import android.os.Bundle;
+import android.os.ServiceManager;
+import android.os.UserHandle;
+import android.text.TextUtils;
import android.util.Log;
-import com.android.settings.Settings.PrivacySettingsActivity;
+import com.android.settings.R;
+
+import java.net.URISyntaxException;
/**
* A trampoline activity used to launch the configured Backup activity.
@@ -36,24 +42,30 @@
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
-
- BackupSettingsHelper backupHelper = new BackupSettingsHelper();
- if (backupHelper.isIntentProvidedByTransport(getPackageManager())) {
- Intent intent = backupHelper.getIntentForBackupSettings();
- if (intent != null) {
- // use startActivityForResult to let the activity check the caller signature
- startActivityForResult(intent, -1);
+ String backup = getResources().getString(R.string.config_backup_settings_intent);
+ if (!TextUtils.isEmpty(backup)) {
+ try {
+ Intent intent = Intent.parseUri(backup, 0);
+ if (intent.resolveActivity(getPackageManager()) != null) {
+ // use startActivityForResult to let the activity check the caller signature
+ IBackupManager bmgr = IBackupManager.Stub.asInterface(
+ ServiceManager.getService(Context.BACKUP_SERVICE));
+ boolean backupOkay;
+ try {
+ backupOkay = bmgr.isBackupServiceActive(UserHandle.myUserId());
+ } catch (Exception e) {
+ // things go wrong talking to the backup system => ignore and
+ // pass the default 'false' as the "backup is a thing?" state.
+ backupOkay = false;
+ }
+ intent.putExtra(BackupManager.EXTRA_BACKUP_SERVICES_AVAILABLE, backupOkay);
+ startActivityForResult(intent, -1);
+ } else {
+ Log.e(TAG, "Backup component not found!");
+ }
+ } catch (URISyntaxException e) {
+ Log.e(TAG, "Invalid backup component URI!", e);
}
- } else {
- // This should never happen, because isIntentProvidedByTransport() is called before
- // starting this activity.
- Log.e(TAG, "Backup transport has not provided an intent"
- + " or the component for the intent is not found!");
- getPackageManager().setComponentEnabledSetting(
- new ComponentName(getPackageName(), PrivacySettingsActivity.class.getName()),
- PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
- PackageManager.DONT_KILL_APP);
- startActivityForResult(new Intent(this, PrivacySettingsActivity.class), -1);
}
finish();
}
diff --git a/src/com/android/settings/BackupSettingsHelper.java b/src/com/android/settings/BackupSettingsHelper.java
deleted file mode 100644
index 37c0971..0000000
--- a/src/com/android/settings/BackupSettingsHelper.java
+++ /dev/null
@@ -1,103 +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;
-
-
-import android.app.backup.BackupManager;
-import android.app.backup.BackupTransport;
-import android.app.backup.IBackupManager;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.os.UserHandle;
-import android.util.Log;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-/**
- * Helper class for {@link BackupSettingsActivity} that interacts with {@link IBackupManager}.
- */
-public class BackupSettingsHelper {
- private static final String TAG = "BackupSettingsHelper";
-
- private IBackupManager mBackupManager = IBackupManager.Stub.asInterface(
- ServiceManager.getService(Context.BACKUP_SERVICE));
-
-
- /**
- * Gets the intent from Backup transport and adds the extra depending on whether the user has
- * rights to see backup settings.
- *
- * @return Intent to launch Backup settings provided by the Backup transport.
- */
- public Intent getIntentForBackupSettings() {
- Intent intent = getIntentFromBackupTransport();
- if (intent != null) {
- intent.putExtra(BackupManager.EXTRA_BACKUP_SERVICES_AVAILABLE, isBackupServiceActive());
- }
- return intent;
- }
-
-
- /**
- * Checks if the transport provided the intent to launch the backup settings and if that
- * intent resolves to an activity.
- */
- public boolean isIntentProvidedByTransport(PackageManager packageManager) {
- Intent intent = getIntentFromBackupTransport();
- return intent != null && intent.resolveActivity(packageManager) != null;
- }
-
- /**
- * Gets an intent to launch the backup settings from the current transport using
- * {@link BackupTransport#dataManagementIntent()} API.
- *
- * @return intent provided by transport or null if no intent was provided.
- */
- private Intent getIntentFromBackupTransport() {
- try {
- Intent intent =
- mBackupManager.getDataManagementIntent(mBackupManager.getCurrentTransport());
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- if (intent != null) {
- Log.d(TAG, "Parsed intent from backup transport: " + intent.toString());
- } else {
- Log.d(TAG, "Received a null intent from backup transport");
- }
- }
- return intent;
- } catch (RemoteException e) {
- Log.e(TAG, "Error getting data management intent", e);
- }
- return null;
- }
-
- /** Checks if backup service is enabled for this user. */
- private boolean isBackupServiceActive() {
- boolean backupOkay;
- try {
- backupOkay = mBackupManager.isBackupServiceActive(UserHandle.myUserId());
- } catch (Exception e) {
- // things go wrong talking to the backup system => ignore and
- // pass the default 'false' as the "backup is a thing?" state.
- backupOkay = false;
- }
- return backupOkay;
- }
-}
diff --git a/src/com/android/settings/DisplaySettings.java b/src/com/android/settings/DisplaySettings.java
index e7b44f6..320cb83 100644
--- a/src/com/android/settings/DisplaySettings.java
+++ b/src/com/android/settings/DisplaySettings.java
@@ -35,6 +35,7 @@
import com.android.settings.display.NightModePreferenceController;
import com.android.settings.display.ScreenSaverPreferenceController;
import com.android.settings.display.TapToWakePreferenceController;
+import com.android.settings.display.ThemePreferenceController;
import com.android.settings.display.TimeoutPreferenceController;
import com.android.settings.display.VrDisplayPreferenceController;
import com.android.settings.display.WallpaperPreferenceController;
@@ -92,6 +93,7 @@
controllers.add(new TimeoutPreferenceController(context));
controllers.add(new VrDisplayPreferenceController(context));
controllers.add(new WallpaperPreferenceController(context));
+ controllers.add(new ThemePreferenceController(context));
return controllers;
}
@@ -177,6 +179,7 @@
new TimeoutPreferenceController(context).updateNonIndexableKeys(result);
new VrDisplayPreferenceController(context).updateNonIndexableKeys(result);
new WallpaperPreferenceController(context).updateNonIndexableKeys(result);
+ new ThemePreferenceController(context).updateNonIndexableKeys(result);
return result;
}
diff --git a/src/com/android/settings/SecuritySettings.java b/src/com/android/settings/SecuritySettings.java
index c06f872..436745f 100644
--- a/src/com/android/settings/SecuritySettings.java
+++ b/src/com/android/settings/SecuritySettings.java
@@ -126,9 +126,13 @@
private static final String KEY_TRUST_AGENT = "trust_agent";
private static final String KEY_SCREEN_PINNING = "screen_pinning_settings";
+ // Security status
+ private static final String KEY_SECURITY_STATUS = "security_status";
+ private static final String SECURITY_STATUS_KEY_PREFIX = "security_status_";
+
// Package verifier Settings
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
- static final String KEY_PACKAGE_VERIFIER_STATE = "package_verifier_state";
+ static final String KEY_PACKAGE_VERIFIER_STATUS = "security_status_package_verifier";
private static final int PACKAGE_VERIFIER_STATE_ENABLED = 1;
// These switch preferences need special handling since they're not all stored in Settings.
@@ -261,6 +265,9 @@
addPreferencesFromResource(R.xml.security_settings);
root = getPreferenceScreen();
+ // Add category for security status
+ addPreferencesFromResource(R.xml.security_settings_status);
+
// Add options for lock/unlock screen
final int resid = getResIdForLockUnlockScreen(getActivity(), mLockPatternUtils,
mManagedPasswordProvider, MY_USER_ID);
@@ -428,19 +435,38 @@
Index.getInstance(getActivity())
.updateFromClassNameResource(SecuritySettings.class.getName(), true, true);
+ PreferenceGroup securityStatusPreferenceGroup =
+ (PreferenceGroup) root.findPreference(KEY_SECURITY_STATUS);
if (mDashboardFeatureProvider.isEnabled()) {
final List<Preference> tilePrefs = mDashboardFeatureProvider.getPreferencesForCategory(
getActivity(), getPrefContext(), CategoryKey.CATEGORY_SECURITY);
+ int numSecurityStatusPrefs = 0;
if (tilePrefs != null && !tilePrefs.isEmpty()) {
for (Preference preference : tilePrefs) {
- root.addPreference(preference);
+ if (!TextUtils.isEmpty(preference.getKey())
+ && preference.getKey().startsWith(SECURITY_STATUS_KEY_PREFIX)) {
+ // Injected security status settings are placed under the Security status
+ // category.
+ securityStatusPreferenceGroup.addPreference(preference);
+ numSecurityStatusPrefs++;
+ } else {
+ // Other injected settings are placed under the Security preference screen.
+ root.addPreference(preference);
+ }
}
}
- // Update preference data with tile data. Security feature provider only updates the
- // data if it actually needs to be changed.
- mSecurityFeatureProvider.updatePreferences(getActivity(), root,
- mDashboardFeatureProvider.getTilesForCategory(CategoryKey.CATEGORY_SECURITY));
+ if (numSecurityStatusPrefs == 0) {
+ root.removePreference(securityStatusPreferenceGroup);
+ } else if (numSecurityStatusPrefs > 0) {
+ // Update preference data with tile data. Security feature provider only updates the
+ // data if it actually needs to be changed.
+ mSecurityFeatureProvider.updatePreferences(getActivity(), root,
+ mDashboardFeatureProvider.getTilesForCategory(
+ CategoryKey.CATEGORY_SECURITY));
+ }
+ } else {
+ root.removePreference(root.findPreference(KEY_SECURITY_STATUS));
}
for (int i = 0; i < SWITCH_PREFERENCE_KEYS.length; i++) {
@@ -1365,7 +1391,7 @@
}
for (int i = 0; i < tilesCount; i++) {
Tile tile = dashboardCategory.getTile(i);
- if (!KEY_PACKAGE_VERIFIER_STATE.equals(tile.key)) {
+ if (!KEY_PACKAGE_VERIFIER_STATUS.equals(tile.key)) {
continue;
}
String summaryUri = tile.metaData.getString(
diff --git a/src/com/android/settings/Settings.java b/src/com/android/settings/Settings.java
index 12b86b6..360d258 100644
--- a/src/com/android/settings/Settings.java
+++ b/src/com/android/settings/Settings.java
@@ -124,6 +124,7 @@
public static class ConfigureNotificationSettingsActivity extends SettingsActivity { /* empty */ }
public static class NotificationAppListActivity extends SettingsActivity { /* empty */ }
public static class AppNotificationSettingsActivity extends SettingsActivity { /* empty */ }
+ public static class ChannelNotificationSettingsActivity extends SettingsActivity { /* empty */ }
public static class OtherSoundSettingsActivity extends SettingsActivity { /* empty */ }
public static class ManageDomainUrlsActivity extends SettingsActivity { /* empty */ }
public static class AutomaticStorageManagerSettingsActivity extends SettingsActivity { /* empty */ }
diff --git a/src/com/android/settings/SettingsActivity.java b/src/com/android/settings/SettingsActivity.java
index 8bb6834..c01e4c4 100644
--- a/src/com/android/settings/SettingsActivity.java
+++ b/src/com/android/settings/SettingsActivity.java
@@ -33,8 +33,6 @@
import android.content.res.Configuration;
import android.nfc.NfcAdapter;
import android.os.AsyncTask;
-import android.os.Build;
-import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.UserHandle;
import android.os.UserManager;
@@ -967,27 +965,29 @@
}
}
- // Check if the backup transport has provided an intent to launch the backup settings.
- BackupSettingsHelper backupHelper = new BackupSettingsHelper();
- boolean useDefaultBackup = !backupHelper.isIntentProvidedByTransport(getPackageManager());
- if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
- Log.v(LOG_TAG, "Enabling default backup settings page: " + useDefaultBackup);
- }
-
+ String backupIntent = getResources().getString(R.string.config_backup_settings_intent);
+ boolean useDefaultBackup = TextUtils.isEmpty(backupIntent);
setTileEnabled(new ComponentName(packageName,
Settings.PrivacySettingsActivity.class.getName()), useDefaultBackup, isAdmin);
setTileEnabled(new ComponentName(packageName,
"com.android.settings.PrivacyDashboardAlias"),
useDefaultBackup, isAdmin);
- // Enable/disable BackupSettingsActivity and its alias.
- if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
- Log.v(LOG_TAG, "Enabling transport provided backup settings: " + !useDefaultBackup);
+ boolean hasBackupActivity = false;
+ if (!useDefaultBackup) {
+ try {
+ Intent intent = Intent.parseUri(backupIntent, 0);
+ hasBackupActivity = !getPackageManager().queryIntentActivities(intent, 0).isEmpty();
+ } catch (URISyntaxException e) {
+ Log.e(LOG_TAG, "Invalid backup intent URI!", e);
+ }
}
+
+ // Enable/disable BackupSettingsActivity and its alias.
setTileEnabled(new ComponentName(packageName,
- BackupSettingsActivity.class.getName()), !useDefaultBackup, isAdmin);
+ BackupSettingsActivity.class.getName()), hasBackupActivity, isAdmin);
setTileEnabled(new ComponentName(packageName,
- "com.android.settings.BackupResetDashboardAlias"), !useDefaultBackup, isAdmin);
+ "com.android.settings.BackupResetDashboardAlias"), hasBackupActivity, isAdmin);
setTileEnabled(new ComponentName(packageName,
Settings.EnterprisePrivacySettingsActivity.class.getName()),
diff --git a/src/com/android/settings/accessibility/AccessibilitySettingsForSetupWizard.java b/src/com/android/settings/accessibility/AccessibilitySettingsForSetupWizard.java
index 009fa5d..b8f3af5 100644
--- a/src/com/android/settings/accessibility/AccessibilitySettingsForSetupWizard.java
+++ b/src/com/android/settings/accessibility/AccessibilitySettingsForSetupWizard.java
@@ -41,11 +41,21 @@
private static final String DISPLAY_MAGNIFICATION_PREFERENCE =
"screen_magnification_preference";
private static final String SCREEN_READER_PREFERENCE = "screen_reader_preference";
+ private static final String SELECT_TO_SPEAK_PREFERENCE = "select_to_speak_preference";
private static final String FONT_SIZE_PREFERENCE = "font_size_preference";
+ // Package names and service names used to identify screen reader and SelectToSpeak services.
+ private static final String SCREEN_READER_PACKAGE_NAME = "com.google.android.marvin.talkback";
+ private static final String SCREEN_READER_SERVICE_NAME =
+ "com.google.android.marvin.talkback.TalkBackService";
+ private static final String SELECT_TO_SPEAK_PACKAGE_NAME = "com.google.android.marvin.talkback";
+ private static final String SELECT_TO_SPEAK_SERVICE_NAME =
+ "com.google.android.accessibility.selecttospeak.SelectToSpeakService";
+
// Preference controls.
private Preference mDisplayMagnificationPreference;
private Preference mScreenReaderPreference;
+ private Preference mSelectToSpeakPreference;
@Override
public int getMetricsCategory() {
@@ -59,12 +69,16 @@
mDisplayMagnificationPreference = findPreference(DISPLAY_MAGNIFICATION_PREFERENCE);
mScreenReaderPreference = findPreference(SCREEN_READER_PREFERENCE);
+ mSelectToSpeakPreference = findPreference(SELECT_TO_SPEAK_PREFERENCE);
}
@Override
public void onResume() {
super.onResume();
- updateScreenReaderPreference();
+ updateAccessibilityServicePreference(mScreenReaderPreference,
+ findService(SCREEN_READER_PACKAGE_NAME, SCREEN_READER_SERVICE_NAME));
+ updateAccessibilityServicePreference(mSelectToSpeakPreference,
+ findService(SELECT_TO_SPEAK_PACKAGE_NAME, SELECT_TO_SPEAK_SERVICE_NAME));
}
@Override
@@ -94,13 +108,15 @@
return super.onPreferenceTreeClick(preference);
}
- private AccessibilityServiceInfo findFirstServiceWithSpokenFeedback() {
+ private AccessibilityServiceInfo findService(String packageName, String serviceName) {
final AccessibilityManager manager =
getActivity().getSystemService(AccessibilityManager.class);
final List<AccessibilityServiceInfo> accessibilityServices =
manager.getInstalledAccessibilityServiceList();
for (AccessibilityServiceInfo info : accessibilityServices) {
- if ((info.feedbackType & AccessibilityServiceInfo.FEEDBACK_SPOKEN) != 0) {
+ ServiceInfo serviceInfo = info.getResolveInfo().serviceInfo;
+ if (packageName.equals(serviceInfo.packageName)
+ && serviceName.equals(serviceInfo.name)) {
return info;
}
}
@@ -108,28 +124,25 @@
return null;
}
- private void updateScreenReaderPreference() {
- // Find a screen reader.
- AccessibilityServiceInfo info = findFirstServiceWithSpokenFeedback();
+ private void updateAccessibilityServicePreference(Preference preference,
+ AccessibilityServiceInfo info) {
if (info == null) {
- mScreenReaderPreference.setEnabled(false);
- } else {
- mScreenReaderPreference.setEnabled(true);
+ getPreferenceScreen().removePreference(preference);
+ return;
}
ServiceInfo serviceInfo = info.getResolveInfo().serviceInfo;
String title = info.getResolveInfo().loadLabel(getPackageManager()).toString();
- mScreenReaderPreference.setTitle(title);
-
+ preference.setTitle(title);
ComponentName componentName = new ComponentName(serviceInfo.packageName, serviceInfo.name);
- mScreenReaderPreference.setKey(componentName.flattenToString());
+ preference.setKey(componentName.flattenToString());
// Update the extras.
- Bundle extras = mScreenReaderPreference.getExtras();
+ Bundle extras = preference.getExtras();
extras.putParcelable(AccessibilitySettings.EXTRA_COMPONENT_NAME, componentName);
extras.putString(AccessibilitySettings.EXTRA_PREFERENCE_KEY,
- mScreenReaderPreference.getKey());
+ preference.getKey());
extras.putString(AccessibilitySettings.EXTRA_TITLE, title);
String description = info.loadDescription(getPackageManager());
diff --git a/src/com/android/settings/accessibility/ToggleSelectToSpeakPreferenceFragmentForSetupWizard.java b/src/com/android/settings/accessibility/ToggleSelectToSpeakPreferenceFragmentForSetupWizard.java
new file mode 100644
index 0000000..2c9b58c
--- /dev/null
+++ b/src/com/android/settings/accessibility/ToggleSelectToSpeakPreferenceFragmentForSetupWizard.java
@@ -0,0 +1,51 @@
+/*
+ * 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.accessibility;
+
+import android.os.Bundle;
+
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+
+public class ToggleSelectToSpeakPreferenceFragmentForSetupWizard
+ extends ToggleAccessibilityServicePreferenceFragment {
+
+ private boolean mToggleSwitchWasInitiallyChecked;
+
+ @Override
+ protected void onProcessArguments(Bundle arguments) {
+ super.onProcessArguments(arguments);
+ mToggleSwitchWasInitiallyChecked = mToggleSwitch.isChecked();
+ }
+
+ @Override
+ public int getMetricsCategory() {
+ return MetricsEvent.SUW_ACCESSIBILITY_TOGGLE_SCREEN_READER;
+ }
+
+ @Override
+ public void onStop() {
+ // Log the final choice in value if it's different from the previous value.
+ if (mToggleSwitch.isChecked() != mToggleSwitchWasInitiallyChecked) {
+ mMetricsFeatureProvider.action(getContext(),
+ MetricsEvent.SUW_ACCESSIBILITY_TOGGLE_SELECT_TO_SPEAK,
+ mToggleSwitch.isChecked());
+ }
+
+ super.onStop();
+ }
+}
+
diff --git a/src/com/android/settings/core/gateway/SettingsGateway.java b/src/com/android/settings/core/gateway/SettingsGateway.java
index 96cbb92..1dd83cb 100644
--- a/src/com/android/settings/core/gateway/SettingsGateway.java
+++ b/src/com/android/settings/core/gateway/SettingsGateway.java
@@ -101,6 +101,7 @@
import com.android.settings.nfc.AndroidBeam;
import com.android.settings.nfc.PaymentSettings;
import com.android.settings.notification.AppNotificationSettings;
+import com.android.settings.notification.ChannelNotificationSettings;
import com.android.settings.notification.ConfigureNotificationSettings;
import com.android.settings.notification.NotificationAccessSettings;
import com.android.settings.notification.NotificationStation;
@@ -209,6 +210,7 @@
InstalledAppDetails.class.getName(),
BatterySaverSettings.class.getName(),
AppNotificationSettings.class.getName(),
+ ChannelNotificationSettings.class.getName(),
OtherSoundSettings.class.getName(),
ApnSettings.class.getName(),
ApnEditor.class.getName(),
diff --git a/src/com/android/settings/deviceinfo/StorageDashboardFragment.java b/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
index 59f9a84..61f3e95 100644
--- a/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
+++ b/src/com/android/settings/deviceinfo/StorageDashboardFragment.java
@@ -21,6 +21,7 @@
import android.os.storage.StorageManager;
import android.os.storage.VolumeInfo;
import android.provider.SearchIndexableResource;
+import android.support.annotation.VisibleForTesting;
import com.android.internal.logging.nano.MetricsProto;
import com.android.settings.R;
@@ -55,14 +56,11 @@
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
- final Context context = getActivity();
// Initialize the storage sizes that we can quickly calc.
+ final Context context = getActivity();
StorageManager sm = context.getSystemService(StorageManager.class);
- String volumeId = getArguments().getString(VolumeInfo.EXTRA_VOLUME_ID,
- VolumeInfo.ID_PRIVATE_INTERNAL);
- mVolume = sm.findVolumeById(volumeId);
- if (!isVolumeValid()) {
+ if (!initializeVolume(sm, getArguments())) {
getActivity().finish();
return;
}
@@ -120,6 +118,17 @@
}
/**
+ * Initializes the volume with a given bundle and returns if the volume is valid.
+ */
+ @VisibleForTesting
+ boolean initializeVolume(StorageManager sm, Bundle bundle) {
+ String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
+ VolumeInfo.ID_PRIVATE_INTERNAL);
+ mVolume = sm.findVolumeById(volumeId);
+ return isVolumeValid();
+ }
+
+ /**
* For Search.
*/
public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
diff --git a/src/com/android/settings/display/ThemePreferenceController.java b/src/com/android/settings/display/ThemePreferenceController.java
new file mode 100644
index 0000000..da5b84a
--- /dev/null
+++ b/src/com/android/settings/display/ThemePreferenceController.java
@@ -0,0 +1,112 @@
+/*
+ * 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.display;
+
+import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.ACTION_THEME;
+
+import android.app.AlertDialog;
+import android.app.UiModeManager;
+import android.content.Context;
+import android.content.DialogInterface.OnClickListener;
+import android.support.v7.preference.ListPreference;
+import android.support.v7.preference.Preference;
+
+import com.android.settings.R;
+import com.android.settings.core.PreferenceController;
+import com.android.settings.core.instrumentation.MetricsFeatureProvider;
+import com.android.settings.overlay.FeatureFactory;
+
+import libcore.util.Objects;
+
+public class ThemePreferenceController extends PreferenceController implements
+ Preference.OnPreferenceChangeListener {
+
+ private static final String KEY_THEME = "theme";
+
+ private final UiModeManager mUiModeManager;
+ private final MetricsFeatureProvider mMetricsFeatureProvider;
+
+ public ThemePreferenceController(Context context) {
+ super(context);
+ mUiModeManager = context.getSystemService(UiModeManager.class);
+ mMetricsFeatureProvider = FeatureFactory.getFactory(context).getMetricsFeatureProvider();
+ }
+
+ @Override
+ public String getPreferenceKey() {
+ return KEY_THEME;
+ }
+
+ @Override
+ public boolean handlePreferenceTreeClick(Preference preference) {
+ if (KEY_THEME.equals(preference.getKey())) {
+ mMetricsFeatureProvider.action(mContext, ACTION_THEME);
+ }
+ return false;
+ }
+
+ @Override
+ public void updateState(Preference preference) {
+ ListPreference pref = (ListPreference) preference;
+ String[] options = mUiModeManager.getAvailableThemes();
+ for (int i = 0; i < options.length; i++) {
+ options[i] = nullToDefault(options[i]);
+ }
+ pref.setEntries(options);
+ pref.setEntryValues(options);
+ String theme = mUiModeManager.getTheme();
+ if (theme == null) {
+ theme = mContext.getString(R.string.default_theme);
+ }
+ pref.setValue(nullToDefault(theme));
+ }
+
+ @Override
+ public boolean onPreferenceChange(Preference preference, Object newValue) {
+ if (Objects.equal(newValue, mUiModeManager.getTheme())) {
+ return true;
+ }
+ // TODO: STOPSHIP Don't require reboot and remove this prompt.
+ OnClickListener onConfirm = (d, i) -> {
+ mUiModeManager.setTheme(defaultToNull((String) newValue));
+ ((ListPreference) preference).setValue((String) newValue);
+ };
+ new AlertDialog.Builder(mContext)
+ .setTitle(R.string.change_theme_reboot)
+ .setPositiveButton(com.android.internal.R.string.global_action_restart, onConfirm)
+ .setNegativeButton(android.R.string.cancel, null)
+ .show();
+ return false;
+ }
+
+ @Override
+ public boolean isAvailable() {
+ String[] themes = mUiModeManager.getAvailableThemes();
+ return themes != null && themes.length > 1;
+ }
+
+ private String nullToDefault(String input) {
+ if (input == null) {
+ return mContext.getString(R.string.default_theme);
+ }
+ return input;
+ }
+
+ private String defaultToNull(String input) {
+ if (mContext.getString(R.string.default_theme).equals(input)) {
+ return null;
+ }
+ return input;
+ }
+}
diff --git a/src/com/android/settings/fuelgauge/BatterySaverController.java b/src/com/android/settings/fuelgauge/BatterySaverController.java
new file mode 100644
index 0000000..08d570a
--- /dev/null
+++ b/src/com/android/settings/fuelgauge/BatterySaverController.java
@@ -0,0 +1,176 @@
+/*
+ * 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.fuelgauge;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.database.ContentObserver;
+import android.os.BatteryManager;
+import android.os.Handler;
+import android.os.PowerManager;
+import android.provider.Settings;
+import android.support.annotation.VisibleForTesting;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.PreferenceScreen;
+import android.util.Log;
+import com.android.settings.R;
+import com.android.settings.Utils;
+import com.android.settings.core.PreferenceController;
+import com.android.settings.core.lifecycle.Lifecycle;
+import com.android.settings.core.lifecycle.LifecycleObserver;
+import com.android.settings.core.lifecycle.events.OnStart;
+import com.android.settings.core.lifecycle.events.OnStop;
+import com.android.settings.dashboard.conditional.BatterySaverCondition;
+import com.android.settings.dashboard.conditional.ConditionManager;
+import com.android.settings.widget.MasterSwitchPreference;
+
+import static android.os.PowerManager.ACTION_POWER_SAVE_MODE_CHANGING;
+
+public class BatterySaverController extends PreferenceController implements
+ Preference.OnPreferenceChangeListener, LifecycleObserver, OnStart, OnStop {
+ private static final String KEY_BATTERY_SAVER = "battery_saver";
+ private static final String TAG = "BatterySaverController";
+ private static final boolean DEBUG = false;
+
+ private final BatteryStateChangeReceiver mBatteryStateChangeReceiver;
+ private final PowerManager mPowerManager;
+ private MasterSwitchPreference mBatterySaverPref;
+
+ public BatterySaverController(Context context, Lifecycle lifecycle) {
+ super(context);
+
+ lifecycle.addObserver(this);
+ mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
+ mBatteryStateChangeReceiver = new BatteryStateChangeReceiver();
+ }
+
+ @Override
+ public boolean isAvailable() {
+ return true;
+ }
+
+ @Override
+ public String getPreferenceKey() {
+ return KEY_BATTERY_SAVER;
+ }
+
+ @Override
+ public void displayPreference(PreferenceScreen screen) {
+ super.displayPreference(screen);
+ mBatterySaverPref = (MasterSwitchPreference) screen.findPreference(KEY_BATTERY_SAVER);
+ }
+
+ @Override
+ public void updateState(Preference preference) {
+ mBatterySaverPref.setChecked(mPowerManager.isPowerSaveMode());
+ updateSummary();
+ }
+
+ @Override
+ public boolean onPreferenceChange(Preference preference, Object newValue) {
+ final boolean saverOn = (Boolean) newValue;
+ if (saverOn != mPowerManager.isPowerSaveMode()
+ && !mPowerManager.setPowerSaveMode(saverOn)) {
+ // Do nothing if power save mode doesn't set correctly
+ return false;
+ }
+
+ refreshConditionManager();
+ updateSummary();
+ return true;
+ }
+
+ @Override
+ public void onStart() {
+ mContext.getContentResolver().registerContentObserver(
+ Settings.Global.getUriFor(Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL)
+ , true, mObserver);
+
+ mBatteryStateChangeReceiver.setListening(true);
+ }
+
+ @Override
+ public void onStop() {
+ mContext.getContentResolver().unregisterContentObserver(mObserver);
+ mBatteryStateChangeReceiver.setListening(false);
+ }
+
+ @VisibleForTesting
+ void refreshConditionManager() {
+ ConditionManager.get(mContext).getCondition(BatterySaverCondition.class).refreshState();
+ }
+
+ private void updateSummary() {
+ final boolean mode = mPowerManager.isPowerSaveMode();
+ final int format = mode ? R.string.battery_saver_on_summary
+ : R.string.battery_saver_off_summary;
+ final int percent = Settings.Global.getInt(mContext.getContentResolver(),
+ Settings.Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0);
+ final int percentFormat = percent > 0 ? R.string.battery_saver_desc_turn_on_auto_pct
+ : R.string.battery_saver_desc_turn_on_auto_never;
+
+ final String summary = mContext.getString(format, mContext.getString(percentFormat,
+ Utils.formatPercentage(percent)));
+
+ mBatterySaverPref.setSummary(summary);
+ }
+
+ private final ContentObserver mObserver = new ContentObserver(new Handler()) {
+ @Override
+ public void onChange(boolean selfChange) {
+ updateSummary();
+ }
+ };
+
+ private final class BatteryStateChangeReceiver extends BroadcastReceiver {
+ private boolean mRegistered;
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (DEBUG) {
+ Log.d(TAG, "Received " + intent.getAction());
+ }
+ final String action = intent.getAction();
+ if (action.equals(ACTION_POWER_SAVE_MODE_CHANGING)) {
+ mBatterySaverPref.setChecked(mPowerManager.isPowerSaveMode());
+ updateSummary();
+ } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
+ final int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
+ // disable BSM switch if phone is plugged in or at 100% while plugged in
+ final boolean enabled = !(status == BatteryManager.BATTERY_STATUS_CHARGING
+ || status == BatteryManager.BATTERY_STATUS_FULL);
+
+ mBatterySaverPref.setSwitchEnabled(enabled);
+ }
+ }
+
+ public void setListening(boolean listening) {
+ if (listening && !mRegistered) {
+ final IntentFilter ifilter = new IntentFilter();
+ ifilter.addAction(Intent.ACTION_BATTERY_CHANGED);
+ ifilter.addAction(ACTION_POWER_SAVE_MODE_CHANGING);
+ mContext.registerReceiver(this, ifilter);
+ mRegistered = true;
+ } else if (!listening && mRegistered) {
+ mContext.unregisterReceiver(this);
+ mRegistered = false;
+ }
+ }
+
+ }
+}
diff --git a/src/com/android/settings/fuelgauge/BatterySaverPreference.java b/src/com/android/settings/fuelgauge/BatterySaverPreference.java
deleted file mode 100644
index 9e0f39b..0000000
--- a/src/com/android/settings/fuelgauge/BatterySaverPreference.java
+++ /dev/null
@@ -1,79 +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.fuelgauge;
-
-import android.content.Context;
-import android.database.ContentObserver;
-import android.os.Handler;
-import android.os.PowerManager;
-import android.provider.Settings;
-import android.provider.Settings.Global;
-import android.support.v7.preference.Preference;
-import android.util.AttributeSet;
-import android.view.View;
-import com.android.settings.R;
-import com.android.settings.Utils;
-
-public class BatterySaverPreference extends Preference {
-
- private PowerManager mPowerManager;
-
- public BatterySaverPreference(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- @Override
- protected void performClick(View view) {
- Utils.startWithFragment(getContext(), getFragment(), null, null, 0, 0, getTitle());
- }
-
- @Override
- public void onAttached() {
- super.onAttached();
- mPowerManager = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
- mObserver.onChange(true);
- getContext().getContentResolver().registerContentObserver(
- Settings.Global.getUriFor(Global.LOW_POWER_MODE_TRIGGER_LEVEL), true, mObserver);
- getContext().getContentResolver().registerContentObserver(
- Settings.Global.getUriFor(Global.LOW_POWER_MODE), true, mObserver);
- }
-
- @Override
- public void onDetached() {
- super.onDetached();
- getContext().getContentResolver().unregisterContentObserver(mObserver);
- }
-
- private void updateSwitch() {
- final Context context = getContext();
- final boolean mode = mPowerManager.isPowerSaveMode();
- int format = mode ? R.string.battery_saver_on_summary
- : R.string.battery_saver_off_summary;
- int percent = Settings.Global.getInt(context.getContentResolver(),
- Global.LOW_POWER_MODE_TRIGGER_LEVEL, 0);
- int percentFormat = percent > 0 ? R.string.battery_saver_desc_turn_on_auto_pct
- : R.string.battery_saver_desc_turn_on_auto_never;
- setSummary(context.getString(format, context.getString(percentFormat,
- Utils.formatPercentage(percent))));
- }
-
- private final ContentObserver mObserver = new ContentObserver(new Handler()) {
- @Override
- public void onChange(boolean selfChange) {
- updateSwitch();
- }
- };
-
-}
diff --git a/src/com/android/settings/fuelgauge/PowerUsageSummary.java b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
index db6bfb8..a989ee6 100644
--- a/src/com/android/settings/fuelgauge/PowerUsageSummary.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
@@ -153,6 +153,7 @@
final List<PreferenceController> controllers = new ArrayList<>();
controllers.add(new AutoBrightnessPreferenceController(context));
controllers.add(new TimeoutPreferenceController(context));
+ controllers.add(new BatterySaverController(context, getLifecycle()));
return controllers;
}
diff --git a/src/com/android/settings/nfc/NfcPreferenceController.java b/src/com/android/settings/nfc/NfcPreferenceController.java
index 65c2d4c..a5e5c3e 100644
--- a/src/com/android/settings/nfc/NfcPreferenceController.java
+++ b/src/com/android/settings/nfc/NfcPreferenceController.java
@@ -44,7 +44,6 @@
private NfcEnabler mNfcEnabler;
private NfcAdapter mNfcAdapter;
- private final Handler mHandler = new Handler();
private int mAirplaneMode;
private AirplaneModeObserver mAirplaneModeObserver;
private SwitchPreference mNfcPreference;
@@ -146,7 +145,7 @@
Settings.Global.getUriFor(Settings.Global.AIRPLANE_MODE_ON);
private AirplaneModeObserver() {
- super(mHandler);
+ super(new Handler());
}
public void register() {
diff --git a/src/com/android/settings/notification/AppNotificationSettings.java b/src/com/android/settings/notification/AppNotificationSettings.java
index d4cd6f8..45762c7 100644
--- a/src/com/android/settings/notification/AppNotificationSettings.java
+++ b/src/com/android/settings/notification/AppNotificationSettings.java
@@ -25,8 +25,10 @@
import android.content.pm.ApplicationInfo;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
+import android.provider.Settings;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceCategory;
+import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
@@ -84,6 +86,11 @@
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ if (mUid < 0 || TextUtils.isEmpty(mPkg) || mPkgInfo == null) {
+ Log.w(TAG, "Missing package or uid or packageinfo");
+ toastAndFinish();
+ return;
+ }
final Activity activity = getActivity();
mDashboardFeatureProvider =
FeatureFactory.getFactory(activity).getDashboardFeatureProvider(activity);
@@ -124,7 +131,7 @@
channelArgs.putInt(AppInfoBase.ARG_PACKAGE_UID, mUid);
channelArgs.putBoolean(AppHeader.EXTRA_HIDE_INFO_BUTTON, true);
channelArgs.putString(AppInfoBase.ARG_PACKAGE_NAME, mPkg);
- channelArgs.putString(ARG_CHANNEL, channel.getId());
+ channelArgs.putString(Settings.EXTRA_CHANNEL_ID, channel.getId());
Intent channelIntent = Utils.onBuildStartFragmentIntent(getActivity(),
ChannelNotificationSettings.class.getName(),
channelArgs, null, 0, null, false);
@@ -154,8 +161,8 @@
@Override
public void onResume() {
super.onResume();
- if ((mUid != -1 && getPackageManager().getPackagesForUid(mUid) == null)) {
- // App isn't around anymore, must have been removed.
+ if (mUid < 0 || TextUtils.isEmpty(mPkg) || mPkgInfo == null) {
+ Log.w(TAG, "Missing package or uid or packageinfo");
finish();
return;
}
diff --git a/src/com/android/settings/notification/ChannelNotificationSettings.java b/src/com/android/settings/notification/ChannelNotificationSettings.java
index 2749e03..ecce79e 100644
--- a/src/com/android/settings/notification/ChannelNotificationSettings.java
+++ b/src/com/android/settings/notification/ChannelNotificationSettings.java
@@ -26,7 +26,6 @@
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.admin.DevicePolicyManager;
-import android.content.Context;
import android.content.Intent;
import android.content.pm.UserInfo;
import android.net.Uri;
@@ -35,6 +34,8 @@
import android.provider.Settings;
import android.service.notification.NotificationListenerService.Ranking;
import android.support.v7.preference.Preference;
+import android.text.TextUtils;
+import android.util.Log;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.internal.widget.LockPatternUtils;
@@ -87,6 +88,11 @@
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ if (mUid < 0 || TextUtils.isEmpty(mPkg) || mPkgInfo == null || mChannel == null) {
+ Log.w(TAG, "Missing package or uid or packageinfo or channel");
+ toastAndFinish();
+ return;
+ }
final Activity activity = getActivity();
mDashboardFeatureProvider =
FeatureFactory.getFactory(activity).getDashboardFeatureProvider(activity);
@@ -103,7 +109,7 @@
mVibrate = (RestrictedSwitchPreference) findPreference(KEY_VIBRATE);
mRingtone = (DefaultNotificationTonePreference) findPreference(KEY_RINGTONE);
- if (mPkgInfo != null) {
+ if (mPkgInfo != null && mChannel != null) {
setupPriorityPref(mChannel.canBypassDnd());
setupVisOverridePref(mChannel.getLockscreenVisibility());
setupLights();
@@ -131,8 +137,8 @@
@Override
public void onResume() {
super.onResume();
- if ((mUid != -1 && getPackageManager().getPackagesForUid(mUid) == null)) {
- // App isn't around anymore, must have been removed.
+ if (mUid < 0 || TextUtils.isEmpty(mPkg) || mPkgInfo == null || mChannel == null) {
+ Log.w(TAG, "Missing package or uid or packageinfo or channel");
finish();
return;
}
diff --git a/src/com/android/settings/notification/NotificationSettingsBase.java b/src/com/android/settings/notification/NotificationSettingsBase.java
index 1535269..f6c6591 100644
--- a/src/com/android/settings/notification/NotificationSettingsBase.java
+++ b/src/com/android/settings/notification/NotificationSettingsBase.java
@@ -18,6 +18,7 @@
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
+import com.android.settings.Utils;
import com.android.settings.applications.AppInfoBase;
import com.android.settingslib.RestrictedLockUtils;
import com.android.settingslib.RestrictedSwitchPreference;
@@ -44,8 +45,6 @@
private static final String TAG = "NotifiSettingsBase";
private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
- protected static final String ARG_CHANNEL = "channel";
-
protected static final String KEY_BLOCK = "block";
protected static final String KEY_BADGE = "badge";
@@ -99,26 +98,26 @@
mUid = args != null && args.containsKey(AppInfoBase.ARG_PACKAGE_UID)
? args.getInt(AppInfoBase.ARG_PACKAGE_UID)
: intent.getIntExtra(Settings.EXTRA_APP_UID, -1);
- if (mUid == -1 || TextUtils.isEmpty(mPkg)) {
- Log.w(TAG, "Missing extras: " + Settings.EXTRA_APP_PACKAGE + " was " + mPkg + ", "
- + Settings.EXTRA_APP_UID + " was " + mUid);
- toastAndFinish();
- return;
- }
- mUserId = UserHandle.getUserId(mUid);
- if (DEBUG) Log.d(TAG, "Load details for pkg=" + mPkg + " uid=" + mUid);
+ if (mUid < 0) {
+ try {
+ mUid = mPm.getPackageUid(mPkg, 0);
+ } catch (NameNotFoundException e) {
+ }
+ }
+
mPkgInfo = findPackageInfo(mPkg, mUid);
- if (mPkgInfo == null) {
- Log.w(TAG, "Failed to find package info: " + Settings.EXTRA_APP_PACKAGE + " was " + mPkg
- + ", " + Settings.EXTRA_APP_UID + " was " + mUid);
+
+ if (mUid < 0 || TextUtils.isEmpty(mPkg) || mPkgInfo == null) {
+ Log.w(TAG, "Missing package or uid or packageinfo");
toastAndFinish();
return;
}
+ mUserId = UserHandle.getUserId(mUid);
mAppRow = mBackend.loadAppRow(mContext, mPm, mPkgInfo);
- mChannel = (args != null && args.containsKey(ARG_CHANNEL)) ?
- mBackend.getChannel(mPkg, mUid, args.getString(ARG_CHANNEL)) : null;
+ mChannel = (args != null && args.containsKey(Settings.EXTRA_CHANNEL_ID)) ?
+ mBackend.getChannel(mPkg, mUid, args.getString(Settings.EXTRA_CHANNEL_ID)) : null;
mSuspendedAppsAdmin = RestrictedLockUtils.checkIfApplicationIsSuspended(
mContext, mPkg, mUserId);
@@ -130,8 +129,8 @@
@Override
public void onResume() {
super.onResume();
- if ((mUid != -1 && getPackageManager().getPackagesForUid(mUid) == null)) {
- // App isn't around anymore, must have been removed.
+ if (mUid < 0 || TextUtils.isEmpty(mPkg) || mPkgInfo == null) {
+ Log.w(TAG, "Missing package or uid or packageinfo");
finish();
return;
}
@@ -157,6 +156,9 @@
}
private PackageInfo findPackageInfo(String pkg, int uid) {
+ if (pkg == null || uid < 0) {
+ return null;
+ }
final String[] packages = mPm.getPackagesForUid(uid);
if (packages != null && pkg != null) {
final int N = packages.length;
@@ -173,4 +175,16 @@
}
return null;
}
+
+ private PackageInfo findPackageInfo(String pkg) {
+ if (pkg == null) {
+ return null;
+ }
+ try {
+ return mPm.getPackageInfo(pkg, PackageManager.GET_SIGNATURES);
+ } catch (NameNotFoundException e) {
+ Log.w(TAG, "Failed to load package " + pkg, e);
+ }
+ return null;
+ }
}
diff --git a/src/com/android/settings/search/SearchIndexableResources.java b/src/com/android/settings/search/SearchIndexableResources.java
index 4f9f92c..aa3c257 100644
--- a/src/com/android/settings/search/SearchIndexableResources.java
+++ b/src/com/android/settings/search/SearchIndexableResources.java
@@ -72,6 +72,8 @@
import com.android.settings.print.PrintSettingsFragment;
import com.android.settings.sim.SimSettings;
import com.android.settings.system.SystemDashboardFragment;
+import com.android.settings.tts.TtsEnginePreferenceFragment;
+import com.android.settings.tts.TtsSlidersFragment;
import com.android.settings.users.UserSettings;
import com.android.settings.wifi.AdvancedWifiSettings;
import com.android.settings.wifi.ConfigureWifiSettings;
@@ -86,7 +88,8 @@
@XmlRes
public static final int NO_DATA_RES_ID = 0;
- private static final HashMap<String, SearchIndexableResource> sResMap = new HashMap<>();
+ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
+ static final HashMap<String, SearchIndexableResource> sResMap = new HashMap<>();
@VisibleForTesting
static void addIndex(Class<?> indexClass, @XmlRes int xmlResId,
@@ -167,6 +170,9 @@
addIndex(ConnectedDeviceDashboardFragment.class, NO_DATA_RES_ID, R.drawable.ic_bt_laptop);
addIndex(EnterprisePrivacySettings.class, NO_DATA_RES_ID, R.drawable.ic_settings_about);
addIndex(PaymentSettings.class, NO_DATA_RES_ID, R.drawable.ic_settings_nfc_payment);
+ addIndex(
+ TtsEnginePreferenceFragment.class, NO_DATA_RES_ID, R.drawable.ic_settings_language);
+ addIndex(TtsSlidersFragment.class, NO_DATA_RES_ID, R.drawable.ic_settings_language);
}
private SearchIndexableResources() {
diff --git a/src/com/android/settings/search/SettingsSearchIndexablesProvider.java b/src/com/android/settings/search/SettingsSearchIndexablesProvider.java
index b2be146..b83f9fd 100644
--- a/src/com/android/settings/search/SettingsSearchIndexablesProvider.java
+++ b/src/com/android/settings/search/SettingsSearchIndexablesProvider.java
@@ -16,13 +16,20 @@
package com.android.settings.search;
+import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.provider.SearchIndexableResource;
import android.provider.SearchIndexablesProvider;
+import android.util.Log;
+
+import com.android.settings.search2.DatabaseIndexingUtils;
import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import static android.provider.SearchIndexablesContract.COLUMN_INDEX_NON_INDEXABLE_KEYS_KEY_VALUE;
import static android.provider.SearchIndexablesContract.COLUMN_INDEX_XML_RES_CLASS_NAME;
import static android.provider.SearchIndexablesContract.COLUMN_INDEX_XML_RES_ICON_RESID;
import static android.provider.SearchIndexablesContract.COLUMN_INDEX_XML_RES_INTENT_ACTION;
@@ -35,7 +42,7 @@
import static android.provider.SearchIndexablesContract.NON_INDEXABLES_KEYS_COLUMNS;
public class SettingsSearchIndexablesProvider extends SearchIndexablesProvider {
- private static final String TAG = "SettingsSearchIndexablesProvider";
+ private static final String TAG = "SettingsSearchProvider";
@Override
public boolean onCreate() {
@@ -47,7 +54,7 @@
MatrixCursor cursor = new MatrixCursor(INDEXABLES_XML_RES_COLUMNS);
Collection<SearchIndexableResource> values = SearchIndexableResources.values();
for (SearchIndexableResource val : values) {
- Object[] ref = new Object[7];
+ Object[] ref = new Object[INDEXABLES_XML_RES_COLUMNS.length];
ref[COLUMN_INDEX_XML_RES_RANK] = val.rank;
ref[COLUMN_INDEX_XML_RES_RESID] = val.xmlResId;
ref[COLUMN_INDEX_XML_RES_CLASS_NAME] = val.className;
@@ -66,9 +73,45 @@
return result;
}
+ /**
+ * Gets a combined list non-indexable keys that come from providers inside of settings.
+ * The non-indexable keys are used in Settings search at both index and update time to verify
+ * the validity of results in the database.
+ */
@Override
public Cursor queryNonIndexableKeys(String[] projection) {
MatrixCursor cursor = new MatrixCursor(NON_INDEXABLES_KEYS_COLUMNS);
+ final Collection<String> values = new HashSet<>();
+ final Context context = getContext();
+
+ for (SearchIndexableResource sir : SearchIndexableResources.values()) {
+ final Class<?> clazz = DatabaseIndexingUtils.getIndexableClass(sir.className);
+ if (clazz == null) {
+ Log.d(TAG, "SearchIndexableResource '" + sir.className +
+ "' should implement the " + Indexable.class.getName() + " interface!");
+ continue;
+ }
+
+ final Indexable.SearchIndexProvider provider =
+ DatabaseIndexingUtils.getSearchIndexProvider(clazz);
+
+ if (provider == null) {
+ Log.d(TAG, "Unable to get SearchIndexableProvider from " +
+ Indexable.class.getName());
+ continue;
+ }
+
+ List<String> providerNonIndexableKeys = provider.getNonIndexableKeys(context);
+ if (providerNonIndexableKeys != null && providerNonIndexableKeys.size() > 0) {
+ values.addAll(providerNonIndexableKeys);
+ }
+ }
+
+ for (String nik : values) {
+ final Object[] ref = new Object[NON_INDEXABLES_KEYS_COLUMNS.length];
+ ref[COLUMN_INDEX_NON_INDEXABLE_KEYS_KEY_VALUE] = nik;
+ cursor.addRow(ref);
+ }
return cursor;
}
}
diff --git a/src/com/android/settings/search2/DatabaseResultLoader.java b/src/com/android/settings/search2/DatabaseResultLoader.java
index 8bb1a41..1f032a0 100644
--- a/src/com/android/settings/search2/DatabaseResultLoader.java
+++ b/src/com/android/settings/search2/DatabaseResultLoader.java
@@ -142,9 +142,7 @@
private List<SearchResult> query(String[] matchColumns, int baseRank) {
final String whereClause = buildWhereClause(matchColumns);
- final String[] selection = new String[matchColumns.length];
- final String query = "%" + mQueryText + "%";
- Arrays.fill(selection, query);
+ final String[] selection = buildQuerySelection(matchColumns.length * 2);
final Cursor resultCursor = mDatabase.query(TABLE_PREFS_INDEX, SELECT_COLUMNS, whereClause,
selection, null, null, null);
@@ -174,6 +172,8 @@
final int count = matchColumns.length;
for (int n = 0; n < count; n++) {
sb.append(matchColumns[n]);
+ sb.append(" like ? OR ");
+ sb.append(matchColumns[n]);
sb.append(" like ?");
if (n < count - 1) {
sb.append(" OR ");
@@ -182,4 +182,23 @@
sb.append(") AND enabled = 1");
return sb.toString();
}
+
+ /**
+ * Fills out the selection array to match the query as the prefix of a word.
+ *
+ * @param size is twice the number of columns to be matched. The first match is for the prefix
+ * of the first word in the column. The second match is for any subsequent word
+ * prefix match.
+ */
+ private String[] buildQuerySelection(int size) {
+ String[] selection = new String[size];
+ final String query = mQueryText + "%";
+ final String subStringQuery = "% " + mQueryText + "%";
+
+ for(int i = 0; i < (size - 1); i += 2) {
+ selection[i] = query;
+ selection[i + 1] = subStringQuery;
+ }
+ return selection;
+ }
}
diff --git a/src/com/android/settings/tts/TextToSpeechSettings.java b/src/com/android/settings/tts/TextToSpeechSettings.java
index 96a7f4e..fe78d20 100644
--- a/src/com/android/settings/tts/TextToSpeechSettings.java
+++ b/src/com/android/settings/tts/TextToSpeechSettings.java
@@ -16,29 +16,27 @@
package com.android.settings.tts;
+import android.support.v7.preference.ListPreference;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.Bundle;
-import android.provider.Settings.SettingNotFoundException;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.EngineInfo;
import android.speech.tts.TtsEngines;
import android.speech.tts.UtteranceProgressListener;
-import android.support.v14.preference.SwitchPreference;
import android.support.v7.preference.Preference;
-import android.support.v7.preference.PreferenceCategory;
import android.text.TextUtils;
import android.util.Log;
-import android.widget.Checkable;
+import android.util.Pair;
+import java.util.Comparator;
+import java.util.Collections;
import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
import com.android.settings.R;
-import com.android.settings.SeekBarPreference;
import com.android.settings.SettingsActivity;
import com.android.settings.SettingsPreferenceFragment;
-import com.android.settings.tts.TtsEnginePreference.RadioButtonGroupState;
import java.util.ArrayList;
import java.util.HashMap;
@@ -48,13 +46,15 @@
import java.util.Objects;
import java.util.Set;
-import static android.provider.Settings.Secure.TTS_DEFAULT_PITCH;
-import static android.provider.Settings.Secure.TTS_DEFAULT_RATE;
import static android.provider.Settings.Secure.TTS_DEFAULT_SYNTH;
+import static android.provider.Settings.Secure.TTS_DEFAULT_PITCH;
-public class TextToSpeechSettings extends SettingsPreferenceFragment implements
- Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener,
- RadioButtonGroupState {
+public class TextToSpeechSettings extends SettingsPreferenceFragment
+ implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener {
+
+ private static final String STATE_KEY_LOCALE_ENTRIES = "locale_entries";
+ private static final String STATE_KEY_LOCALE_ENTRY_VALUES = "locale_entry_values";
+ private static final String STATE_KEY_LOCALE_VALUE = "locale_value";
private static final String TAG = "TextToSpeechSettings";
private static final boolean DBG = false;
@@ -62,84 +62,37 @@
/** Preference key for the "play TTS example" preference. */
private static final String KEY_PLAY_EXAMPLE = "tts_play_example";;
- /** Preference key for the TTS pitch selection slider. */
- private static final String KEY_DEFAULT_PITCH = "tts_default_pitch";
-
- /** Preference key for the TTS rate selection slider. */
- private static final String KEY_DEFAULT_RATE = "tts_default_rate";
-
- /** Preference key for the TTS reset speech rate preference. */
- private static final String KEY_RESET_SPEECH_RATE = "reset_speech_rate";
-
- /** Preference key for the TTS reset speech pitch preference. */
- private static final String KEY_RESET_SPEECH_PITCH = "reset_speech_pitch";
-
/** Preference key for the TTS status field. */
private static final String KEY_STATUS = "tts_status";
/**
- * Preference key for the engine selection preference.
- */
- private static final String KEY_ENGINE_PREFERENCE_SECTION =
- "tts_engine_preference_section";
-
- /**
* These look like birth years, but they aren't mine. I'm much younger than this.
*/
private static final int GET_SAMPLE_TEXT = 1983;
private static final int VOICE_DATA_INTEGRITY_CHECK = 1977;
- /**
- * Speech rate value.
- * This value should be kept in sync with the max value set in tts_settings xml.
- */
- private static final int MAX_SPEECH_RATE = 600;
- private static final int MIN_SPEECH_RATE = 10;
-
- /**
- * Speech pitch value.
- * TTS pitch value varies from 25 to 400, where 100 is the value
- * for normal pitch. The max pitch value is set to 400, based on feedback from users
- * and the GoogleTTS pitch variation range. The range for pitch is not set in stone
- * and should be readjusted based on user need.
- * This value should be kept in sync with the max value set in tts_settings xml.
- */
- private static final int MAX_SPEECH_PITCH = 400;
- private static final int MIN_SPEECH_PITCH = 25;
-
- private PreferenceCategory mEnginePreferenceCategory;
- private SeekBarPreference mDefaultPitchPref;
- private SeekBarPreference mDefaultRatePref;
- private Preference mResetSpeechRate;
- private Preference mResetSpeechPitch;
private Preference mPlayExample;
private Preference mEngineStatus;
- private int mDefaultPitch = TextToSpeech.Engine.DEFAULT_PITCH;
- private int mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE;
- /**
- * The currently selected engine.
- */
+ private static final String KEY_ENGINE_LOCALE = "tts_default_lang";
+ private static final String KEY_ENGINE_SETTINGS = "tts_engine_settings";
+ private static final String KEY_INSTALL_DATA = "tts_install_data";
+
+ private int mSelectedLocaleIndex = -1;
+
+ /** The currently selected engine. */
private String mCurrentEngine;
- /**
- * The engine checkbox that is currently checked. Saves us a bit of effort
- * in deducing the right one from the currently selected engine.
- */
- private Checkable mCurrentChecked;
-
- /**
- * The previously selected TTS engine. Useful for rollbacks if the users
- * choice is not loaded or fails a voice integrity check.
- */
- private String mPreviousEngine;
-
private TextToSpeech mTts = null;
private TtsEngines mEnginesHelper = null;
private String mSampleText = null;
+ private ListPreference mLocalePreference;
+ private Preference mEngineSettingsPreference;
+ private Preference mInstallVoicesPreference;
+
/**
* Default locale used by selected TTS engine, null if not connected to any engine.
*/
@@ -164,18 +117,6 @@
}
};
- /**
- * The initialization listener used when the user changes his choice of
- * engine (as opposed to when then screen is being initialized for the first
- * time).
- */
- private final TextToSpeech.OnInitListener mUpdateListener = new TextToSpeech.OnInitListener() {
- @Override
- public void onInit(int status) {
- onUpdateEngine(status);
- }
- };
-
@Override
public int getMetricsCategory() {
return MetricsEvent.TTS_TEXT_TO_SPEECH;
@@ -192,21 +133,40 @@
mPlayExample.setOnPreferenceClickListener(this);
mPlayExample.setEnabled(false);
- mResetSpeechRate = findPreference(KEY_RESET_SPEECH_RATE);
- mResetSpeechRate.setOnPreferenceClickListener(this);
- mResetSpeechPitch = findPreference(KEY_RESET_SPEECH_PITCH);
- mResetSpeechPitch.setOnPreferenceClickListener(this);
+ mEnginesHelper = new TtsEngines(getActivity().getApplicationContext());
- mEnginePreferenceCategory = (PreferenceCategory) findPreference(
- KEY_ENGINE_PREFERENCE_SECTION);
- mDefaultPitchPref = (SeekBarPreference) findPreference(KEY_DEFAULT_PITCH);
- mDefaultRatePref = (SeekBarPreference) findPreference(KEY_DEFAULT_RATE);
+ mLocalePreference = (ListPreference) findPreference(KEY_ENGINE_LOCALE);
+ mLocalePreference.setOnPreferenceChangeListener(this);
+
+ if (savedInstanceState == null) {
+ mLocalePreference.setEnabled(false);
+ mLocalePreference.setEntries(new CharSequence[0]);
+ mLocalePreference.setEntryValues(new CharSequence[0]);
+ } else {
+ // Repopulate mLocalePreference with saved state. Will be updated later with
+ // up-to-date values when checkTtsData() calls back with results.
+ final CharSequence[] entries =
+ savedInstanceState.getCharSequenceArray(STATE_KEY_LOCALE_ENTRIES);
+ final CharSequence[] entryValues =
+ savedInstanceState.getCharSequenceArray(STATE_KEY_LOCALE_ENTRY_VALUES);
+ final CharSequence value = savedInstanceState.getCharSequence(STATE_KEY_LOCALE_VALUE);
+
+ mLocalePreference.setEntries(entries);
+ mLocalePreference.setEntryValues(entryValues);
+ mLocalePreference.setValue(value != null ? value.toString() : null);
+ mLocalePreference.setEnabled(entries.length > 0);
+ }
+
+ mEngineSettingsPreference = findPreference(KEY_ENGINE_SETTINGS);
+ mEngineSettingsPreference.setOnPreferenceClickListener(this);
+ mInstallVoicesPreference = findPreference(KEY_INSTALL_DATA);
+ mInstallVoicesPreference.setOnPreferenceClickListener(this);
+ mInstallVoicesPreference.setEnabled(false);
mEngineStatus = findPreference(KEY_STATUS);
updateEngineStatus(R.string.tts_status_checking);
mTts = new TextToSpeech(getActivity().getApplicationContext(), mInitListener);
- mEnginesHelper = new TtsEngines(getActivity().getApplicationContext());
setTtsUtteranceProgressListener();
initSettings();
@@ -222,6 +182,23 @@
if (mTts == null || mCurrentDefaultLocale == null) {
return;
}
+ if (!mTts.getDefaultEngine().equals(mTts.getCurrentEngine())) {
+ try {
+ mTts.shutdown();
+ mTts = null;
+ } catch (Exception e) {
+ Log.e(TAG, "Error shutting down TTS engine" + e);
+ }
+ mTts = new TextToSpeech(getActivity().getApplicationContext(), mInitListener);
+ setTtsUtteranceProgressListener();
+ initSettings();
+ } else {
+ // Do set pitch correctly after it may have changed, and unlike speed, it doesn't change
+ // immediately.
+ final ContentResolver resolver = getContentResolver();
+ mTts.setPitch(android.provider.Settings.Secure.getInt(resolver, TTS_DEFAULT_PITCH, TextToSpeech.Engine.DEFAULT_PITCH)/100.0f);
+ }
+
Locale ttsDefaultLocale = mTts.getDefaultLanguage();
if (mCurrentDefaultLocale != null && !mCurrentDefaultLocale.equals(ttsDefaultLocale)) {
updateWidgetState(false);
@@ -259,26 +236,9 @@
private void initSettings() {
final ContentResolver resolver = getContentResolver();
- // Set up the default rate and pitch.
- mDefaultRate = android.provider.Settings.Secure.getInt(
- resolver, TTS_DEFAULT_RATE, TextToSpeech.Engine.DEFAULT_RATE);
- mDefaultPitch = android.provider.Settings.Secure.getInt(
- resolver, TTS_DEFAULT_PITCH, TextToSpeech.Engine.DEFAULT_PITCH);
-
- mDefaultRatePref.setProgress(getSeekBarProgressFromValue(KEY_DEFAULT_RATE, mDefaultRate));
- mDefaultRatePref.setOnPreferenceChangeListener(this);
- mDefaultRatePref.setMax(getSeekBarProgressFromValue(KEY_DEFAULT_RATE, MAX_SPEECH_RATE));
-
- mDefaultPitchPref.setProgress(getSeekBarProgressFromValue(KEY_DEFAULT_PITCH,
- mDefaultPitch));
- mDefaultPitchPref.setOnPreferenceChangeListener(this);
- mDefaultPitchPref.setMax(getSeekBarProgressFromValue(KEY_DEFAULT_PITCH,
- MAX_SPEECH_PITCH));
-
if (mTts != null) {
mCurrentEngine = mTts.getCurrentEngine();
- mTts.setSpeechRate(mDefaultRate/100.0f);
- mTts.setPitch(mDefaultPitch/100.0f);
+ mTts.setPitch(android.provider.Settings.Secure.getInt(resolver, TTS_DEFAULT_PITCH, TextToSpeech.Engine.DEFAULT_PITCH)/100.0f);
}
SettingsActivity activity = null;
@@ -289,53 +249,37 @@
"Settings");
}
- mEnginePreferenceCategory.removeAll();
+ if (mCurrentEngine != null) {
+ EngineInfo info = mEnginesHelper.getEngineInfo(mCurrentEngine);
+ mEngineSettingsPreference.setSummary(info.label);
+ final Intent settingsIntent = mEnginesHelper.getSettingsIntent(info.name);
+ mEngineSettingsPreference.setIntent(settingsIntent);
+ if (settingsIntent == null) {
+ mEngineSettingsPreference.setEnabled(false);
+ }
- List<EngineInfo> engines = mEnginesHelper.getEngines();
- for (EngineInfo engine : engines) {
- TtsEnginePreference enginePref = new TtsEnginePreference(getPrefContext(), engine,
- this, activity);
- mEnginePreferenceCategory.addPreference(enginePref);
+ Preference mEnginePreference = findPreference("tts_engine_preference");
+ mEnginePreference.setSummary(info.label);
}
checkVoiceData(mCurrentEngine);
}
/**
- * The minimum speech pitch/rate value should be > 0 but the minimum value of a seekbar in
- * android is fixed at 0. Therefore, we increment the seekbar progress with MIN_SPEECH_VALUE
- * so that the minimum seekbar progress value is MIN_SPEECH_PITCH/RATE.
- * SPEECH_VALUE = MIN_SPEECH_VALUE + SEEKBAR_PROGRESS
- */
- private int getValueFromSeekBarProgress(String preferenceKey, int progress) {
- if (preferenceKey.equals(KEY_DEFAULT_RATE)) {
- return MIN_SPEECH_RATE + progress;
- } else if (preferenceKey.equals(KEY_DEFAULT_PITCH)) {
- return MIN_SPEECH_PITCH + progress;
- }
- return progress;
- }
-
- /**
- * Since we are appending the MIN_SPEECH value to the speech seekbar progress, the
- * speech seekbar progress should be set to (speechValue - MIN_SPEECH value).
- */
- private int getSeekBarProgressFromValue(String preferenceKey, int value) {
- if (preferenceKey.equals(KEY_DEFAULT_RATE)) {
- return value - MIN_SPEECH_RATE;
- } else if (preferenceKey.equals(KEY_DEFAULT_PITCH)) {
- return value - MIN_SPEECH_PITCH;
- }
- return value;
- }
-
- /**
* Called when the TTS engine is initialized.
*/
public void onInitEngine(int status) {
if (status == TextToSpeech.SUCCESS) {
if (DBG) Log.d(TAG, "TTS engine for settings screen initialized.");
checkDefaultLocale();
+ getActivity()
+ .runOnUiThread(
+ new Runnable() {
+ @Override
+ public void run() {
+ mLocalePreference.setEnabled(true);
+ }
+ });
} else {
if (DBG) Log.d(TAG, "TTS engine for settings screen failed to initialize successfully.");
updateWidgetState(false);
@@ -452,9 +396,88 @@
onSampleTextReceived(resultCode, data);
} else if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
onVoiceDataIntegrityCheckDone(data);
+ if (resultCode != TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL) {
+ updateDefaultLocalePref(data);
+ }
}
}
+ private void updateDefaultLocalePref(Intent data) {
+ final ArrayList<String> availableLangs =
+ data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
+
+ final ArrayList<String> unavailableLangs =
+ data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES);
+
+ if (availableLangs != null && unavailableLangs.size() > 0) {
+ mInstallVoicesPreference.setEnabled(true);
+ } else {
+ mInstallVoicesPreference.setEnabled(false);
+ }
+
+ if (availableLangs == null || availableLangs.size() == 0) {
+ mLocalePreference.setEnabled(false);
+ return;
+ }
+ Locale currentLocale = null;
+ if (!mEnginesHelper.isLocaleSetToDefaultForEngine(mTts.getCurrentEngine())) {
+ currentLocale = mEnginesHelper.getLocalePrefForEngine(mTts.getCurrentEngine());
+ }
+
+ ArrayList<Pair<String, Locale>> entryPairs =
+ new ArrayList<Pair<String, Locale>>(availableLangs.size());
+ for (int i = 0; i < availableLangs.size(); i++) {
+ Locale locale = mEnginesHelper.parseLocaleString(availableLangs.get(i));
+ if (locale != null) {
+ entryPairs.add(new Pair<String, Locale>(locale.getDisplayName(), locale));
+ }
+ }
+
+ // Sort it
+ Collections.sort(
+ entryPairs,
+ new Comparator<Pair<String, Locale>>() {
+ @Override
+ public int compare(Pair<String, Locale> lhs, Pair<String, Locale> rhs) {
+ return lhs.first.compareToIgnoreCase(rhs.first);
+ }
+ });
+
+ // Get two arrays out of one of pairs
+ mSelectedLocaleIndex = 0; // Will point to the R.string.tts_lang_use_system value
+ CharSequence[] entries = new CharSequence[availableLangs.size() + 1];
+ CharSequence[] entryValues = new CharSequence[availableLangs.size() + 1];
+
+ entries[0] = getActivity().getString(R.string.tts_lang_use_system);
+ entryValues[0] = "";
+
+ int i = 1;
+ for (Pair<String, Locale> entry : entryPairs) {
+ if (entry.second.equals(currentLocale)) {
+ mSelectedLocaleIndex = i;
+ }
+ entries[i] = entry.first;
+ entryValues[i++] = entry.second.toString();
+ }
+
+ mLocalePreference.setEntries(entries);
+ mLocalePreference.setEntryValues(entryValues);
+ mLocalePreference.setEnabled(true);
+ setLocalePreference(mSelectedLocaleIndex);
+ }
+
+ /** Set entry from entry table in mLocalePreference */
+ private void setLocalePreference(int index) {
+ if (index < 0) {
+ mLocalePreference.setValue("");
+ mLocalePreference.setSummary(R.string.tts_lang_not_selected);
+ } else {
+ mLocalePreference.setValueIndex(index);
+ mLocalePreference.setSummary(mLocalePreference.getEntries()[index]);
+ }
+ }
+
+
private String getDefaultSampleString() {
if (mTts != null && mTts.getLanguage() != null) {
try {
@@ -522,17 +545,59 @@
@Override
public boolean onPreferenceChange(Preference preference, Object objValue) {
- if (KEY_DEFAULT_RATE.equals(preference.getKey())) {
- updateSpeechRate((Integer) objValue);
- } else if (KEY_DEFAULT_PITCH.equals(preference.getKey())) {
- updateSpeechPitchValue((Integer) objValue);
+ if (preference == mLocalePreference) {
+ String localeString = (String) objValue;
+ updateLanguageTo(
+ (!TextUtils.isEmpty(localeString)
+ ? mEnginesHelper.parseLocaleString(localeString)
+ : null));
+ checkDefaultLocale();
+ return true;
}
return true;
}
+ private void updateLanguageTo(Locale locale) {
+ int selectedLocaleIndex = -1;
+ String localeString = (locale != null) ? locale.toString() : "";
+ for (int i = 0; i < mLocalePreference.getEntryValues().length; i++) {
+ if (localeString.equalsIgnoreCase(mLocalePreference.getEntryValues()[i].toString())) {
+ selectedLocaleIndex = i;
+ break;
+ }
+ }
+
+ if (selectedLocaleIndex == -1) {
+ Log.w(TAG, "updateLanguageTo called with unknown locale argument");
+ return;
+ }
+ mLocalePreference.setSummary(mLocalePreference.getEntries()[selectedLocaleIndex]);
+ mSelectedLocaleIndex = selectedLocaleIndex;
+
+ mEnginesHelper.updateLocalePrefForEngine(mTts.getCurrentEngine(), locale);
+
+ // Null locale means "use system default"
+ mTts.setLanguage((locale != null) ? locale : Locale.getDefault());
+ }
+
/**
- * Called when mPlayExample, mResetSpeechRate or mResetSpeechPitch is
- * clicked.
+ * Ask the current default engine to launch the matching INSTALL_TTS_DATA activity so the
+ * required TTS files are properly installed.
+ */
+ private void installVoiceData() {
+ if (TextUtils.isEmpty(mCurrentEngine)) return;
+ Intent intent = new Intent(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
+ intent.setPackage(mCurrentEngine);
+ try {
+ Log.v(TAG, "Installing voice data: " + intent.toUri(0));
+ startActivity(intent);
+ } catch (ActivityNotFoundException ex) {
+ Log.e(TAG, "Failed to install TTS data, no acitivty found for " + intent + ")");
+ }
+ }
+
+ /**
+ * Called when mPlayExample, mInstallVoicesPreference is clicked.
*/
@Override
public boolean onPreferenceClick(Preference preference) {
@@ -541,57 +606,15 @@
// the actual speaking
speakSampleText();
return true;
- } else if (preference == mResetSpeechRate) {
- int speechRateSeekbarProgress = getSeekBarProgressFromValue(
- KEY_DEFAULT_RATE, TextToSpeech.Engine.DEFAULT_RATE);
- mDefaultRatePref.setProgress(speechRateSeekbarProgress);
- updateSpeechRate(speechRateSeekbarProgress);
- return true;
- } else if (preference == mResetSpeechPitch) {
- int pitchSeekbarProgress = getSeekBarProgressFromValue(
- KEY_DEFAULT_PITCH, TextToSpeech.Engine.DEFAULT_PITCH);
- mDefaultPitchPref.setProgress(pitchSeekbarProgress);
- updateSpeechPitchValue(pitchSeekbarProgress);
- return true;
+ } else if (preference == mInstallVoicesPreference) {
+ installVoiceData();
+ return true;
}
return false;
}
- private void updateSpeechRate(int speechRateSeekBarProgress) {
- mDefaultRate = getValueFromSeekBarProgress(KEY_DEFAULT_RATE,
- speechRateSeekBarProgress);
- try {
- android.provider.Settings.Secure.putInt(getContentResolver(),
- TTS_DEFAULT_RATE, mDefaultRate);
- if (mTts != null) {
- mTts.setSpeechRate(mDefaultRate / 100.0f);
- }
- if (DBG) Log.d(TAG, "TTS default rate changed, now " + mDefaultRate);
- } catch (NumberFormatException e) {
- Log.e(TAG, "could not persist default TTS rate setting", e);
- }
- return;
- }
-
- private void updateSpeechPitchValue(int speechPitchSeekBarProgress) {
- mDefaultPitch = getValueFromSeekBarProgress(KEY_DEFAULT_PITCH,
- speechPitchSeekBarProgress);
- try {
- android.provider.Settings.Secure.putInt(getContentResolver(),
- TTS_DEFAULT_PITCH, mDefaultPitch);
- if (mTts != null) {
- mTts.setPitch(mDefaultPitch / 100.0f);
- }
- if (DBG) Log.d(TAG, "TTS default pitch changed, now" + mDefaultPitch);
- } catch (NumberFormatException e) {
- Log.e(TAG, "could not persist default TTS pitch setting", e);
- }
- return;
- }
-
private void updateWidgetState(boolean enable) {
mPlayExample.setEnabled(enable);
- mDefaultRatePref.setEnabled(enable);
mEngineStatus.setEnabled(enable);
}
@@ -614,67 +637,7 @@
dialog.show();
}
- private void updateDefaultEngine(String engine) {
- if (DBG) Log.d(TAG, "Updating default synth to : " + engine);
-
- // Disable the "play sample text" preference and the speech
- // rate preference while the engine is being swapped.
- updateWidgetState(false);
- updateEngineStatus(R.string.tts_status_checking);
-
- // Keep track of the previous engine that was being used. So that
- // we can reuse the previous engine.
- //
- // Note that if TextToSpeech#getCurrentEngine is not null, it means at
- // the very least that we successfully bound to the engine service.
- mPreviousEngine = mTts.getCurrentEngine();
-
- // Step 1: Shut down the existing TTS engine.
- if (mTts != null) {
- try {
- mTts.shutdown();
- mTts = null;
- } catch (Exception e) {
- Log.e(TAG, "Error shutting down TTS engine" + e);
- }
- }
-
- // Step 2: Connect to the new TTS engine.
- // Step 3 is continued on #onUpdateEngine (below) which is called when
- // the app binds successfully to the engine.
- if (DBG) Log.d(TAG, "Updating engine : Attempting to connect to engine: " + engine);
- mTts = new TextToSpeech(getActivity().getApplicationContext(), mUpdateListener, engine);
- setTtsUtteranceProgressListener();
- }
-
- /*
- * Step 3: We have now bound to the TTS engine the user requested. We will
- * attempt to check voice data for the engine if we successfully bound to it,
- * or revert to the previous engine if we didn't.
- */
- public void onUpdateEngine(int status) {
- if (status == TextToSpeech.SUCCESS) {
- if (DBG) {
- Log.d(TAG, "Updating engine: Successfully bound to the engine: " +
- mTts.getCurrentEngine());
- }
- checkVoiceData(mTts.getCurrentEngine());
- } else {
- if (DBG) Log.d(TAG, "Updating engine: Failed to bind to engine, reverting.");
- if (mPreviousEngine != null) {
- // This is guaranteed to at least bind, since mPreviousEngine would be
- // null if the previous bind to this engine failed.
- mTts = new TextToSpeech(getActivity().getApplicationContext(), mInitListener,
- mPreviousEngine);
- setTtsUtteranceProgressListener();
- }
- mPreviousEngine = null;
- }
- }
-
- /*
- * Step 4: Check whether the voice data for the engine is ok.
- */
+ /** Check whether the voice data for the engine is ok. */
private void checkVoiceData(String engine) {
Intent intent = new Intent(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
intent.setPackage(engine);
@@ -686,9 +649,7 @@
}
}
- /*
- * Step 5: The voice data check is complete.
- */
+ /** The voice data check is complete. */
private void onVoiceDataIntegrityCheckDone(Intent data) {
final String engine = mTts.getCurrentEngine();
@@ -715,39 +676,5 @@
if (evaluateDefaultLocale()) {
getSampleText();
}
-
- final int engineCount = mEnginePreferenceCategory.getPreferenceCount();
- for (int i = 0; i < engineCount; ++i) {
- final Preference p = mEnginePreferenceCategory.getPreference(i);
- if (p instanceof TtsEnginePreference) {
- TtsEnginePreference enginePref = (TtsEnginePreference) p;
- if (enginePref.getKey().equals(engine)) {
- enginePref.setVoiceDataDetails(data);
- break;
- }
- }
- }
}
-
- @Override
- public Checkable getCurrentChecked() {
- return mCurrentChecked;
- }
-
- @Override
- public String getCurrentKey() {
- return mCurrentEngine;
- }
-
- @Override
- public void setCurrentChecked(Checkable current) {
- mCurrentChecked = current;
- }
-
- @Override
- public void setCurrentKey(String key) {
- mCurrentEngine = key;
- updateDefaultEngine(mCurrentEngine);
- }
-
}
diff --git a/src/com/android/settings/tts/TtsEnginePreference.java b/src/com/android/settings/tts/TtsEnginePreference.java
index 385b861..9a84002 100644
--- a/src/com/android/settings/tts/TtsEnginePreference.java
+++ b/src/com/android/settings/tts/TtsEnginePreference.java
@@ -20,19 +20,16 @@
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
-import android.os.Bundle;
import android.speech.tts.TextToSpeech.EngineInfo;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceViewHolder;
import android.util.Log;
-import android.view.View;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import com.android.settings.R;
import com.android.settings.SettingsActivity;
-import com.android.settings.Utils;
public class TtsEnginePreference extends Preference {
@@ -40,31 +37,6 @@
private static final String TAG = "TtsEnginePreference";
/**
- * Key for the name of the TTS engine passed in to the engine
- * settings fragment {@link TtsEngineSettingsFragment}.
- */
- static final String FRAGMENT_ARGS_NAME = "name";
-
- /**
- * Key for the label of the TTS engine passed in to the engine
- * settings fragment. This is used as the title of the fragment
- * {@link TtsEngineSettingsFragment}.
- */
- static final String FRAGMENT_ARGS_LABEL = "label";
-
- /**
- * Key for the voice data data passed in to the engine settings
- * fragmetn {@link TtsEngineSettingsFragment}.
- */
- static final String FRAGMENT_ARGS_VOICES = "voices";
-
- /**
- * The preference activity that owns this preference. Required
- * for instantiating the engine specific settings screen.
- */
- private final SettingsActivity mSettingsActivity;
-
- /**
* The engine information for the engine this preference represents.
* Contains it's name, label etc. which are used for display.
*/
@@ -81,7 +53,6 @@
*/
private volatile boolean mPreventRadioButtonCallbacks;
- private View mSettingsIcon;
private RadioButton mRadioButton;
private Intent mVoiceCheckData;
@@ -99,7 +70,6 @@
setLayoutResource(R.layout.preference_tts_engine);
mSharedState = state;
- mSettingsActivity = prefActivity;
mEngineInfo = info;
mPreventRadioButtonCallbacks = false;
@@ -130,52 +100,10 @@
mPreventRadioButtonCallbacks = false;
mRadioButton = rb;
-
- mSettingsIcon = view.findViewById(R.id.tts_engine_settings);
- // Will be enabled only the engine has passed the voice check, and
- // is currently enabled.
- mSettingsIcon.setEnabled(isChecked && mVoiceCheckData != null);
- if (!isChecked) {
- mSettingsIcon.setAlpha(Utils.DISABLED_ALPHA);
- }
- mSettingsIcon.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Bundle args = new Bundle();
- args.putString(FRAGMENT_ARGS_NAME, mEngineInfo.name);
- args.putString(FRAGMENT_ARGS_LABEL, mEngineInfo.label);
- if (mVoiceCheckData != null) {
- args.putParcelable(FRAGMENT_ARGS_VOICES, mVoiceCheckData);
- }
-
- // Note that we use this instead of the (easier to use)
- // SettingsActivity.startPreferenceFragment because the
- // title will not be updated correctly in the fragment
- // breadcrumb since it isn't inflated from the XML layout.
- mSettingsActivity.startPreferencePanel(
- TtsEngineSettingsFragment.class.getName(),
- args, 0, mEngineInfo.label, null, 0);
- }
- });
-
- if (mVoiceCheckData != null) {
- mSettingsIcon.setEnabled(mRadioButton.isChecked());
- }
}
public void setVoiceDataDetails(Intent data) {
mVoiceCheckData = data;
- // This might end up running before getView aboive, in which
- // case mSettingsIcon && mRadioButton will be null. In this case
- // getView will set the right values.
- if (mSettingsIcon != null && mRadioButton != null) {
- if (mRadioButton.isChecked()) {
- mSettingsIcon.setEnabled(true);
- } else {
- mSettingsIcon.setEnabled(false);
- mSettingsIcon.setAlpha(Utils.DISABLED_ALPHA);
- }
- }
}
private boolean shouldDisplayDataAlert() {
@@ -227,8 +155,6 @@
// Privileged engine, set it current
makeCurrentEngine(buttonView);
}
- } else {
- mSettingsIcon.setEnabled(false);
}
}
@@ -239,7 +165,6 @@
mSharedState.setCurrentChecked(current);
mSharedState.setCurrentKey(getKey());
callChangeListener(mSharedState.getCurrentKey());
- mSettingsIcon.setEnabled(true);
}
diff --git a/src/com/android/settings/tts/TtsEnginePreferenceFragment.java b/src/com/android/settings/tts/TtsEnginePreferenceFragment.java
new file mode 100644
index 0000000..e0ed8b7
--- /dev/null
+++ b/src/com/android/settings/tts/TtsEnginePreferenceFragment.java
@@ -0,0 +1,194 @@
+package com.android.settings.tts;
+
+import android.speech.tts.TextToSpeech;
+import com.android.settings.R;
+import android.os.Bundle;
+import com.android.settings.SettingsPreferenceFragment;
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import android.support.v7.preference.PreferenceCategory;
+import android.speech.tts.TtsEngines;
+import android.speech.tts.TextToSpeech.EngineInfo;
+import com.android.settings.SettingsActivity;
+import com.android.settings.tts.TtsEnginePreference.RadioButtonGroupState;
+import android.widget.Checkable;
+import android.util.Log;
+import static android.provider.Settings.Secure.TTS_DEFAULT_SYNTH;
+import com.android.settings.search.Indexable;
+import com.android.settings.search.BaseSearchIndexProvider;
+import android.content.Context;
+import android.provider.SearchIndexableResource;
+
+import java.util.List;
+import java.util.Arrays;
+
+public class TtsEnginePreferenceFragment extends SettingsPreferenceFragment //implements
+ implements RadioButtonGroupState, Indexable {
+ private static final String TAG = "TtsEnginePreferenceFragment";
+
+ private static final int VOICE_DATA_INTEGRITY_CHECK = 1977;
+
+ /** The currently selected engine. */
+ private String mCurrentEngine;
+
+ /**
+ * The engine checkbox that is currently checked. Saves us a bit of effort in deducing the right
+ * one from the currently selected engine.
+ */
+ private Checkable mCurrentChecked;
+
+ /**
+ * The previously selected TTS engine. Useful for rollbacks if the users choice is not loaded or
+ * fails a voice integrity check.
+ */
+ private String mPreviousEngine;
+
+ private PreferenceCategory mEnginePreferenceCategory;
+
+ private TextToSpeech mTts = null;
+ private TtsEngines mEnginesHelper = null;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ addPreferencesFromResource(R.xml.tts_engine_picker);
+
+ mEnginePreferenceCategory =
+ (PreferenceCategory) findPreference("tts_engine_preference_category");
+ mEnginesHelper = new TtsEngines(getActivity().getApplicationContext());
+
+ mTts = new TextToSpeech(getActivity().getApplicationContext(), null);
+
+ initSettings();
+ }
+
+ @Override
+ public int getMetricsCategory() {
+ return MetricsEvent.TTS_ENGINE_SETTINGS;
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ if (mTts != null) {
+ mTts.shutdown();
+ mTts = null;
+ }
+ }
+
+ private void initSettings() {
+ if (mTts != null) {
+ mCurrentEngine = mTts.getCurrentEngine();
+ }
+
+ mEnginePreferenceCategory.removeAll();
+
+ SettingsActivity activity = (SettingsActivity) getActivity();
+
+ List<EngineInfo> engines = mEnginesHelper.getEngines();
+ for (EngineInfo engine : engines) {
+ TtsEnginePreference enginePref =
+ new TtsEnginePreference(getPrefContext(), engine, this, activity);
+ mEnginePreferenceCategory.addPreference(enginePref);
+ }
+ }
+
+ @Override
+ public Checkable getCurrentChecked() {
+ return mCurrentChecked;
+ }
+
+ @Override
+ public String getCurrentKey() {
+ return mCurrentEngine;
+ }
+
+ @Override
+ public void setCurrentChecked(Checkable current) {
+ mCurrentChecked = current;
+ }
+
+ /**
+ * The initialization listener used when the user changes his choice of engine (as opposed to
+ * when then screen is being initialized for the first time).
+ */
+ private final TextToSpeech.OnInitListener mUpdateListener =
+ new TextToSpeech.OnInitListener() {
+ @Override
+ public void onInit(int status) {
+ onUpdateEngine(status);
+ }
+ };
+
+ private void updateDefaultEngine(String engine) {
+ Log.d(TAG, "Updating default synth to : " + engine);
+
+ // Keep track of the previous engine that was being used. So that
+ // we can reuse the previous engine.
+ //
+ // Note that if TextToSpeech#getCurrentEngine is not null, it means at
+ // the very least that we successfully bound to the engine service.
+ mPreviousEngine = mTts.getCurrentEngine();
+
+ // Step 1: Shut down the existing TTS engine.
+ Log.i(TAG, "Shutting down current tts engine");
+ if (mTts != null) {
+ try {
+ mTts.shutdown();
+ mTts = null;
+ } catch (Exception e) {
+ Log.e(TAG, "Error shutting down TTS engine" + e);
+ }
+ }
+
+ // Step 2: Connect to the new TTS engine.
+ // Step 3 is continued on #onUpdateEngine (below) which is called when
+ // the app binds successfully to the engine.
+ Log.i(TAG, "Updating engine : Attempting to connect to engine: " + engine);
+ mTts = new TextToSpeech(getActivity().getApplicationContext(), mUpdateListener, engine);
+ Log.i(TAG, "Success");
+ }
+
+ /**
+ * Step 3: We have now bound to the TTS engine the user requested. We will attempt to check
+ * voice data for the engine if we successfully bound to it, or revert to the previous engine if
+ * we didn't.
+ */
+ public void onUpdateEngine(int status) {
+ if (status == TextToSpeech.SUCCESS) {
+ Log.d(
+ TAG,
+ "Updating engine: Successfully bound to the engine: "
+ + mTts.getCurrentEngine());
+ android.provider.Settings.Secure.putString(
+ getContentResolver(), TTS_DEFAULT_SYNTH, mTts.getCurrentEngine());
+ } else {
+ Log.d(TAG, "Updating engine: Failed to bind to engine, reverting.");
+ if (mPreviousEngine != null) {
+ // This is guaranteed to at least bind, since mPreviousEngine would be
+ // null if the previous bind to this engine failed.
+ mTts =
+ new TextToSpeech(
+ getActivity().getApplicationContext(), null, mPreviousEngine);
+ }
+ mPreviousEngine = null;
+ }
+ }
+
+ @Override
+ public void setCurrentKey(String key) {
+ mCurrentEngine = key;
+ updateDefaultEngine(mCurrentEngine);
+ }
+
+ public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+ new BaseSearchIndexProvider() {
+ @Override
+ public List<SearchIndexableResource> getXmlResourcesToIndex(
+ Context context, boolean enabled) {
+ Log.i(TAG, "Indexing");
+ final SearchIndexableResource sir = new SearchIndexableResource(context);
+ sir.xmlResId = R.xml.tts_engine_picker;
+ return Arrays.asList(sir);
+ }
+ };
+}
diff --git a/src/com/android/settings/tts/TtsEngineSettingsFragment.java b/src/com/android/settings/tts/TtsEngineSettingsFragment.java
deleted file mode 100644
index 42222df..0000000
--- a/src/com/android/settings/tts/TtsEngineSettingsFragment.java
+++ /dev/null
@@ -1,370 +0,0 @@
-/*
- * 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.
- */
-
-package com.android.settings.tts;
-
-import android.content.ActivityNotFoundException;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.os.Bundle;
-import android.speech.tts.TextToSpeech;
-import android.speech.tts.TtsEngines;
-import android.support.v7.preference.ListPreference;
-import android.support.v7.preference.Preference;
-import android.support.v7.preference.Preference.OnPreferenceChangeListener;
-import android.support.v7.preference.Preference.OnPreferenceClickListener;
-import android.support.v7.preference.PreferenceScreen;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.Pair;
-
-import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
-import com.android.settings.R;
-import com.android.settings.SettingsPreferenceFragment;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Locale;
-
-
-public class TtsEngineSettingsFragment extends SettingsPreferenceFragment implements
- OnPreferenceClickListener, OnPreferenceChangeListener {
- private static final String TAG = "TtsEngineSettings";
- private static final boolean DBG = false;
-
- private static final String KEY_ENGINE_LOCALE = "tts_default_lang";
- private static final String KEY_ENGINE_SETTINGS = "tts_engine_settings";
- private static final String KEY_INSTALL_DATA = "tts_install_data";
-
- private static final String STATE_KEY_LOCALE_ENTRIES = "locale_entries";
- private static final String STATE_KEY_LOCALE_ENTRY_VALUES= "locale_entry_values";
- private static final String STATE_KEY_LOCALE_VALUE = "locale_value";
-
- private static final int VOICE_DATA_INTEGRITY_CHECK = 1977;
-
- private TtsEngines mEnginesHelper;
- private ListPreference mLocalePreference;
- private Preference mEngineSettingsPreference;
- private Preference mInstallVoicesPreference;
- private Intent mEngineSettingsIntent;
- private Intent mVoiceDataDetails;
-
- private TextToSpeech mTts;
-
- private int mSelectedLocaleIndex = -1;
-
- private final TextToSpeech.OnInitListener mTtsInitListener = new TextToSpeech.OnInitListener() {
- @Override
- public void onInit(int status) {
- if (status != TextToSpeech.SUCCESS) {
- finishFragment();
- } else {
- getActivity().runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mLocalePreference.setEnabled(true);
- }
- });
- }
- }
- };
-
- private final BroadcastReceiver mLanguagesChangedReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- // Installed or uninstalled some data packs
- if (TextToSpeech.Engine.ACTION_TTS_DATA_INSTALLED.equals(intent.getAction())) {
- checkTtsData();
- }
- }
- };
-
- public TtsEngineSettingsFragment() {
- super();
- }
-
- @Override
- public int getMetricsCategory() {
- return MetricsEvent.TTS_ENGINE_SETTINGS;
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- addPreferencesFromResource(R.xml.tts_engine_settings);
- mEnginesHelper = new TtsEngines(getActivity());
-
- final PreferenceScreen root = getPreferenceScreen();
- mLocalePreference = (ListPreference) root.findPreference(KEY_ENGINE_LOCALE);
- mLocalePreference.setOnPreferenceChangeListener(this);
- mEngineSettingsPreference = root.findPreference(KEY_ENGINE_SETTINGS);
- mEngineSettingsPreference.setOnPreferenceClickListener(this);
- mInstallVoicesPreference = root.findPreference(KEY_INSTALL_DATA);
- mInstallVoicesPreference.setOnPreferenceClickListener(this);
-
- root.setTitle(getEngineLabel());
- root.setKey(getEngineName());
- mEngineSettingsPreference.setTitle(getResources().getString(
- R.string.tts_engine_settings_title, getEngineLabel()));
-
- mEngineSettingsIntent = mEnginesHelper.getSettingsIntent(getEngineName());
- if (mEngineSettingsIntent == null) {
- mEngineSettingsPreference.setEnabled(false);
- }
- mInstallVoicesPreference.setEnabled(false);
-
- if (savedInstanceState == null) {
- mLocalePreference.setEnabled(false);
- mLocalePreference.setEntries(new CharSequence[0]);
- mLocalePreference.setEntryValues(new CharSequence[0]);
- } else {
- // Repopulate mLocalePreference with saved state. Will be updated later with
- // up-to-date values when checkTtsData() calls back with results.
- final CharSequence[] entries =
- savedInstanceState.getCharSequenceArray(STATE_KEY_LOCALE_ENTRIES);
- final CharSequence[] entryValues =
- savedInstanceState.getCharSequenceArray(STATE_KEY_LOCALE_ENTRY_VALUES);
- final CharSequence value =
- savedInstanceState.getCharSequence(STATE_KEY_LOCALE_VALUE);
-
- mLocalePreference.setEntries(entries);
- mLocalePreference.setEntryValues(entryValues);
- mLocalePreference.setValue(value != null ? value.toString() : null);
- mLocalePreference.setEnabled(entries.length > 0);
- }
-
- mVoiceDataDetails = getArguments().getParcelable(TtsEnginePreference.FRAGMENT_ARGS_VOICES);
-
- mTts = new TextToSpeech(getActivity().getApplicationContext(), mTtsInitListener,
- getEngineName());
-
- // Check if data packs changed
- checkTtsData();
-
- getActivity().registerReceiver(mLanguagesChangedReceiver,
- new IntentFilter(TextToSpeech.Engine.ACTION_TTS_DATA_INSTALLED));
- }
-
- @Override
- public void onDestroy() {
- getActivity().unregisterReceiver(mLanguagesChangedReceiver);
- mTts.shutdown();
- super.onDestroy();
- }
-
- @Override
- public void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
-
- // Save the mLocalePreference values, so we can repopulate it with entries.
- outState.putCharSequenceArray(STATE_KEY_LOCALE_ENTRIES,
- mLocalePreference.getEntries());
- outState.putCharSequenceArray(STATE_KEY_LOCALE_ENTRY_VALUES,
- mLocalePreference.getEntryValues());
- outState.putCharSequence(STATE_KEY_LOCALE_VALUE,
- mLocalePreference.getValue());
- }
-
- private final void checkTtsData() {
- Intent intent = new Intent(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
- intent.setPackage(getEngineName());
- try {
- if (DBG) Log.d(TAG, "Updating engine: Checking voice data: " + intent.toUri(0));
- startActivityForResult(intent, VOICE_DATA_INTEGRITY_CHECK);
- } catch (ActivityNotFoundException ex) {
- Log.e(TAG, "Failed to check TTS data, no activity found for " + intent + ")");
- }
- }
-
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
- if (resultCode != TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL) {
- updateVoiceDetails(data);
- } else {
- Log.e(TAG, "CheckVoiceData activity failed");
- }
- }
- }
-
- private void updateVoiceDetails(Intent data) {
- if (data == null){
- Log.e(TAG, "Engine failed voice data integrity check (null return)" +
- mTts.getCurrentEngine());
- return;
- }
- mVoiceDataDetails = data;
-
- if (DBG) Log.d(TAG, "Parsing voice data details, data: " + mVoiceDataDetails.toUri(0));
-
- final ArrayList<String> available = mVoiceDataDetails.getStringArrayListExtra(
- TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
- final ArrayList<String> unavailable = mVoiceDataDetails.getStringArrayListExtra(
- TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES);
-
- if (unavailable != null && unavailable.size() > 0) {
- mInstallVoicesPreference.setEnabled(true);
- } else {
- mInstallVoicesPreference.setEnabled(false);
- }
-
- if (available == null){
- Log.e(TAG, "TTS data check failed (available == null).");
- mLocalePreference.setEnabled(false);
- return;
- } else {
- updateDefaultLocalePref(available);
- }
- }
-
- private void updateDefaultLocalePref(ArrayList<String> availableLangs) {
- if (availableLangs == null || availableLangs.size() == 0) {
- mLocalePreference.setEnabled(false);
- return;
- }
- Locale currentLocale = null;
- if (!mEnginesHelper.isLocaleSetToDefaultForEngine(getEngineName())) {
- currentLocale = mEnginesHelper.getLocalePrefForEngine(getEngineName());
- }
-
- ArrayList<Pair<String, Locale>> entryPairs =
- new ArrayList<Pair<String, Locale>>(availableLangs.size());
- for (int i = 0; i < availableLangs.size(); i++) {
- Locale locale = mEnginesHelper.parseLocaleString(availableLangs.get(i));
- if (locale != null){
- entryPairs.add(new Pair<String, Locale>(
- locale.getDisplayName(), locale));
- }
- }
-
- // Sort it
- Collections.sort(entryPairs, new Comparator<Pair<String, Locale>>() {
- @Override
- public int compare(Pair<String, Locale> lhs, Pair<String, Locale> rhs) {
- return lhs.first.compareToIgnoreCase(rhs.first);
- }
- });
-
- // Get two arrays out of one of pairs
- mSelectedLocaleIndex = 0; // Will point to the R.string.tts_lang_use_system value
- CharSequence[] entries = new CharSequence[availableLangs.size()+1];
- CharSequence[] entryValues = new CharSequence[availableLangs.size()+1];
-
- entries[0] = getActivity().getString(R.string.tts_lang_use_system);
- entryValues[0] = "";
-
- int i = 1;
- for (Pair<String, Locale> entry : entryPairs) {
- if (entry.second.equals(currentLocale)) {
- mSelectedLocaleIndex = i;
- }
- entries[i] = entry.first;
- entryValues[i++] = entry.second.toString();
- }
-
- mLocalePreference.setEntries(entries);
- mLocalePreference.setEntryValues(entryValues);
- mLocalePreference.setEnabled(true);
- setLocalePreference(mSelectedLocaleIndex);
- }
-
- /** Set entry from entry table in mLocalePreference */
- private void setLocalePreference(int index) {
- if (index < 0) {
- mLocalePreference.setValue("");
- mLocalePreference.setSummary(R.string.tts_lang_not_selected);
- } else {
- mLocalePreference.setValueIndex(index);
- mLocalePreference.setSummary(mLocalePreference.getEntries()[index]);
- }
- }
-
- /**
- * Ask the current default engine to launch the matching INSTALL_TTS_DATA activity
- * so the required TTS files are properly installed.
- */
- private void installVoiceData() {
- if (TextUtils.isEmpty(getEngineName())) return;
- Intent intent = new Intent(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
- intent.setPackage(getEngineName());
- try {
- Log.v(TAG, "Installing voice data: " + intent.toUri(0));
- startActivity(intent);
- } catch (ActivityNotFoundException ex) {
- Log.e(TAG, "Failed to install TTS data, no acitivty found for " + intent + ")");
- }
- }
-
- @Override
- public boolean onPreferenceClick(Preference preference) {
- if (preference == mInstallVoicesPreference) {
- installVoiceData();
- return true;
- } else if (preference == mEngineSettingsPreference) {
- startActivity(mEngineSettingsIntent);
- return true;
- }
-
- return false;
- }
-
- @Override
- public boolean onPreferenceChange(Preference preference, Object newValue) {
- if (preference == mLocalePreference) {
- String localeString = (String) newValue;
- updateLanguageTo((!TextUtils.isEmpty(localeString) ?
- mEnginesHelper.parseLocaleString(localeString) : null));
- return true;
- }
- return false;
- }
-
- private void updateLanguageTo(Locale locale) {
- int selectedLocaleIndex = -1;
- String localeString = (locale != null) ? locale.toString() : "";
- for (int i=0; i < mLocalePreference.getEntryValues().length; i++) {
- if (localeString.equalsIgnoreCase(mLocalePreference.getEntryValues()[i].toString())) {
- selectedLocaleIndex = i;
- break;
- }
- }
-
- if (selectedLocaleIndex == -1) {
- Log.w(TAG, "updateLanguageTo called with unknown locale argument");
- return;
- }
- mLocalePreference.setSummary(mLocalePreference.getEntries()[selectedLocaleIndex]);
- mSelectedLocaleIndex = selectedLocaleIndex;
-
- mEnginesHelper.updateLocalePrefForEngine(getEngineName(), locale);
-
- if (getEngineName().equals(mTts.getCurrentEngine())) {
- // Null locale means "use system default"
- mTts.setLanguage((locale != null) ? locale : Locale.getDefault());
- }
- }
-
- private String getEngineName() {
- return getArguments().getString(TtsEnginePreference.FRAGMENT_ARGS_NAME);
- }
-
- private String getEngineLabel() {
- return getArguments().getString(TtsEnginePreference.FRAGMENT_ARGS_LABEL);
- }
-}
diff --git a/src/com/android/settings/tts/TtsSlidersFragment.java b/src/com/android/settings/tts/TtsSlidersFragment.java
new file mode 100644
index 0000000..7fdbd62
--- /dev/null
+++ b/src/com/android/settings/tts/TtsSlidersFragment.java
@@ -0,0 +1,207 @@
+package com.android.settings.tts;
+
+import android.speech.tts.TextToSpeech;
+import com.android.settings.R;
+import android.os.Bundle;
+import com.android.settings.SettingsPreferenceFragment;
+import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import android.util.Log;
+import com.android.settings.SeekBarPreference;
+import android.support.v7.preference.Preference;
+import android.content.ContentResolver;
+import com.android.settings.search.Indexable;
+import com.android.settings.search.BaseSearchIndexProvider;
+import android.content.Context;
+import android.provider.SearchIndexableResource;
+
+import java.util.List;
+import java.util.Arrays;
+
+import static android.provider.Settings.Secure.TTS_DEFAULT_PITCH;
+import static android.provider.Settings.Secure.TTS_DEFAULT_RATE;
+
+public class TtsSlidersFragment extends SettingsPreferenceFragment
+ implements Preference.OnPreferenceChangeListener,
+ Preference.OnPreferenceClickListener,
+ Indexable {
+ private static final String TAG = TtsSlidersFragment.class.getSimpleName();
+ private static final boolean DBG = false;
+
+ /** Preference key for the TTS pitch selection slider. */
+ private static final String KEY_DEFAULT_PITCH = "tts_default_pitch";
+
+ /** Preference key for the TTS rate selection slider. */
+ private static final String KEY_DEFAULT_RATE = "tts_default_rate";
+
+ /** Preference key for the TTS reset speech rate preference. */
+ private static final String KEY_RESET_SPEECH_RATE = "reset_speech_rate";
+
+ /** Preference key for the TTS reset speech pitch preference. */
+ private static final String KEY_RESET_SPEECH_PITCH = "reset_speech_pitch";
+
+ /**
+ * Speech rate value. This value should be kept in sync with the max value set in tts_settings
+ * xml.
+ */
+ private static final int MAX_SPEECH_RATE = 600;
+
+ private static final int MIN_SPEECH_RATE = 10;
+
+ /**
+ * Speech pitch value. TTS pitch value varies from 25 to 400, where 100 is the value for normal
+ * pitch. The max pitch value is set to 400, based on feedback from users and the GoogleTTS
+ * pitch variation range. The range for pitch is not set in stone and should be readjusted based
+ * on user need. This value should be kept in sync with the max value set in tts_settings xml.
+ */
+ private static final int MAX_SPEECH_PITCH = 400;
+
+ private static final int MIN_SPEECH_PITCH = 25;
+
+ private int mDefaultPitch = TextToSpeech.Engine.DEFAULT_PITCH;
+ private int mDefaultRate = TextToSpeech.Engine.DEFAULT_RATE;
+
+ private SeekBarPreference mDefaultPitchPref;
+ private SeekBarPreference mDefaultRatePref;
+ private Preference mResetSpeechRate;
+ private Preference mResetSpeechPitch;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ addPreferencesFromResource(R.xml.tts_sliders);
+
+ mResetSpeechRate = findPreference(KEY_RESET_SPEECH_RATE);
+ mResetSpeechRate.setOnPreferenceClickListener(this);
+ mResetSpeechPitch = findPreference(KEY_RESET_SPEECH_PITCH);
+ mResetSpeechPitch.setOnPreferenceClickListener(this);
+
+ mDefaultPitchPref = (SeekBarPreference) findPreference(KEY_DEFAULT_PITCH);
+ mDefaultRatePref = (SeekBarPreference) findPreference(KEY_DEFAULT_RATE);
+
+ initSettings();
+ }
+
+ private void initSettings() {
+ final ContentResolver resolver = getContentResolver();
+ // Set up the default rate and pitch.
+ mDefaultRate =
+ android.provider.Settings.Secure.getInt(
+ resolver, TTS_DEFAULT_RATE, TextToSpeech.Engine.DEFAULT_RATE);
+ mDefaultPitch =
+ android.provider.Settings.Secure.getInt(
+ resolver, TTS_DEFAULT_PITCH, TextToSpeech.Engine.DEFAULT_PITCH);
+
+ mDefaultRatePref.setProgress(getSeekBarProgressFromValue(KEY_DEFAULT_RATE, mDefaultRate));
+ mDefaultRatePref.setOnPreferenceChangeListener(this);
+ mDefaultRatePref.setMax(getSeekBarProgressFromValue(KEY_DEFAULT_RATE, MAX_SPEECH_RATE));
+
+ mDefaultPitchPref.setProgress(
+ getSeekBarProgressFromValue(KEY_DEFAULT_PITCH, mDefaultPitch));
+ mDefaultPitchPref.setOnPreferenceChangeListener(this);
+ mDefaultPitchPref.setMax(getSeekBarProgressFromValue(KEY_DEFAULT_PITCH, MAX_SPEECH_PITCH));
+ }
+
+ /**
+ * The minimum speech pitch/rate value should be > 0 but the minimum value of a seekbar in
+ * android is fixed at 0. Therefore, we increment the seekbar progress with MIN_SPEECH_VALUE so
+ * that the minimum seekbar progress value is MIN_SPEECH_PITCH/RATE. SPEECH_VALUE =
+ * MIN_SPEECH_VALUE + SEEKBAR_PROGRESS
+ */
+ private int getValueFromSeekBarProgress(String preferenceKey, int progress) {
+ if (preferenceKey.equals(KEY_DEFAULT_RATE)) {
+ return MIN_SPEECH_RATE + progress;
+ } else if (preferenceKey.equals(KEY_DEFAULT_PITCH)) {
+ return MIN_SPEECH_PITCH + progress;
+ }
+ return progress;
+ }
+
+ /**
+ * Since we are appending the MIN_SPEECH value to the speech seekbar progress, the speech
+ * seekbar progress should be set to (speechValue - MIN_SPEECH value).
+ */
+ private int getSeekBarProgressFromValue(String preferenceKey, int value) {
+ if (preferenceKey.equals(KEY_DEFAULT_RATE)) {
+ return value - MIN_SPEECH_RATE;
+ } else if (preferenceKey.equals(KEY_DEFAULT_PITCH)) {
+ return value - MIN_SPEECH_PITCH;
+ }
+ return value;
+ }
+
+ @Override
+ public boolean onPreferenceChange(Preference preference, Object objValue) {
+ if (KEY_DEFAULT_RATE.equals(preference.getKey())) {
+ updateSpeechRate((Integer) objValue);
+ } else if (KEY_DEFAULT_PITCH.equals(preference.getKey())) {
+ updateSpeechPitchValue((Integer) objValue);
+ }
+ return true;
+ }
+
+ /** Called when mPlayExample, mResetSpeechRate or mResetSpeechPitch is clicked. */
+ @Override
+ public boolean onPreferenceClick(Preference preference) {
+ if (preference == mResetSpeechRate) {
+ int speechRateSeekbarProgress =
+ getSeekBarProgressFromValue(KEY_DEFAULT_RATE, TextToSpeech.Engine.DEFAULT_RATE);
+ mDefaultRatePref.setProgress(speechRateSeekbarProgress);
+ updateSpeechRate(speechRateSeekbarProgress);
+ return true;
+ } else if (preference == mResetSpeechPitch) {
+ int pitchSeekbarProgress =
+ getSeekBarProgressFromValue(
+ KEY_DEFAULT_PITCH, TextToSpeech.Engine.DEFAULT_PITCH);
+ mDefaultPitchPref.setProgress(pitchSeekbarProgress);
+ updateSpeechPitchValue(pitchSeekbarProgress);
+ return true;
+ }
+ return false;
+ }
+
+ private void updateSpeechRate(int speechRateSeekBarProgress) {
+ mDefaultRate = getValueFromSeekBarProgress(KEY_DEFAULT_RATE, speechRateSeekBarProgress);
+ try {
+ android.provider.Settings.Secure.putInt(
+ getContentResolver(), TTS_DEFAULT_RATE, mDefaultRate);
+ if (DBG) Log.d(TAG, "TTS default rate changed, now " + mDefaultRate);
+ } catch (NumberFormatException e) {
+ Log.e(TAG, "could not persist default TTS rate setting", e);
+ }
+ return;
+ }
+
+ private void updateSpeechPitchValue(int speechPitchSeekBarProgress) {
+ mDefaultPitch = getValueFromSeekBarProgress(KEY_DEFAULT_PITCH, speechPitchSeekBarProgress);
+ try {
+ android.provider.Settings.Secure.putInt(
+ getContentResolver(), TTS_DEFAULT_PITCH, mDefaultPitch);
+ if (DBG) Log.d(TAG, "TTS default pitch changed, now" + mDefaultPitch);
+ } catch (NumberFormatException e) {
+ Log.e(TAG, "could not persist default TTS pitch setting", e);
+ }
+ return;
+ }
+
+ @Override
+ public void onDestroy() {
+ super.onDestroy();
+ }
+
+ @Override
+ public int getMetricsCategory() {
+ return MetricsEvent.TTS_SLIDERS;
+ }
+
+ public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+ new BaseSearchIndexProvider() {
+ @Override
+ public List<SearchIndexableResource> getXmlResourcesToIndex(
+ Context context, boolean enabled) {
+ Log.i(TAG, "Indexing");
+ final SearchIndexableResource sir = new SearchIndexableResource(context);
+ sir.xmlResId = R.xml.tts_sliders;
+ return Arrays.asList(sir);
+ }
+ };
+}
diff --git a/src/com/android/settings/webview/WebViewAppListAdapter.java b/src/com/android/settings/webview/WebViewAppListAdapter.java
index 85dbf7c..4c36a47 100644
--- a/src/com/android/settings/webview/WebViewAppListAdapter.java
+++ b/src/com/android/settings/webview/WebViewAppListAdapter.java
@@ -16,8 +16,10 @@
import android.content.Context;
import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.RemoteException;
+import android.graphics.Color;
import android.support.annotation.VisibleForTesting;
import android.view.LayoutInflater;
import android.view.View;
@@ -36,6 +38,7 @@
*/
class WebViewAppListAdapter extends ArrayAdapter<WebViewApplicationInfo> {
private final LayoutInflater mInflater;
+ private final String mCurrentWebViewPackageName;
public WebViewAppListAdapter(Context context,
WebViewUpdateServiceWrapper webviewUpdateServiceWrapper) {
@@ -53,6 +56,10 @@
packageInfoList.add(info);
}
addAll(packageInfoList);
+
+ PackageInfo currentWebViewPackage = webviewUpdateServiceWrapper.getCurrentWebViewPackage();
+ mCurrentWebViewPackageName =
+ currentWebViewPackage == null ? null : currentWebViewPackage.packageName;
}
@Override
@@ -80,6 +87,11 @@
holder.disabled.setVisibility(View.GONE);
// Only allow a package to be chosen if it is enabled and installed for all users.
convertView.setEnabled(isEnabled(position));
+ if (info.info.packageName.equals(mCurrentWebViewPackageName)) {
+ convertView.setBackgroundColor(Color.GRAY);
+ } else {
+ convertView.setBackgroundColor(Color.WHITE);
+ }
return convertView;
}
diff --git a/src/com/android/settings/webview/WebViewAppPreferenceController.java b/src/com/android/settings/webview/WebViewAppPreferenceController.java
index eb5467a..cfb358e 100644
--- a/src/com/android/settings/webview/WebViewAppPreferenceController.java
+++ b/src/com/android/settings/webview/WebViewAppPreferenceController.java
@@ -73,9 +73,10 @@
* Handle the return-value from the WebViewAppPicker Activity.
*/
public void onActivityResult(int resultCode, Intent data) {
- if (resultCode == Activity.RESULT_OK) {
- updateState(null);
- }
+ // Update the preference summary no matter whether we succeeded to change the webview
+ // implementation correctly - we might have changed implementation to one the user did not
+ // choose.
+ updateState(null);
}
private String getCurrentWebViewPackageLabel(Context context) {
diff --git a/tests/robotests/assets/grandfather_not_implementing_indexable b/tests/robotests/assets/grandfather_not_implementing_indexable
index d774779..33484d1 100644
--- a/tests/robotests/assets/grandfather_not_implementing_indexable
+++ b/tests/robotests/assets/grandfather_not_implementing_indexable
@@ -50,6 +50,7 @@
com.android.settings.print.PrintJobSettingsFragment
com.android.settings.applications.SpecialAccessSettings
com.android.settings.accessibility.ToggleScreenReaderPreferenceFragmentForSetupWizard
+com.android.settings.accessibility.ToggleSelectToSpeakPreferenceFragmentForSetupWizard
com.android.settings.accounts.AccountSyncSettings
com.android.settings.notification.RedactionInterstitial$RedactionInterstitialFragment
com.android.settings.inputmethod.InputMethodAndSubtypeEnabler
diff --git a/tests/robotests/src/com/android/settings/BackupSettingsHelperTest.java b/tests/robotests/src/com/android/settings/BackupSettingsHelperTest.java
deleted file mode 100644
index b14debc..0000000
--- a/tests/robotests/src/com/android/settings/BackupSettingsHelperTest.java
+++ /dev/null
@@ -1,188 +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;
-
-import android.app.backup.BackupManager;
-import android.app.backup.IBackupManager;
-import android.content.ComponentName;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.os.IBinder;
-import android.os.RemoteException;
-
-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.annotation.Implementation;
-import org.robolectric.annotation.Implements;
-
-import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-
-
-
-@RunWith(SettingsRobolectricTestRunner.class)
-@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION,
- shadows = {BackupSettingsHelperTest.ShadowBackupManagerStub.class})
-public class BackupSettingsHelperTest {
-
- private BackupSettingsHelper mBackupSettingsHelper;
-
- @Mock
- private static IBackupManager mBackupManager;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
- when(mBackupManager.getCurrentTransport()).thenReturn("test_transport");
- mBackupSettingsHelper = new BackupSettingsHelper();
- }
-
- @Test
- public void testGetIntentFromBackupTransport() throws Exception {
- Intent intent = new Intent();
-
- when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
-
- Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettings();
-
- verify(mBackupManager).getDataManagementIntent(anyString());
- }
-
- @Test
- public void testGetIntentFromBackupTransport_WithIntent() throws Exception {
- Intent intent = mock(Intent.class);
-
- when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
-
- Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettings();
-
- assertThat(backupIntent).isEqualTo(intent);
- }
-
- @Test
- public void testGetIntentFromBackupTransport_WithNullIntent() throws Exception {
- when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(null);
-
- Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettings();
-
- assertThat(backupIntent).isNull();
- }
-
- @Test
- public void testGetIntentFromBackupTransport_RemoteException() throws Exception {
- when(mBackupManager.getDataManagementIntent(anyString())).thenThrow(new RemoteException());
-
- Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettings();
-
- assertThat(backupIntent).isNull();
- }
-
- @Test
- public void testGetIntentFromBackupTransport_BackupEnabled() throws Exception {
- Intent intent = new Intent("test_intent");
-
- when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
- when(mBackupManager.isBackupServiceActive(anyInt())).thenReturn(true);
-
- Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettings();
-
- assertThat(backupIntent.getExtras().get(BackupManager.EXTRA_BACKUP_SERVICES_AVAILABLE))
- .isEqualTo(true);
- }
-
- @Test
- public void testGetIntentFromBackupTransport_BackupDisabled() throws Exception {
- Intent intent = new Intent("test_intent");
-
- when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
- when(mBackupManager.isBackupServiceActive(anyInt())).thenReturn(false);
-
- Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettings();
-
- assertThat(backupIntent.getExtras().get(BackupManager.EXTRA_BACKUP_SERVICES_AVAILABLE))
- .isEqualTo(false);
- }
-
- @Test
- public void testGetIntentFromBackupTransport_BackupStatusException() throws Exception {
- Intent intent = new Intent("test_intent");
-
- when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
- when(mBackupManager.isBackupServiceActive(anyInt())).thenThrow(new RemoteException());
-
- Intent backupIntent = mBackupSettingsHelper.getIntentForBackupSettings();
-
- assertThat(backupIntent.getExtras().get(BackupManager.EXTRA_BACKUP_SERVICES_AVAILABLE))
- .isEqualTo(false);
- }
-
- @Test
- public void testIsIntentProvidedByTransport_WithNullIntent() throws Exception {
- when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(null);
-
- PackageManager packageManager = mock(PackageManager.class);
-
- boolean isIntentProvided = mBackupSettingsHelper.isIntentProvidedByTransport(packageManager);
-
- assertThat(isIntentProvided).isFalse();
- }
-
- @Test
- public void testIsIntentProvidedByTransport_WithInvalidIntent() throws Exception {
- Intent intent = mock(Intent.class);
-
- when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
-
- PackageManager packageManager = mock(PackageManager.class);
- when(intent.resolveActivity(packageManager)).thenReturn(null);
-
- boolean isIntentProvided = mBackupSettingsHelper.isIntentProvidedByTransport(packageManager);
-
- assertThat(isIntentProvided).isFalse();
- }
-
- @Test
- public void testIsIntentProvidedByTransport_WithIntent() throws Exception {
- Intent intent = mock(Intent.class);
-
- when(mBackupManager.getDataManagementIntent(anyString())).thenReturn(intent);
-
- PackageManager packageManager = mock(PackageManager.class);
- when(intent.resolveActivity(packageManager)).thenReturn(mock(ComponentName.class));
-
- boolean isIntentProvided = mBackupSettingsHelper.isIntentProvidedByTransport(packageManager);
-
- assertThat(isIntentProvided).isTrue();
- }
-
- @Implements(IBackupManager.Stub.class)
- public static class ShadowBackupManagerStub {
- @Implementation
- public static IBackupManager asInterface(IBinder iBinder) {
- return mBackupManager;
- }
- }
-}
diff --git a/tests/robotests/src/com/android/settings/SecuritySettingsTest.java b/tests/robotests/src/com/android/settings/SecuritySettingsTest.java
index af853dc..92214e3 100644
--- a/tests/robotests/src/com/android/settings/SecuritySettingsTest.java
+++ b/tests/robotests/src/com/android/settings/SecuritySettingsTest.java
@@ -144,7 +144,7 @@
public void testGetPackageVerifierSummary_matchingTile() {
when(mDashboardCategory.getTilesCount()).thenReturn(1);
Tile tile = new Tile();
- tile.key = SecuritySettings.KEY_PACKAGE_VERIFIER_STATE;
+ tile.key = SecuritySettings.KEY_PACKAGE_VERIFIER_STATUS;
Bundle bundle = new Bundle();
bundle.putString(TileUtils.META_DATA_PREFERENCE_SUMMARY_URI, "content://host/path");
tile.metaData = bundle;
diff --git a/tests/robotests/src/com/android/settings/deviceinfo/StorageDashboardFragmentTest.java b/tests/robotests/src/com/android/settings/deviceinfo/StorageDashboardFragmentTest.java
index 5775aeb..f16304e 100644
--- a/tests/robotests/src/com/android/settings/deviceinfo/StorageDashboardFragmentTest.java
+++ b/tests/robotests/src/com/android/settings/deviceinfo/StorageDashboardFragmentTest.java
@@ -16,6 +16,10 @@
package com.android.settings.deviceinfo;
import android.content.Context;
+import android.os.Bundle;
+import android.os.storage.DiskInfo;
+import android.os.storage.StorageManager;
+import android.os.storage.VolumeInfo;
import android.provider.SearchIndexableResource;
import com.android.settings.SettingsRobolectricTestRunner;
@@ -35,15 +39,19 @@
import java.util.List;
import static com.google.common.truth.Truth.assertThat;
+
+import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class StorageDashboardFragmentTest {
-
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Context mContext;
+ @Mock(answer = Answers.RETURNS_DEEP_STUBS)
+ private StorageManager mStorageManager;
+
private StorageDashboardFragment mFragment;
@Before
@@ -71,4 +79,11 @@
assertThat(indexRes).isNotNull();
assertThat(indexRes.get(0).xmlResId).isEqualTo(mFragment.getPreferenceScreenResId());
}
+
+ @Test
+ public void testInitializeVolumeDoesntBreakOnNullVolume() {
+ VolumeInfo info = new VolumeInfo("id", 0, new DiskInfo("id", 0), "");
+ when(mStorageManager.findVolumeById(anyString())).thenReturn(info);
+ mFragment.initializeVolume(mStorageManager, new Bundle());
+ }
}
\ No newline at end of file
diff --git a/tests/robotests/src/com/android/settings/fuelgauge/BatterySaverControllerTest.java b/tests/robotests/src/com/android/settings/fuelgauge/BatterySaverControllerTest.java
new file mode 100644
index 0000000..9656381
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/fuelgauge/BatterySaverControllerTest.java
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.android.settings.fuelgauge;
+
+import android.content.Context;
+import android.os.PowerManager;
+import com.android.settings.SettingsRobolectricTestRunner;
+import com.android.settings.TestConfig;
+import com.android.settings.core.lifecycle.Lifecycle;
+import com.android.settings.widget.MasterSwitchPreference;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.annotation.Config;
+import org.robolectric.util.ReflectionHelpers;
+
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@RunWith(SettingsRobolectricTestRunner.class)
+@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
+public class BatterySaverControllerTest {
+ @Mock
+ private MasterSwitchPreference mBatterySaverPref;
+ @Mock
+ private PowerManager mPowerManager;
+ @Mock
+ private Context mContext;
+ @Mock
+ private Lifecycle mLifecycle;
+ private BatterySaverController mBatterySaverController;
+
+ @Before
+ public void setUp() {
+ MockitoAnnotations.initMocks(this);
+
+ mBatterySaverController = spy(new BatterySaverController(mContext, mLifecycle));
+ ReflectionHelpers.setField(mBatterySaverController, "mPowerManager", mPowerManager);
+ ReflectionHelpers.setField(mBatterySaverController, "mBatterySaverPref", mBatterySaverPref);
+ doNothing().when(mBatterySaverController).refreshConditionManager();
+ }
+
+ @Test
+ public void testOnPreferenceChange_TurnOnBatterySaver_BatterySaverOn() {
+ testOnPreferenceChangeInner(true);
+ }
+
+ @Test
+ public void testOnPreferenceChange_TurnOffBatterySaver_BatterySaverOff() {
+ testOnPreferenceChangeInner(false);
+ }
+
+ @Test
+ public void testUpdateState_SaverModeOn_PreferenceChecked() {
+ testUpdateStateInner(true);
+ }
+
+ @Test
+ public void testUpdateState_SaverModeOff_PreferenceUnChecked() {
+ testUpdateStateInner(false);
+ }
+
+ private void testOnPreferenceChangeInner(final boolean saverOn) {
+ when(mPowerManager.setPowerSaveMode(saverOn)).thenReturn(true);
+ when(mPowerManager.isPowerSaveMode()).thenReturn(!saverOn);
+
+ mBatterySaverController.onPreferenceChange(mBatterySaverPref, saverOn);
+ verify(mPowerManager).setPowerSaveMode(saverOn);
+ }
+
+ private void testUpdateStateInner(final boolean saverOn) {
+ when(mPowerManager.isPowerSaveMode()).thenReturn(saverOn);
+
+ mBatterySaverController.updateState(mBatterySaverPref);
+ verify(mBatterySaverPref).setChecked(saverOn);
+ }
+}
diff --git a/tests/robotests/src/com/android/settings/search/DatabaseResultLoaderTest.java b/tests/robotests/src/com/android/settings/search/DatabaseResultLoaderTest.java
index 31e6e6c..6368fcb 100644
--- a/tests/robotests/src/com/android/settings/search/DatabaseResultLoaderTest.java
+++ b/tests/robotests/src/com/android/settings/search/DatabaseResultLoaderTest.java
@@ -144,6 +144,62 @@
assertThat(loader.loadInBackground().size()).isEqualTo(1);
}
+ @Test
+ public void testSpecialCasePrefix_MatchesPrefixOfEntry() {
+ insertSpecialCase("Photos");
+ loader = new DatabaseResultLoader(mContext, "pho");
+ assertThat(loader.loadInBackground().size()).isEqualTo(1);
+ }
+
+ @Test
+ public void testSpecialCasePrefix_DoesNotMatchNonPrefixSubstring() {
+ insertSpecialCase("Photos");
+ loader = new DatabaseResultLoader(mContext, "hot");
+ assertThat(loader.loadInBackground().size()).isEqualTo(0);
+ }
+
+ @Test
+ public void testSpecialCaseMultiWordPrefix_MatchesPrefixOfEntry() {
+ insertSpecialCase("Apps Notifications");
+ loader = new DatabaseResultLoader(mContext, "Apps");
+ assertThat(loader.loadInBackground().size()).isEqualTo(1);
+ }
+
+ @Test
+ public void testSpecialCaseMultiWordPrefix_MatchesSecondWordPrefixOfEntry() {
+ insertSpecialCase("Apps Notifications");
+ loader = new DatabaseResultLoader(mContext, "Not");
+ assertThat(loader.loadInBackground().size()).isEqualTo(1);
+ }
+
+ @Test
+ public void testSpecialCaseMultiWordPrefix_DoesNotMatchMatchesPrefixOfFirstEntry() {
+ insertSpecialCase("Apps Notifications");
+ loader = new DatabaseResultLoader(mContext, "pp");
+ assertThat(loader.loadInBackground().size()).isEqualTo(0);
+ }
+
+ @Test
+ public void testSpecialCaseMultiWordPrefix_DoesNotMatchMatchesPrefixOfSecondEntry() {
+ insertSpecialCase("Apps Notifications");
+ loader = new DatabaseResultLoader(mContext, "tion");
+ assertThat(loader.loadInBackground().size()).isEqualTo(0);
+ }
+
+ @Test
+ public void testSpecialCaseMultiWordPrefixWithSpecial_MatchesPrefixOfEntry() {
+ insertSpecialCase("Apps & Notifications");
+ loader = new DatabaseResultLoader(mContext, "App");
+ assertThat(loader.loadInBackground().size()).isEqualTo(1);
+ }
+
+ @Test
+ public void testSpecialCaseMultiWordPrefixWithSpecial_MatchesPrefixOfSecondEntry() {
+ insertSpecialCase("Apps & Notifications");
+ loader = new DatabaseResultLoader(mContext, "No");
+ assertThat(loader.loadInBackground().size()).isEqualTo(1);
+ }
+
private void insertSpecialCase(String specialCase) {
String normalized = DatabaseIndexingUtils.normalizeHyphen(specialCase);
normalized = DatabaseIndexingUtils.normalizeString(normalized);
@@ -184,11 +240,11 @@
values.put(IndexDatabaseHelper.IndexColumns.DATA_TITLE, "alpha_title");
values.put(IndexDatabaseHelper.IndexColumns.DATA_TITLE_NORMALIZED, "alpha title");
values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_ON, "alpha_summary");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_ON_NORMALIZED, "alpha_summary");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_ON_NORMALIZED, "alpha summary");
values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_OFF, "alpha_summary");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_OFF_NORMALIZED, "alpha_summary");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_ENTRIES, "alpha_entries");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_KEYWORDS, "alpha_keywords");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_OFF_NORMALIZED, "alpha summary");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_ENTRIES, "alpha entries");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_KEYWORDS, "alpha keywords");
values.put(IndexDatabaseHelper.IndexColumns.CLASS_NAME,
"com.android.settings.gestures.GestureSettings");
values.put(IndexDatabaseHelper.IndexColumns.SCREEN_TITLE, "Moves");
@@ -211,11 +267,11 @@
values.put(IndexDatabaseHelper.IndexColumns.DATA_TITLE, "bravo_title");
values.put(IndexDatabaseHelper.IndexColumns.DATA_TITLE_NORMALIZED, "bravo title");
values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_ON, "bravo_summary");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_ON_NORMALIZED, "bravo_summary");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_ON_NORMALIZED, "bravo summary");
values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_OFF, "bravo_summary");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_OFF_NORMALIZED, "bravo_summary");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_ENTRIES, "bravo_entries");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_KEYWORDS, "bravo_keywords");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_OFF_NORMALIZED, "bravo summary");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_ENTRIES, "bravo entries");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_KEYWORDS, "bravo keywords");
values.put(IndexDatabaseHelper.IndexColumns.CLASS_NAME,
"com.android.settings.gestures.GestureSettings");
values.put(IndexDatabaseHelper.IndexColumns.SCREEN_TITLE, "Moves");
@@ -237,11 +293,11 @@
values.put(IndexDatabaseHelper.IndexColumns.DATA_TITLE, "charlie_title");
values.put(IndexDatabaseHelper.IndexColumns.DATA_TITLE_NORMALIZED, "charlie title");
values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_ON, "charlie_summary");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_ON_NORMALIZED, "charlie_summary");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_ON_NORMALIZED, "charlie summary");
values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_OFF, "charlie_summary");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_OFF_NORMALIZED, "charlie_summary");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_ENTRIES, "charlie_entries");
- values.put(IndexDatabaseHelper.IndexColumns.DATA_KEYWORDS, "charlie_keywords");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_SUMMARY_OFF_NORMALIZED, "charlie summary");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_ENTRIES, "charlie entries");
+ values.put(IndexDatabaseHelper.IndexColumns.DATA_KEYWORDS, "charlie keywords");
values.put(IndexDatabaseHelper.IndexColumns.CLASS_NAME,
"com.android.settings.gestures.GestureSettings");
values.put(IndexDatabaseHelper.IndexColumns.SCREEN_TITLE, "Moves");
diff --git a/tests/robotests/src/com/android/settings/search/FakeIndexProvider.java b/tests/robotests/src/com/android/settings/search/FakeIndexProvider.java
new file mode 100644
index 0000000..35486ef
--- /dev/null
+++ b/tests/robotests/src/com/android/settings/search/FakeIndexProvider.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package com.android.settings.search;
+
+import android.content.Context;
+import android.provider.SearchIndexableResource;
+import com.android.settings.core.PreferenceController;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class FakeIndexProvider implements Indexable {
+
+ public static final String KEY = "TestKey";
+
+ public static final Indexable.SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
+ new BaseSearchIndexProvider() {
+ @Override
+ public List<SearchIndexableResource> getXmlResourcesToIndex(Context context,
+ boolean enabled) {
+ return null;
+ }
+
+ @Override
+ public List<String> getNonIndexableKeys(Context context) {
+ ArrayList<String> result = new ArrayList<>();
+ result.add(KEY);
+ return result;
+ }
+
+ @Override
+ public List<PreferenceController> getPreferenceControllers(Context context) {
+ return null;
+ }
+ };
+
+}
diff --git a/tests/robotests/src/com/android/settings/search/SearchIndexableResourcesTest.java b/tests/robotests/src/com/android/settings/search/SearchIndexableResourcesTest.java
index efb5cbc..62bb7fb 100644
--- a/tests/robotests/src/com/android/settings/search/SearchIndexableResourcesTest.java
+++ b/tests/robotests/src/com/android/settings/search/SearchIndexableResourcesTest.java
@@ -16,14 +16,20 @@
package com.android.settings.search;
+import static android.provider.SearchIndexablesContract.COLUMN_INDEX_NON_INDEXABLE_KEYS_KEY_VALUE;
import static com.android.settings.search.SearchIndexableResources.NO_DATA_RES_ID;
+import static com.android.settings.search.SearchIndexableResources.sResMap;
import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.spy;
import android.annotation.DrawableRes;
import android.annotation.XmlRes;
+import android.database.Cursor;
import android.provider.SearchIndexableResource;
+import android.text.TextUtils;
import com.android.settings.R;
import com.android.settings.SettingsRobolectricTestRunner;
import com.android.settings.TestConfig;
@@ -31,8 +37,11 @@
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
+import java.util.HashMap;
+
@RunWith(SettingsRobolectricTestRunner.class)
@Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION)
public class SearchIndexableResourcesTest {
@@ -72,4 +81,24 @@
assertThat(index.xmlResId).isEqualTo(NO_DATA_RES_ID);
assertThat(index.iconResId).isEqualTo(R.drawable.ic_settings_wireless);
}
+
+ @Test
+ public void testNonIndexableKeys_GetsKeyFromProvider() {
+ SearchIndexableResources.sResMap.clear();
+ SearchIndexableResources.addIndex(FakeIndexProvider.class, 0, 0);
+
+ SettingsSearchIndexablesProvider provider = spy(new SettingsSearchIndexablesProvider());
+
+ Cursor cursor = provider.queryNonIndexableKeys(null);
+ boolean hasTestKey = false;
+ while(cursor.moveToNext()) {
+ String key = cursor.getString(COLUMN_INDEX_NON_INDEXABLE_KEYS_KEY_VALUE);
+ if (TextUtils.equals(key, FakeIndexProvider.KEY)) {
+ hasTestKey = true;
+ break;
+ }
+ }
+
+ assertThat(hasTestKey).isTrue();
+ }
}
diff --git a/tests/robotests/src/com/android/settings/webview/WebViewAppPreferenceControllerTest.java b/tests/robotests/src/com/android/settings/webview/WebViewAppPreferenceControllerTest.java
index c16bd1f..e0a32a4 100644
--- a/tests/robotests/src/com/android/settings/webview/WebViewAppPreferenceControllerTest.java
+++ b/tests/robotests/src/com/android/settings/webview/WebViewAppPreferenceControllerTest.java
@@ -70,7 +70,7 @@
verify(controller, times(1)).updateState(any());
}
- @Test public void testOnActivityResultWithFailureDoesNothing() {
+ @Test public void testOnActivityResultWithFailure() {
WebViewUpdateServiceWrapper wvusWrapper = mock(WebViewUpdateServiceWrapper.class);
WebViewAppPreferenceController controller =
@@ -78,6 +78,6 @@
controller.displayPreference(mPreferenceScreen); // Makes sure Preference is non-null
controller.onActivityResult(Activity.RESULT_CANCELED, new Intent(DEFAULT_PACKAGE_NAME));
- verify(controller, never()).updateState(any());
+ verify(controller, times(1)).updateState(any());
}
}
diff --git a/tests/unit/src/com/android/settings/display/ThemePreferenceControllerTest.java b/tests/unit/src/com/android/settings/display/ThemePreferenceControllerTest.java
new file mode 100644
index 0000000..231787e
--- /dev/null
+++ b/tests/unit/src/com/android/settings/display/ThemePreferenceControllerTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.settings.core;
+
+import static junit.framework.TestCase.assertNotNull;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.app.UiModeManager;
+import android.content.Context;
+import android.content.ContextWrapper;
+import android.support.test.InstrumentationRegistry;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+import android.support.v7.preference.ListPreference;
+
+import com.android.settings.R;
+import com.android.settings.display.ThemePreferenceController;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+
+@SmallTest
+@RunWith(AndroidJUnit4.class)
+public class ThemePreferenceControllerTest {
+
+ private UiModeManager mMockUiModeManager;
+ private ContextWrapper mContext;
+ private ThemePreferenceController mPreferenceController;
+
+ @Before
+ public void setup() {
+ mMockUiModeManager = mock(UiModeManager.class);
+ mContext = new ContextWrapper(InstrumentationRegistry.getTargetContext()) {
+ @Override
+ public Object getSystemService(String name) {
+ if (Context.UI_MODE_SERVICE.equals(name)) {
+ return mMockUiModeManager;
+ }
+ return super.getSystemService(name);
+ }
+ };
+ mPreferenceController = new ThemePreferenceController(mContext);
+ }
+
+ @Test
+ public void testUpdateState() {
+ when(mMockUiModeManager.getAvailableThemes()).thenReturn(new String[] {
+ null,
+ "Theme1",
+ "Theme2",
+ });
+ when(mMockUiModeManager.getTheme()).thenReturn("Theme1");
+ ListPreference pref = mock(ListPreference.class);
+ mPreferenceController.updateState(pref);
+ ArgumentCaptor<String[]> arg = ArgumentCaptor.forClass(String[].class);
+ verify(pref).setEntries(arg.capture());
+
+ String[] entries = arg.getValue();
+ assertEquals(3, entries.length);
+ assertNotNull(entries[0]);
+ assertEquals("Theme1", entries[1]);
+ assertEquals("Theme2", entries[2]);
+
+ verify(pref).setEntryValues(arg.capture());
+ String[] entryValues = arg.getValue();
+ assertEquals(3, entryValues.length);
+ assertNotNull(entryValues[0]);
+ assertEquals("Theme1", entryValues[1]);
+ assertEquals("Theme2", entryValues[2]);
+
+ verify(pref).setValue(eq("Theme1"));
+ }
+
+ @Test
+ public void testAvailable_false() {
+ when(mMockUiModeManager.getAvailableThemes()).thenReturn(new String[1]);
+ assertFalse(mPreferenceController.isAvailable());
+ }
+
+ @Test
+ public void testAvailable_true() {
+ when(mMockUiModeManager.getAvailableThemes()).thenReturn(new String[2]);
+ assertTrue(mPreferenceController.isAvailable());
+ }
+}