2 * Copyright (C) 2014 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.settings;
19 import android.app.ActionBar;
20 import android.app.ActivityManager;
21 import android.app.Fragment;
22 import android.app.FragmentManager;
23 import android.app.FragmentTransaction;
24 import android.content.BroadcastReceiver;
25 import android.content.ComponentName;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.content.IntentFilter;
29 import android.content.SharedPreferences;
30 import android.content.pm.ActivityInfo;
31 import android.content.pm.PackageManager;
32 import android.content.pm.PackageManager.NameNotFoundException;
33 import android.graphics.Bitmap;
34 import android.graphics.Canvas;
35 import android.graphics.drawable.Drawable;
36 import android.os.AsyncTask;
37 import android.os.Bundle;
38 import android.os.UserHandle;
39 import android.os.UserManager;
40 import android.support.annotation.VisibleForTesting;
41 import android.support.v14.preference.PreferenceFragment;
42 import android.support.v7.preference.Preference;
43 import android.support.v7.preference.PreferenceManager;
44 import android.text.TextUtils;
45 import android.transition.TransitionManager;
46 import android.util.Log;
47 import android.view.View;
48 import android.view.View.OnClickListener;
49 import android.view.ViewGroup;
50 import android.widget.Button;
51 import android.widget.Toolbar;
52 import com.android.internal.util.ArrayUtils;
53 import com.android.settings.Settings.WifiSettingsActivity;
54 import com.android.settings.backup.BackupSettingsActivity;
55 import com.android.settings.core.gateway.SettingsGateway;
56 import com.android.settings.core.instrumentation.MetricsFeatureProvider;
57 import com.android.settings.core.instrumentation.SharedPreferencesLogger;
58 import com.android.settings.dashboard.DashboardFeatureProvider;
59 import com.android.settings.dashboard.DashboardSummary;
60 import com.android.settings.development.DevelopmentSettings;
61 import com.android.settings.overlay.FeatureFactory;
62 import com.android.settings.search.SearchActivity;
63 import com.android.settings.wfd.WifiDisplaySettings;
64 import com.android.settings.widget.SwitchBar;
65 import com.android.settingslib.drawer.DashboardCategory;
66 import com.android.settingslib.drawer.SettingsDrawerActivity;
67 import java.util.ArrayList;
68 import java.util.List;
71 public class SettingsActivity extends SettingsDrawerActivity
72 implements PreferenceManager.OnPreferenceTreeClickListener,
73 PreferenceFragment.OnPreferenceStartFragmentCallback,
74 ButtonBarHandler, FragmentManager.OnBackStackChangedListener, OnClickListener {
76 private static final String LOG_TAG = "Settings";
78 // Constants for state save/restore
79 private static final String SAVE_KEY_CATEGORIES = ":settings:categories";
81 static final String SAVE_KEY_SHOW_HOME_AS_UP = ":settings:show_home_as_up";
84 * When starting this activity, the invoking Intent can contain this extra
85 * string to specify which fragment should be initially displayed.
86 * <p/>Starting from Key Lime Pie, when this argument is passed in, the activity
87 * will call isValidFragment() to confirm that the fragment class name is valid for this
90 public static final String EXTRA_SHOW_FRAGMENT = ":settings:show_fragment";
93 * The metrics category constant for logging source when a setting fragment is opened.
95 public static final String EXTRA_SOURCE_METRICS_CATEGORY = ":settings:source_metrics";
98 * When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
99 * this extra can also be specified to supply a Bundle of arguments to pass
100 * to that fragment when it is instantiated during the initial creation
103 public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS = ":settings:show_fragment_args";
106 * Fragment "key" argument passed thru {@link #EXTRA_SHOW_FRAGMENT_ARGUMENTS}
108 public static final String EXTRA_FRAGMENT_ARG_KEY = ":settings:fragment_args_key";
110 public static final String BACK_STACK_PREFS = ":settings:prefs";
112 // extras that allow any preference activity to be launched as part of a wizard
114 // show Back and Next buttons? takes boolean parameter
115 // Back will then return RESULT_CANCELED and Next RESULT_OK
116 protected static final String EXTRA_PREFS_SHOW_BUTTON_BAR = "extra_prefs_show_button_bar";
118 // add a Skip button?
119 private static final String EXTRA_PREFS_SHOW_SKIP = "extra_prefs_show_skip";
121 // specify custom text for the Back or Next buttons, or cause a button to not appear
122 // at all by setting it to null
123 protected static final String EXTRA_PREFS_SET_NEXT_TEXT = "extra_prefs_set_next_text";
124 protected static final String EXTRA_PREFS_SET_BACK_TEXT = "extra_prefs_set_back_text";
127 * When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
128 * those extra can also be specify to supply the title or title res id to be shown for
131 public static final String EXTRA_SHOW_FRAGMENT_TITLE = ":settings:show_fragment_title";
133 * The package name used to resolve the title resource id.
135 public static final String EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME =
136 ":settings:show_fragment_title_res_package_name";
137 public static final String EXTRA_SHOW_FRAGMENT_TITLE_RESID =
138 ":settings:show_fragment_title_resid";
139 public static final String EXTRA_SHOW_FRAGMENT_AS_SHORTCUT =
140 ":settings:show_fragment_as_shortcut";
142 public static final String EXTRA_SHOW_FRAGMENT_AS_SUBSETTING =
143 ":settings:show_fragment_as_subsetting";
146 public static final String EXTRA_HIDE_DRAWER = ":settings:hide_drawer";
148 public static final String META_DATA_KEY_FRAGMENT_CLASS =
149 "com.android.settings.FRAGMENT_CLASS";
151 private static final String EXTRA_UI_OPTIONS = "settings:ui_options";
153 private static final int REQUEST_SUGGESTION = 42;
155 private String mFragmentClass;
157 private CharSequence mInitialTitle;
158 private int mInitialTitleResId;
160 private static final String[] LIKE_SHORTCUT_INTENT_ACTION_ARRAY = {
161 "android.settings.APPLICATION_DETAILS_SETTINGS"
164 private SharedPreferences mDevelopmentPreferences;
165 private SharedPreferences.OnSharedPreferenceChangeListener mDevelopmentPreferencesListener;
167 private boolean mBatteryPresent = true;
168 private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
170 public void onReceive(Context context, Intent intent) {
171 String action = intent.getAction();
172 if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
173 boolean batteryPresent = Utils.isBatteryPresent(intent);
175 if (mBatteryPresent != batteryPresent) {
176 mBatteryPresent = batteryPresent;
183 private SwitchBar mSwitchBar;
185 private Button mNextButton;
188 boolean mDisplayHomeAsUpEnabled;
190 private boolean mIsShowingDashboard;
191 private boolean mIsShortcut;
193 private ViewGroup mContent;
195 private MetricsFeatureProvider mMetricsFeatureProvider;
198 private ArrayList<DashboardCategory> mCategories = new ArrayList<>();
200 private DashboardFeatureProvider mDashboardFeatureProvider;
201 private ComponentName mCurrentSuggestion;
203 public SwitchBar getSwitchBar() {
208 public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) {
209 startPreferencePanel(caller, pref.getFragment(), pref.getExtras(), -1, pref.getTitle(),
215 public boolean onPreferenceTreeClick(Preference preference) {
220 public SharedPreferences getSharedPreferences(String name, int mode) {
221 if (name.equals(getPackageName() + "_preferences")) {
222 return new SharedPreferencesLogger(this, getMetricsTag());
224 return super.getSharedPreferences(name, mode);
227 private String getMetricsTag() {
228 String tag = getClass().getName();
229 if (getIntent() != null && getIntent().hasExtra(EXTRA_SHOW_FRAGMENT)) {
230 tag = getIntent().getStringExtra(EXTRA_SHOW_FRAGMENT);
232 if (tag.startsWith("com.android.settings.")) {
233 tag = tag.replace("com.android.settings.", "");
238 private static boolean isShortCutIntent(final Intent intent) {
239 Set<String> categories = intent.getCategories();
240 return (categories != null) && categories.contains("com.android.settings.SHORTCUT");
243 private static boolean isLikeShortCutIntent(final Intent intent) {
244 String action = intent.getAction();
245 if (action == null) {
248 for (int i = 0; i < LIKE_SHORTCUT_INTENT_ACTION_ARRAY.length; i++) {
249 if (LIKE_SHORTCUT_INTENT_ACTION_ARRAY[i].equals(action)) return true;
255 protected void onCreate(Bundle savedState) {
256 super.onCreate(savedState);
257 long startTime = System.currentTimeMillis();
259 final FeatureFactory factory = FeatureFactory.getFactory(this);
261 mDashboardFeatureProvider = factory.getDashboardFeatureProvider(this);
262 mMetricsFeatureProvider = factory.getMetricsFeatureProvider();
264 // Should happen before any call to getIntent()
267 final Intent intent = getIntent();
268 if (intent.hasExtra(EXTRA_UI_OPTIONS)) {
269 getWindow().setUiOptions(intent.getIntExtra(EXTRA_UI_OPTIONS, 0));
272 mDevelopmentPreferences = getSharedPreferences(DevelopmentSettings.PREF_FILE,
273 Context.MODE_PRIVATE);
275 // Getting Intent properties can only be done after the super.onCreate(...)
276 final String initialFragmentName = intent.getStringExtra(EXTRA_SHOW_FRAGMENT);
278 mIsShortcut = isShortCutIntent(intent) || isLikeShortCutIntent(intent) ||
279 intent.getBooleanExtra(EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, false);
281 final ComponentName cn = intent.getComponent();
282 final String className = cn.getClassName();
284 mIsShowingDashboard = className.equals(Settings.class.getName());
286 // This is a "Sub Settings" when:
287 // - this is a real SubSettings
288 // - or :settings:show_fragment_as_subsetting is passed to the Intent
289 final boolean isSubSettings = this instanceof SubSettings ||
290 intent.getBooleanExtra(EXTRA_SHOW_FRAGMENT_AS_SUBSETTING, false);
292 // If this is a sub settings, then apply the SubSettings Theme for the ActionBar content
295 setTheme(R.style.Theme_SubSettings);
298 setContentView(mIsShowingDashboard ?
299 R.layout.settings_main_dashboard : R.layout.settings_main_prefs);
301 mContent = findViewById(R.id.main_content);
303 getFragmentManager().addOnBackStackChangedListener(this);
305 if (savedState != null) {
306 // We are restarting from a previous saved state; used that to initialize, instead
307 // of starting fresh.
308 setTitleFromIntent(intent);
310 ArrayList<DashboardCategory> categories =
311 savedState.getParcelableArrayList(SAVE_KEY_CATEGORIES);
312 if (categories != null) {
314 mCategories.addAll(categories);
315 setTitleFromBackStack();
318 mDisplayHomeAsUpEnabled = savedState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
321 launchSettingFragment(initialFragmentName, isSubSettings, intent);
324 if (mIsShowingDashboard) {
325 setSearchBarVisibility();
326 findViewById(R.id.action_bar).setVisibility(View.GONE);
327 Toolbar toolbar = findViewById(R.id.search_action_bar);
328 toolbar.setOnClickListener(this);
329 setActionBar(toolbar);
331 // Please forgive me for what I am about to do.
333 // Need to make the navigation icon non-clickable so that the entire card is clickable
334 // and goes to the search UI. Also set the background to null so there's no ripple.
335 View navView = toolbar.getNavigationView();
336 navView.setClickable(false);
337 navView.setBackground(null);
340 ActionBar actionBar = getActionBar();
341 if (actionBar != null) {
342 actionBar.setDisplayHomeAsUpEnabled(mDisplayHomeAsUpEnabled);
343 actionBar.setHomeButtonEnabled(mDisplayHomeAsUpEnabled);
345 mSwitchBar = findViewById(R.id.switch_bar);
346 if (mSwitchBar != null) {
347 mSwitchBar.setMetricsTag(getMetricsTag());
350 // see if we should show Back/Next buttons
351 if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_BUTTON_BAR, false)) {
353 View buttonBar = findViewById(R.id.button_bar);
354 if (buttonBar != null) {
355 buttonBar.setVisibility(View.VISIBLE);
357 Button backButton = (Button)findViewById(R.id.back_button);
358 backButton.setOnClickListener(new OnClickListener() {
359 public void onClick(View v) {
360 setResult(RESULT_CANCELED, null);
364 Button skipButton = (Button)findViewById(R.id.skip_button);
365 skipButton.setOnClickListener(new OnClickListener() {
366 public void onClick(View v) {
367 setResult(RESULT_OK, null);
371 mNextButton = (Button)findViewById(R.id.next_button);
372 mNextButton.setOnClickListener(new OnClickListener() {
373 public void onClick(View v) {
374 setResult(RESULT_OK, null);
379 // set our various button parameters
380 if (intent.hasExtra(EXTRA_PREFS_SET_NEXT_TEXT)) {
381 String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_NEXT_TEXT);
382 if (TextUtils.isEmpty(buttonText)) {
383 mNextButton.setVisibility(View.GONE);
386 mNextButton.setText(buttonText);
389 if (intent.hasExtra(EXTRA_PREFS_SET_BACK_TEXT)) {
390 String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_BACK_TEXT);
391 if (TextUtils.isEmpty(buttonText)) {
392 backButton.setVisibility(View.GONE);
395 backButton.setText(buttonText);
398 if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_SKIP, false)) {
399 skipButton.setVisibility(View.VISIBLE);
405 Log.d(LOG_TAG, "onCreate took " + (System.currentTimeMillis() - startTime) + " ms");
410 void setSearchBarVisibility() {
411 findViewById(R.id.search_bar).setVisibility(
412 Utils.isDeviceProvisioned(this) ? View.VISIBLE : View.INVISIBLE);
416 void launchSettingFragment(String initialFragmentName, boolean isSubSettings, Intent intent) {
417 if (!mIsShowingDashboard && initialFragmentName != null) {
418 // UP will be shown only if it is a sub settings
420 mDisplayHomeAsUpEnabled = isSubSettings;
421 } else if (isSubSettings) {
422 mDisplayHomeAsUpEnabled = true;
424 mDisplayHomeAsUpEnabled = false;
426 setTitleFromIntent(intent);
428 Bundle initialArguments = intent.getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
429 switchToFragment(initialFragmentName, initialArguments, true, false,
430 mInitialTitleResId, mInitialTitle, false);
432 // Show search icon as up affordance if we are displaying the main Dashboard
433 mDisplayHomeAsUpEnabled = true;
434 mInitialTitleResId = R.string.dashboard_title;
436 switchToFragment(DashboardSummary.class.getName(), null /* args */, false, false,
437 mInitialTitleResId, mInitialTitle, false);
441 private void setTitleFromIntent(Intent intent) {
442 final int initialTitleResId = intent.getIntExtra(EXTRA_SHOW_FRAGMENT_TITLE_RESID, -1);
443 if (initialTitleResId > 0) {
444 mInitialTitle = null;
445 mInitialTitleResId = initialTitleResId;
447 final String initialTitleResPackageName = intent.getStringExtra(
448 EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME);
449 if (initialTitleResPackageName != null) {
451 Context authContext = createPackageContextAsUser(initialTitleResPackageName,
452 0 /* flags */, new UserHandle(UserHandle.myUserId()));
453 mInitialTitle = authContext.getResources().getText(mInitialTitleResId);
454 setTitle(mInitialTitle);
455 mInitialTitleResId = -1;
457 } catch (NameNotFoundException e) {
458 Log.w(LOG_TAG, "Could not find package" + initialTitleResPackageName);
461 setTitle(mInitialTitleResId);
464 mInitialTitleResId = -1;
465 final String initialTitle = intent.getStringExtra(EXTRA_SHOW_FRAGMENT_TITLE);
466 mInitialTitle = (initialTitle != null) ? initialTitle : getTitle();
467 setTitle(mInitialTitle);
472 public void onBackStackChanged() {
473 setTitleFromBackStack();
476 private void setTitleFromBackStack() {
477 final int count = getFragmentManager().getBackStackEntryCount();
480 if (mInitialTitleResId > 0) {
481 setTitle(mInitialTitleResId);
483 setTitle(mInitialTitle);
488 FragmentManager.BackStackEntry bse = getFragmentManager().getBackStackEntryAt(count - 1);
489 setTitleFromBackStackEntry(bse);
492 private void setTitleFromBackStackEntry(FragmentManager.BackStackEntry bse) {
493 final CharSequence title;
494 final int titleRes = bse.getBreadCrumbTitleRes();
496 title = getText(titleRes);
498 title = bse.getBreadCrumbTitle();
506 protected void onSaveInstanceState(Bundle outState) {
507 super.onSaveInstanceState(outState);
512 * For testing purposes to avoid crashes from final variables in Activity's onSaveInstantState.
515 void saveState(Bundle outState) {
516 if (mCategories.size() > 0) {
517 outState.putParcelableArrayList(SAVE_KEY_CATEGORIES, mCategories);
520 outState.putBoolean(SAVE_KEY_SHOW_HOME_AS_UP, mDisplayHomeAsUpEnabled);
524 protected void onRestoreInstanceState(Bundle savedInstanceState) {
525 super.onRestoreInstanceState(savedInstanceState);
527 mDisplayHomeAsUpEnabled = savedInstanceState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
531 protected void onResume() {
534 mDevelopmentPreferencesListener = (sharedPreferences, key) -> updateTilesList();
535 mDevelopmentPreferences.registerOnSharedPreferenceChangeListener(
536 mDevelopmentPreferencesListener);
538 registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
544 protected void onPause() {
546 mDevelopmentPreferences.unregisterOnSharedPreferenceChangeListener(
547 mDevelopmentPreferencesListener);
548 mDevelopmentPreferencesListener = null;
549 unregisterReceiver(mBatteryInfoReceiver);
553 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
554 final Bitmap icon = getBitmapFromXmlResource(R.drawable.ic_launcher_settings);
555 taskDescription.setIcon(icon);
556 super.setTaskDescription(taskDescription);
559 protected boolean isValidFragment(String fragmentName) {
560 // Almost all fragments are wrapped in this,
561 // except for a few that have their own activities.
562 for (int i = 0; i < SettingsGateway.ENTRY_FRAGMENTS.length; i++) {
563 if (SettingsGateway.ENTRY_FRAGMENTS[i].equals(fragmentName)) return true;
569 public Intent getIntent() {
570 Intent superIntent = super.getIntent();
571 String startingFragment = getStartingFragmentClass(superIntent);
572 // This is called from super.onCreate, isMultiPane() is not yet reliable
573 // Do not use onIsHidingHeaders either, which relies itself on this method
574 if (startingFragment != null) {
575 Intent modIntent = new Intent(superIntent);
576 modIntent.putExtra(EXTRA_SHOW_FRAGMENT, startingFragment);
577 Bundle args = superIntent.getExtras();
579 args = new Bundle(args);
583 args.putParcelable("intent", superIntent);
584 modIntent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
591 * Checks if the component name in the intent is different from the Settings class and
592 * returns the class name to load as a fragment.
594 private String getStartingFragmentClass(Intent intent) {
595 if (mFragmentClass != null) return mFragmentClass;
597 String intentClass = intent.getComponent().getClassName();
598 if (intentClass.equals(getClass().getName())) return null;
600 if ("com.android.settings.ManageApplications".equals(intentClass)
601 || "com.android.settings.RunningServices".equals(intentClass)
602 || "com.android.settings.applications.StorageUse".equals(intentClass)) {
603 // Old names of manage apps.
604 intentClass = com.android.settings.applications.ManageApplications.class.getName();
611 * Start a new fragment containing a preference panel. If the preferences
612 * are being displayed in multi-pane mode, the given fragment class will
613 * be instantiated and placed in the appropriate pane. If running in
614 * single-pane mode, a new activity will be launched in which to show the
617 * @param fragmentClass Full name of the class implementing the fragment.
618 * @param args Any desired arguments to supply to the fragment.
619 * @param titleRes Optional resource identifier of the title of this
621 * @param titleText Optional text of the title of this fragment.
622 * @param resultTo Optional fragment that result data should be sent to.
623 * If non-null, resultTo.onActivityResult() will be called when this
624 * preference panel is done. The launched panel must use
625 * {@link #finishPreferencePanel(Fragment, int, Intent)} when done.
626 * @param resultRequestCode If resultTo is non-null, this is the caller's
627 * request code to be received with the result.
629 public void startPreferencePanel(Fragment caller, String fragmentClass, Bundle args,
630 int titleRes, CharSequence titleText, Fragment resultTo, int resultRequestCode) {
633 if (titleText != null) {
634 title = titleText.toString();
636 // There not much we can do in that case
640 Utils.startWithFragment(this, fragmentClass, args, resultTo, resultRequestCode,
641 titleRes, title, mIsShortcut, mMetricsFeatureProvider.getMetricsCategory(caller));
645 * Start a new fragment in a new activity containing a preference panel for a given user. If the
646 * preferences are being displayed in multi-pane mode, the given fragment class will be
647 * instantiated and placed in the appropriate pane. If running in single-pane mode, a new
648 * activity will be launched in which to show the fragment.
650 * @param fragmentClass Full name of the class implementing the fragment.
651 * @param args Any desired arguments to supply to the fragment.
652 * @param titleRes Optional resource identifier of the title of this fragment.
653 * @param titleText Optional text of the title of this fragment.
654 * @param userHandle The user for which the panel has to be started.
656 public void startPreferencePanelAsUser(Fragment caller, String fragmentClass,
657 Bundle args, int titleRes, CharSequence titleText, UserHandle userHandle) {
658 // This is a workaround.
660 // Calling startWithFragmentAsUser() without specifying FLAG_ACTIVITY_NEW_TASK to the intent
661 // starting the fragment could cause a native stack corruption. See b/17523189. However,
662 // adding that flag and start the preference panel with the same UserHandler will make it
663 // impossible to use back button to return to the previous screen. See b/20042570.
665 // We work around this issue by adding FLAG_ACTIVITY_NEW_TASK to the intent, while doing
666 // another check here to call startPreferencePanel() instead of startWithFragmentAsUser()
667 // when we're calling it as the same user.
668 if (userHandle.getIdentifier() == UserHandle.myUserId()) {
669 startPreferencePanel(caller, fragmentClass, args, titleRes, titleText, null, 0);
673 if (titleText != null) {
674 title = titleText.toString();
676 // There not much we can do in that case
680 Utils.startWithFragmentAsUser(this, fragmentClass, args, titleRes, title,
681 mIsShortcut, mMetricsFeatureProvider.getMetricsCategory(caller), userHandle);
686 * Called by a preference panel fragment to finish itself.
688 * @param caller The fragment that is asking to be finished.
689 * @param resultCode Optional result code to send back to the original
690 * launching fragment.
691 * @param resultData Optional result data to send back to the original
692 * launching fragment.
694 public void finishPreferencePanel(Fragment caller, int resultCode, Intent resultData) {
695 setResult(resultCode, resultData);
700 * Start a new fragment.
702 * @param fragment The fragment to start
703 * @param push If true, the current fragment will be pushed onto the back stack. If false,
704 * the current fragment will be replaced.
706 public void startPreferenceFragment(Fragment fragment, boolean push) {
707 FragmentTransaction transaction = getFragmentManager().beginTransaction();
708 transaction.replace(R.id.main_content, fragment);
710 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
711 transaction.addToBackStack(BACK_STACK_PREFS);
713 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
715 transaction.commitAllowingStateLoss();
719 * Switch to a specific Fragment with taking care of validation, Title and BackStack
721 private Fragment switchToFragment(String fragmentName, Bundle args, boolean validate,
722 boolean addToBackStack, int titleResId, CharSequence title, boolean withTransition) {
723 if (validate && !isValidFragment(fragmentName)) {
724 throw new IllegalArgumentException("Invalid fragment for this activity: "
727 Fragment f = Fragment.instantiate(this, fragmentName, args);
728 FragmentTransaction transaction = getFragmentManager().beginTransaction();
729 transaction.replace(R.id.main_content, f);
730 if (withTransition) {
731 TransitionManager.beginDelayedTransition(mContent);
733 if (addToBackStack) {
734 transaction.addToBackStack(SettingsActivity.BACK_STACK_PREFS);
736 if (titleResId > 0) {
737 transaction.setBreadCrumbTitle(titleResId);
738 } else if (title != null) {
739 transaction.setBreadCrumbTitle(title);
741 transaction.commitAllowingStateLoss();
742 getFragmentManager().executePendingTransactions();
746 private void updateTilesList() {
747 // Generally the items that are will be changing from these updates will
748 // not be in the top list of tiles, so run it in the background and the
749 // SettingsDrawerActivity will pick up on the updates automatically.
750 AsyncTask.execute(new Runnable() {
758 private void doUpdateTilesList() {
759 PackageManager pm = getPackageManager();
760 final UserManager um = UserManager.get(this);
761 final boolean isAdmin = um.isAdminUser();
762 boolean somethingChanged = false;
763 String packageName = getPackageName();
764 somethingChanged = setTileEnabled(
765 new ComponentName(packageName, WifiSettingsActivity.class.getName()),
766 pm.hasSystemFeature(PackageManager.FEATURE_WIFI), isAdmin) || somethingChanged;
768 somethingChanged = setTileEnabled(new ComponentName(packageName,
769 Settings.BluetoothSettingsActivity.class.getName()),
770 pm.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH), isAdmin)
773 boolean isDataPlanFeatureEnabled = FeatureFactory.getFactory(this)
774 .getDataPlanFeatureProvider()
777 // When the data plan feature flag is turned on we disable DataUsageSummaryActivity
778 // and enable DataPlanUsageSummaryActivity. When the feature flag is turned off we do the
781 // Disable DataUsageSummaryActivity if the data plan feature flag is turned on otherwise
782 // disable DataPlanUsageSummaryActivity.
783 somethingChanged = setTileEnabled(
784 new ComponentName(packageName,
785 isDataPlanFeatureEnabled
786 ? Settings.DataUsageSummaryActivity.class.getName()
787 : Settings.DataPlanUsageSummaryActivity.class.getName()),
789 isAdmin) || somethingChanged;
791 // Enable DataUsageSummaryActivity if the data plan feature flag is turned on otherwise
792 // enable DataPlanUsageSummaryActivity.
793 somethingChanged = setTileEnabled(
794 new ComponentName(packageName,
795 isDataPlanFeatureEnabled
796 ? Settings.DataPlanUsageSummaryActivity.class.getName()
797 : Settings.DataUsageSummaryActivity.class.getName()),
798 Utils.isBandwidthControlEnabled() /* enabled */,
799 isAdmin) || somethingChanged;
801 somethingChanged = setTileEnabled(new ComponentName(packageName,
802 Settings.SimSettingsActivity.class.getName()),
803 Utils.showSimCardTile(this), isAdmin)
806 somethingChanged = setTileEnabled(new ComponentName(packageName,
807 Settings.PowerUsageSummaryActivity.class.getName()),
808 mBatteryPresent, isAdmin) || somethingChanged;
810 somethingChanged = setTileEnabled(new ComponentName(packageName,
811 Settings.UserSettingsActivity.class.getName()),
812 UserHandle.MU_ENABLED && UserManager.supportsMultipleUsers()
813 && !Utils.isMonkeyRunning(), isAdmin)
816 somethingChanged = setTileEnabled(new ComponentName(packageName,
817 Settings.NetworkDashboardActivity.class.getName()),
818 !UserManager.isDeviceInDemoMode(this), isAdmin)
821 somethingChanged = setTileEnabled(new ComponentName(packageName,
822 Settings.ConnectedDeviceDashboardActivity.class.getName()),
823 !UserManager.isDeviceInDemoMode(this), isAdmin)
826 somethingChanged = setTileEnabled(new ComponentName(packageName,
827 Settings.DateTimeSettingsActivity.class.getName()),
828 !UserManager.isDeviceInDemoMode(this), isAdmin)
831 somethingChanged = setTileEnabled(new ComponentName(packageName,
832 Settings.PrintSettingsActivity.class.getName()),
833 pm.hasSystemFeature(PackageManager.FEATURE_PRINTING), isAdmin)
836 final boolean showDev = mDevelopmentPreferences.getBoolean(
837 DevelopmentSettings.PREF_SHOW, android.os.Build.TYPE.equals("eng"))
838 && !um.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES);
839 somethingChanged = setTileEnabled(new ComponentName(packageName,
840 Settings.DevelopmentSettingsActivity.class.getName()),
844 // Enable/disable backup settings depending on whether the user is admin.
845 somethingChanged = setTileEnabled(new ComponentName(packageName,
846 BackupSettingsActivity.class.getName()), true, isAdmin)
849 somethingChanged = setTileEnabled(new ComponentName(packageName,
850 Settings.WifiDisplaySettingsActivity.class.getName()),
851 WifiDisplaySettings.isAvailable(this), isAdmin)
854 if (UserHandle.MU_ENABLED && !isAdmin) {
856 // When on restricted users, disable all extra categories (but only the settings ones).
857 final List<DashboardCategory> categories = mDashboardFeatureProvider.getAllCategories();
858 synchronized (categories) {
859 for (DashboardCategory category : categories) {
860 final int tileCount = category.getTilesCount();
861 for (int i = 0; i < tileCount; i++) {
862 final ComponentName component = category.getTile(i).intent.getComponent();
864 final String name = component.getClassName();
865 final boolean isEnabledForRestricted = ArrayUtils.contains(
866 SettingsGateway.SETTINGS_FOR_RESTRICTED, name);
867 if (packageName.equals(component.getPackageName())
868 && !isEnabledForRestricted) {
869 somethingChanged = setTileEnabled(component, false, isAdmin)
877 // Final step, refresh categories.
878 if (somethingChanged) {
879 Log.d(LOG_TAG, "Enabled state changed for some tiles, reloading all categories");
882 Log.d(LOG_TAG, "No enabled state changed, skipping updateCategory call");
887 * @return whether or not the enabled state actually changed.
889 private boolean setTileEnabled(ComponentName component, boolean enabled, boolean isAdmin) {
890 if (UserHandle.MU_ENABLED && !isAdmin && getPackageName().equals(component.getPackageName())
891 && !ArrayUtils.contains(SettingsGateway.SETTINGS_FOR_RESTRICTED,
892 component.getClassName())) {
895 return setTileEnabled(component, enabled);
898 private void getMetaData() {
900 ActivityInfo ai = getPackageManager().getActivityInfo(getComponentName(),
901 PackageManager.GET_META_DATA);
902 if (ai == null || ai.metaData == null) return;
903 mFragmentClass = ai.metaData.getString(META_DATA_KEY_FRAGMENT_CLASS);
904 } catch (NameNotFoundException nnfe) {
906 Log.d(LOG_TAG, "Cannot get Metadata for: " + getComponentName().toString());
910 // give subclasses access to the Next button
911 public boolean hasNextButton() {
912 return mNextButton != null;
915 public Button getNextButton() {
920 public boolean shouldUpRecreateTask(Intent targetIntent) {
921 return super.shouldUpRecreateTask(new Intent(this, SettingsActivity.class));
924 public void startSuggestion(Intent intent) {
925 if (intent == null || ActivityManager.isUserAMonkey()) {
928 mCurrentSuggestion = intent.getComponent();
929 startActivityForResult(intent, REQUEST_SUGGESTION);
933 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
934 if (requestCode == REQUEST_SUGGESTION && mCurrentSuggestion != null
935 && resultCode != RESULT_CANCELED) {
936 getPackageManager().setComponentEnabledSetting(mCurrentSuggestion,
937 PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
939 super.onActivityResult(requestCode, resultCode, data);
943 Bitmap getBitmapFromXmlResource(int drawableRes) {
944 Drawable drawable = getResources().getDrawable(drawableRes, getTheme());
945 Canvas canvas = new Canvas();
946 Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
947 drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
948 canvas.setBitmap(bitmap);
949 drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
950 drawable.draw(canvas);
956 public void onClick(View v) {
957 Intent intent = new Intent(this, SearchActivity.class);
958 startActivity(intent);