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.nfc.NfcAdapter;
37 import android.os.AsyncTask;
38 import android.os.Bundle;
39 import android.os.UserHandle;
40 import android.os.UserManager;
41 import android.support.annotation.VisibleForTesting;
42 import android.support.v14.preference.PreferenceFragment;
43 import android.support.v7.preference.Preference;
44 import android.support.v7.preference.PreferenceManager;
45 import android.text.TextUtils;
46 import android.transition.TransitionManager;
47 import android.util.Log;
48 import android.view.Menu;
49 import android.view.View;
50 import android.view.View.OnClickListener;
51 import android.view.ViewGroup;
52 import android.widget.Button;
53 import android.widget.Toolbar;
55 import com.android.internal.util.ArrayUtils;
56 import com.android.settings.Settings.WifiSettingsActivity;
57 import com.android.settings.backup.BackupSettingsActivity;
58 import com.android.settings.core.gateway.SettingsGateway;
59 import com.android.settings.core.instrumentation.MetricsFeatureProvider;
60 import com.android.settings.core.instrumentation.SharedPreferencesLogger;
61 import com.android.settings.dashboard.DashboardFeatureProvider;
62 import com.android.settings.dashboard.DashboardSummary;
63 import com.android.settings.development.DevelopmentSettings;
64 import com.android.settings.overlay.FeatureFactory;
65 import com.android.settings.search.DynamicIndexableContentMonitor;
66 import com.android.settings.search2.SearchActivity;
67 import com.android.settings.search2.SearchFeatureProvider;
68 import com.android.settings.wfd.WifiDisplaySettings;
69 import com.android.settings.widget.SwitchBar;
70 import com.android.settingslib.drawer.DashboardCategory;
71 import com.android.settingslib.drawer.SettingsDrawerActivity;
73 import java.util.ArrayList;
74 import java.util.List;
77 public class SettingsActivity extends SettingsDrawerActivity
78 implements PreferenceManager.OnPreferenceTreeClickListener,
79 PreferenceFragment.OnPreferenceStartFragmentCallback,
80 ButtonBarHandler, FragmentManager.OnBackStackChangedListener, OnClickListener {
82 private static final String LOG_TAG = "Settings";
84 public static final int LOADER_ID_INDEXABLE_CONTENT_MONITOR = 1;
86 // Constants for state save/restore
87 private static final String SAVE_KEY_CATEGORIES = ":settings:categories";
89 static final String SAVE_KEY_SHOW_HOME_AS_UP = ":settings:show_home_as_up";
91 static final String SAVE_KEY_SHOW_SEARCH = ":settings:show_search";
94 * When starting this activity, the invoking Intent can contain this extra
95 * string to specify which fragment should be initially displayed.
96 * <p/>Starting from Key Lime Pie, when this argument is passed in, the activity
97 * will call isValidFragment() to confirm that the fragment class name is valid for this
100 public static final String EXTRA_SHOW_FRAGMENT = ":settings:show_fragment";
103 * The metrics category constant for logging source when a setting fragment is opened.
105 public static final String EXTRA_SOURCE_METRICS_CATEGORY = ":settings:source_metrics";
108 * When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
109 * this extra can also be specified to supply a Bundle of arguments to pass
110 * to that fragment when it is instantiated during the initial creation
113 public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS = ":settings:show_fragment_args";
116 * Fragment "key" argument passed thru {@link #EXTRA_SHOW_FRAGMENT_ARGUMENTS}
118 public static final String EXTRA_FRAGMENT_ARG_KEY = ":settings:fragment_args_key";
120 public static final String BACK_STACK_PREFS = ":settings:prefs";
122 // extras that allow any preference activity to be launched as part of a wizard
124 // show Back and Next buttons? takes boolean parameter
125 // Back will then return RESULT_CANCELED and Next RESULT_OK
126 protected static final String EXTRA_PREFS_SHOW_BUTTON_BAR = "extra_prefs_show_button_bar";
128 // add a Skip button?
129 private static final String EXTRA_PREFS_SHOW_SKIP = "extra_prefs_show_skip";
131 // specify custom text for the Back or Next buttons, or cause a button to not appear
132 // at all by setting it to null
133 protected static final String EXTRA_PREFS_SET_NEXT_TEXT = "extra_prefs_set_next_text";
134 protected static final String EXTRA_PREFS_SET_BACK_TEXT = "extra_prefs_set_back_text";
137 * When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
138 * those extra can also be specify to supply the title or title res id to be shown for
141 public static final String EXTRA_SHOW_FRAGMENT_TITLE = ":settings:show_fragment_title";
143 * The package name used to resolve the title resource id.
145 public static final String EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME =
146 ":settings:show_fragment_title_res_package_name";
147 public static final String EXTRA_SHOW_FRAGMENT_TITLE_RESID =
148 ":settings:show_fragment_title_resid";
149 public static final String EXTRA_SHOW_FRAGMENT_AS_SHORTCUT =
150 ":settings:show_fragment_as_shortcut";
152 public static final String EXTRA_SHOW_FRAGMENT_AS_SUBSETTING =
153 ":settings:show_fragment_as_subsetting";
156 public static final String EXTRA_HIDE_DRAWER = ":settings:hide_drawer";
158 public static final String META_DATA_KEY_FRAGMENT_CLASS =
159 "com.android.settings.FRAGMENT_CLASS";
161 private static final String EXTRA_UI_OPTIONS = "settings:ui_options";
163 private static final int REQUEST_SUGGESTION = 42;
165 private String mFragmentClass;
167 private CharSequence mInitialTitle;
168 private int mInitialTitleResId;
170 private static final String[] LIKE_SHORTCUT_INTENT_ACTION_ARRAY = {
171 "android.settings.APPLICATION_DETAILS_SETTINGS"
174 private SharedPreferences mDevelopmentPreferences;
175 private SharedPreferences.OnSharedPreferenceChangeListener mDevelopmentPreferencesListener;
177 private boolean mBatteryPresent = true;
178 private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
180 public void onReceive(Context context, Intent intent) {
181 String action = intent.getAction();
182 if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
183 boolean batteryPresent = Utils.isBatteryPresent(intent);
185 if (mBatteryPresent != batteryPresent) {
186 mBatteryPresent = batteryPresent;
193 private DynamicIndexableContentMonitor mDynamicIndexableContentMonitor;
195 private ActionBar mActionBar;
196 private SwitchBar mSwitchBar;
198 private Button mNextButton;
201 boolean mDisplayHomeAsUpEnabled;
203 boolean mDisplaySearch;
205 private boolean mIsShowingDashboard;
206 private boolean mIsShortcut;
208 private ViewGroup mContent;
210 private SearchFeatureProvider mSearchFeatureProvider;
211 private MetricsFeatureProvider mMetricsFeatureProvider;
214 private ArrayList<DashboardCategory> mCategories = new ArrayList<>();
216 private DashboardFeatureProvider mDashboardFeatureProvider;
217 private ComponentName mCurrentSuggestion;
219 public SwitchBar getSwitchBar() {
224 public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) {
225 startPreferencePanel(caller, pref.getFragment(), pref.getExtras(), -1, pref.getTitle(),
231 public boolean onPreferenceTreeClick(Preference preference) {
236 public boolean onCreateOptionsMenu(Menu menu) {
237 if (!mDisplaySearch) {
240 mSearchFeatureProvider.setUpSearchMenu(menu, this);
245 public SharedPreferences getSharedPreferences(String name, int mode) {
246 if (name.equals(getPackageName() + "_preferences")) {
247 return new SharedPreferencesLogger(this, getMetricsTag());
249 return super.getSharedPreferences(name, mode);
252 private String getMetricsTag() {
253 String tag = getClass().getName();
254 if (getIntent() != null && getIntent().hasExtra(EXTRA_SHOW_FRAGMENT)) {
255 tag = getIntent().getStringExtra(EXTRA_SHOW_FRAGMENT);
257 if (tag.startsWith("com.android.settings.")) {
258 tag = tag.replace("com.android.settings.", "");
263 private static boolean isShortCutIntent(final Intent intent) {
264 Set<String> categories = intent.getCategories();
265 return (categories != null) && categories.contains("com.android.settings.SHORTCUT");
268 private static boolean isLikeShortCutIntent(final Intent intent) {
269 String action = intent.getAction();
270 if (action == null) {
273 for (int i = 0; i < LIKE_SHORTCUT_INTENT_ACTION_ARRAY.length; i++) {
274 if (LIKE_SHORTCUT_INTENT_ACTION_ARRAY[i].equals(action)) return true;
280 protected void onCreate(Bundle savedState) {
281 super.onCreate(savedState);
282 long startTime = System.currentTimeMillis();
284 final FeatureFactory factory = FeatureFactory.getFactory(this);
286 mDashboardFeatureProvider = factory.getDashboardFeatureProvider(this);
287 mSearchFeatureProvider = factory.getSearchFeatureProvider();
288 mMetricsFeatureProvider = factory.getMetricsFeatureProvider();
290 // Should happen before any call to getIntent()
293 final Intent intent = getIntent();
294 if (intent.hasExtra(EXTRA_UI_OPTIONS)) {
295 getWindow().setUiOptions(intent.getIntExtra(EXTRA_UI_OPTIONS, 0));
298 mDevelopmentPreferences = getSharedPreferences(DevelopmentSettings.PREF_FILE,
299 Context.MODE_PRIVATE);
301 // Getting Intent properties can only be done after the super.onCreate(...)
302 final String initialFragmentName = intent.getStringExtra(EXTRA_SHOW_FRAGMENT);
304 mIsShortcut = isShortCutIntent(intent) || isLikeShortCutIntent(intent) ||
305 intent.getBooleanExtra(EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, false);
307 final ComponentName cn = intent.getComponent();
308 final String className = cn.getClassName();
310 mIsShowingDashboard = className.equals(Settings.class.getName());
312 // This is a "Sub Settings" when:
313 // - this is a real SubSettings
314 // - or :settings:show_fragment_as_subsetting is passed to the Intent
315 final boolean isSubSettings = this instanceof SubSettings ||
316 intent.getBooleanExtra(EXTRA_SHOW_FRAGMENT_AS_SUBSETTING, false);
318 // If this is a sub settings, then apply the SubSettings Theme for the ActionBar content
321 setTheme(R.style.Theme_SubSettings);
324 setContentView(mIsShowingDashboard ?
325 R.layout.settings_main_dashboard : R.layout.settings_main_prefs);
327 mContent = (ViewGroup) findViewById(R.id.main_content);
329 getFragmentManager().addOnBackStackChangedListener(this);
331 if (savedState != null) {
332 // We are restarting from a previous saved state; used that to initialize, instead
333 // of starting fresh.
334 setTitleFromIntent(intent);
336 ArrayList<DashboardCategory> categories =
337 savedState.getParcelableArrayList(SAVE_KEY_CATEGORIES);
338 if (categories != null) {
340 mCategories.addAll(categories);
341 setTitleFromBackStack();
344 mDisplayHomeAsUpEnabled = savedState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
347 launchSettingFragment(initialFragmentName, isSubSettings, intent);
350 if (mIsShowingDashboard) {
351 findViewById(R.id.search_bar).setVisibility(View.VISIBLE);
352 findViewById(R.id.action_bar).setVisibility(View.GONE);
353 Toolbar toolbar = findViewById(R.id.search_action_bar);
354 toolbar.setOnClickListener(this);
355 setActionBar(toolbar);
358 mActionBar = getActionBar();
359 if (mActionBar != null) {
360 mActionBar.setDisplayHomeAsUpEnabled(mDisplayHomeAsUpEnabled);
361 mActionBar.setHomeButtonEnabled(mDisplayHomeAsUpEnabled);
363 mSwitchBar = (SwitchBar) findViewById(R.id.switch_bar);
364 if (mSwitchBar != null) {
365 mSwitchBar.setMetricsTag(getMetricsTag());
368 // see if we should show Back/Next buttons
369 if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_BUTTON_BAR, false)) {
371 View buttonBar = findViewById(R.id.button_bar);
372 if (buttonBar != null) {
373 buttonBar.setVisibility(View.VISIBLE);
375 Button backButton = (Button)findViewById(R.id.back_button);
376 backButton.setOnClickListener(new OnClickListener() {
377 public void onClick(View v) {
378 setResult(RESULT_CANCELED, null);
382 Button skipButton = (Button)findViewById(R.id.skip_button);
383 skipButton.setOnClickListener(new OnClickListener() {
384 public void onClick(View v) {
385 setResult(RESULT_OK, null);
389 mNextButton = (Button)findViewById(R.id.next_button);
390 mNextButton.setOnClickListener(new OnClickListener() {
391 public void onClick(View v) {
392 setResult(RESULT_OK, null);
397 // set our various button parameters
398 if (intent.hasExtra(EXTRA_PREFS_SET_NEXT_TEXT)) {
399 String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_NEXT_TEXT);
400 if (TextUtils.isEmpty(buttonText)) {
401 mNextButton.setVisibility(View.GONE);
404 mNextButton.setText(buttonText);
407 if (intent.hasExtra(EXTRA_PREFS_SET_BACK_TEXT)) {
408 String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_BACK_TEXT);
409 if (TextUtils.isEmpty(buttonText)) {
410 backButton.setVisibility(View.GONE);
413 backButton.setText(buttonText);
416 if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_SKIP, false)) {
417 skipButton.setVisibility(View.VISIBLE);
423 Log.d(LOG_TAG, "onCreate took " + (System.currentTimeMillis() - startTime) + " ms");
428 void launchSettingFragment(String initialFragmentName, boolean isSubSettings, Intent intent) {
429 if (!mIsShowingDashboard && initialFragmentName != null) {
430 mDisplaySearch = false;
431 // UP will be shown only if it is a sub settings
433 mDisplayHomeAsUpEnabled = isSubSettings;
434 } else if (isSubSettings) {
435 mDisplayHomeAsUpEnabled = true;
437 mDisplayHomeAsUpEnabled = false;
439 setTitleFromIntent(intent);
441 Bundle initialArguments = intent.getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
442 switchToFragment(initialFragmentName, initialArguments, true, false,
443 mInitialTitleResId, mInitialTitle, false);
445 // Show search icon as up affordance if we are displaying the main Dashboard
446 mDisplayHomeAsUpEnabled = true;
447 // toolbar is search affordance so don't show search
448 mDisplaySearch = false;
449 mInitialTitleResId = R.string.dashboard_title;
451 switchToFragment(DashboardSummary.class.getName(), null /* args */, false, false,
452 mInitialTitleResId, mInitialTitle, false);
456 public void setDisplaySearchMenu(boolean displaySearch) {
457 if (displaySearch != mDisplaySearch) {
458 mDisplaySearch = displaySearch;
459 invalidateOptionsMenu();
463 private void setTitleFromIntent(Intent intent) {
464 final int initialTitleResId = intent.getIntExtra(EXTRA_SHOW_FRAGMENT_TITLE_RESID, -1);
465 if (initialTitleResId > 0) {
466 mInitialTitle = null;
467 mInitialTitleResId = initialTitleResId;
469 final String initialTitleResPackageName = intent.getStringExtra(
470 EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME);
471 if (initialTitleResPackageName != null) {
473 Context authContext = createPackageContextAsUser(initialTitleResPackageName,
474 0 /* flags */, new UserHandle(UserHandle.myUserId()));
475 mInitialTitle = authContext.getResources().getText(mInitialTitleResId);
476 setTitle(mInitialTitle);
477 mInitialTitleResId = -1;
479 } catch (NameNotFoundException e) {
480 Log.w(LOG_TAG, "Could not find package" + initialTitleResPackageName);
483 setTitle(mInitialTitleResId);
486 mInitialTitleResId = -1;
487 final String initialTitle = intent.getStringExtra(EXTRA_SHOW_FRAGMENT_TITLE);
488 mInitialTitle = (initialTitle != null) ? initialTitle : getTitle();
489 setTitle(mInitialTitle);
494 public void onBackStackChanged() {
495 setTitleFromBackStack();
498 private void setTitleFromBackStack() {
499 final int count = getFragmentManager().getBackStackEntryCount();
502 if (mInitialTitleResId > 0) {
503 setTitle(mInitialTitleResId);
505 setTitle(mInitialTitle);
510 FragmentManager.BackStackEntry bse = getFragmentManager().getBackStackEntryAt(count - 1);
511 setTitleFromBackStackEntry(bse);
514 private void setTitleFromBackStackEntry(FragmentManager.BackStackEntry bse) {
515 final CharSequence title;
516 final int titleRes = bse.getBreadCrumbTitleRes();
518 title = getText(titleRes);
520 title = bse.getBreadCrumbTitle();
528 protected void onSaveInstanceState(Bundle outState) {
529 super.onSaveInstanceState(outState);
534 * For testing purposes to avoid crashes from final variables in Activity's onSaveInstantState.
537 void saveState(Bundle outState) {
538 if (mCategories.size() > 0) {
539 outState.putParcelableArrayList(SAVE_KEY_CATEGORIES, mCategories);
542 outState.putBoolean(SAVE_KEY_SHOW_HOME_AS_UP, mDisplayHomeAsUpEnabled);
543 outState.putBoolean(SAVE_KEY_SHOW_SEARCH, mDisplaySearch);
547 protected void onRestoreInstanceState(Bundle savedInstanceState) {
548 super.onRestoreInstanceState(savedInstanceState);
550 mDisplayHomeAsUpEnabled = savedInstanceState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
551 mDisplaySearch = savedInstanceState.getBoolean(SAVE_KEY_SHOW_SEARCH);
555 protected void onResume() {
558 mDevelopmentPreferencesListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
560 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
564 mDevelopmentPreferences.registerOnSharedPreferenceChangeListener(
565 mDevelopmentPreferencesListener);
567 registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
568 if (mDynamicIndexableContentMonitor == null) {
569 mDynamicIndexableContentMonitor = new DynamicIndexableContentMonitor();
571 mDynamicIndexableContentMonitor.register(this, LOADER_ID_INDEXABLE_CONTENT_MONITOR);
577 protected void onPause() {
579 mDevelopmentPreferences.unregisterOnSharedPreferenceChangeListener(
580 mDevelopmentPreferencesListener);
581 mDevelopmentPreferencesListener = null;
582 unregisterReceiver(mBatteryInfoReceiver);
583 if (mDynamicIndexableContentMonitor != null) {
584 mDynamicIndexableContentMonitor.unregister(this, LOADER_ID_INDEXABLE_CONTENT_MONITOR);
589 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
590 final Bitmap icon = getBitmapFromXmlResource(R.drawable.ic_launcher_settings);
591 taskDescription.setIcon(icon);
592 super.setTaskDescription(taskDescription);
595 protected boolean isValidFragment(String fragmentName) {
596 // Almost all fragments are wrapped in this,
597 // except for a few that have their own activities.
598 for (int i = 0; i < SettingsGateway.ENTRY_FRAGMENTS.length; i++) {
599 if (SettingsGateway.ENTRY_FRAGMENTS[i].equals(fragmentName)) return true;
605 public Intent getIntent() {
606 Intent superIntent = super.getIntent();
607 String startingFragment = getStartingFragmentClass(superIntent);
608 // This is called from super.onCreate, isMultiPane() is not yet reliable
609 // Do not use onIsHidingHeaders either, which relies itself on this method
610 if (startingFragment != null) {
611 Intent modIntent = new Intent(superIntent);
612 modIntent.putExtra(EXTRA_SHOW_FRAGMENT, startingFragment);
613 Bundle args = superIntent.getExtras();
615 args = new Bundle(args);
619 args.putParcelable("intent", superIntent);
620 modIntent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
627 * Checks if the component name in the intent is different from the Settings class and
628 * returns the class name to load as a fragment.
630 private String getStartingFragmentClass(Intent intent) {
631 if (mFragmentClass != null) return mFragmentClass;
633 String intentClass = intent.getComponent().getClassName();
634 if (intentClass.equals(getClass().getName())) return null;
636 if ("com.android.settings.ManageApplications".equals(intentClass)
637 || "com.android.settings.RunningServices".equals(intentClass)
638 || "com.android.settings.applications.StorageUse".equals(intentClass)) {
639 // Old names of manage apps.
640 intentClass = com.android.settings.applications.ManageApplications.class.getName();
647 * Start a new fragment containing a preference panel. If the preferences
648 * are being displayed in multi-pane mode, the given fragment class will
649 * be instantiated and placed in the appropriate pane. If running in
650 * single-pane mode, a new activity will be launched in which to show the
653 * @param fragmentClass Full name of the class implementing the fragment.
654 * @param args Any desired arguments to supply to the fragment.
655 * @param titleRes Optional resource identifier of the title of this
657 * @param titleText Optional text of the title of this fragment.
658 * @param resultTo Optional fragment that result data should be sent to.
659 * If non-null, resultTo.onActivityResult() will be called when this
660 * preference panel is done. The launched panel must use
661 * {@link #finishPreferencePanel(Fragment, int, Intent)} when done.
662 * @param resultRequestCode If resultTo is non-null, this is the caller's
663 * request code to be received with the result.
665 public void startPreferencePanel(Fragment caller, String fragmentClass, Bundle args,
666 int titleRes, CharSequence titleText, Fragment resultTo, int resultRequestCode) {
669 if (titleText != null) {
670 title = titleText.toString();
672 // There not much we can do in that case
676 Utils.startWithFragment(this, fragmentClass, args, resultTo, resultRequestCode,
677 titleRes, title, mIsShortcut, mMetricsFeatureProvider.getMetricsCategory(caller));
681 * Start a new fragment in a new activity containing a preference panel for a given user. If the
682 * preferences are being displayed in multi-pane mode, the given fragment class will be
683 * instantiated and placed in the appropriate pane. If running in single-pane mode, a new
684 * activity will be launched in which to show the fragment.
686 * @param fragmentClass Full name of the class implementing the fragment.
687 * @param args Any desired arguments to supply to the fragment.
688 * @param titleRes Optional resource identifier of the title of this fragment.
689 * @param titleText Optional text of the title of this fragment.
690 * @param userHandle The user for which the panel has to be started.
692 public void startPreferencePanelAsUser(Fragment caller, String fragmentClass,
693 Bundle args, int titleRes, CharSequence titleText, UserHandle userHandle) {
694 // This is a workaround.
696 // Calling startWithFragmentAsUser() without specifying FLAG_ACTIVITY_NEW_TASK to the intent
697 // starting the fragment could cause a native stack corruption. See b/17523189. However,
698 // adding that flag and start the preference panel with the same UserHandler will make it
699 // impossible to use back button to return to the previous screen. See b/20042570.
701 // We work around this issue by adding FLAG_ACTIVITY_NEW_TASK to the intent, while doing
702 // another check here to call startPreferencePanel() instead of startWithFragmentAsUser()
703 // when we're calling it as the same user.
704 if (userHandle.getIdentifier() == UserHandle.myUserId()) {
705 startPreferencePanel(caller, fragmentClass, args, titleRes, titleText, null, 0);
709 if (titleText != null) {
710 title = titleText.toString();
712 // There not much we can do in that case
716 Utils.startWithFragmentAsUser(this, fragmentClass, args, titleRes, title,
717 mIsShortcut, mMetricsFeatureProvider.getMetricsCategory(caller), userHandle);
722 * Called by a preference panel fragment to finish itself.
724 * @param caller The fragment that is asking to be finished.
725 * @param resultCode Optional result code to send back to the original
726 * launching fragment.
727 * @param resultData Optional result data to send back to the original
728 * launching fragment.
730 public void finishPreferencePanel(Fragment caller, int resultCode, Intent resultData) {
731 setResult(resultCode, resultData);
736 * Start a new fragment.
738 * @param fragment The fragment to start
739 * @param push If true, the current fragment will be pushed onto the back stack. If false,
740 * the current fragment will be replaced.
742 public void startPreferenceFragment(Fragment fragment, boolean push) {
743 FragmentTransaction transaction = getFragmentManager().beginTransaction();
744 transaction.replace(R.id.main_content, fragment);
746 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
747 transaction.addToBackStack(BACK_STACK_PREFS);
749 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
751 transaction.commitAllowingStateLoss();
755 * Switch to a specific Fragment with taking care of validation, Title and BackStack
757 private Fragment switchToFragment(String fragmentName, Bundle args, boolean validate,
758 boolean addToBackStack, int titleResId, CharSequence title, boolean withTransition) {
759 if (validate && !isValidFragment(fragmentName)) {
760 throw new IllegalArgumentException("Invalid fragment for this activity: "
763 Fragment f = Fragment.instantiate(this, fragmentName, args);
764 FragmentTransaction transaction = getFragmentManager().beginTransaction();
765 transaction.replace(R.id.main_content, f);
766 if (withTransition) {
767 TransitionManager.beginDelayedTransition(mContent);
769 if (addToBackStack) {
770 transaction.addToBackStack(SettingsActivity.BACK_STACK_PREFS);
772 if (titleResId > 0) {
773 transaction.setBreadCrumbTitle(titleResId);
774 } else if (title != null) {
775 transaction.setBreadCrumbTitle(title);
777 transaction.commitAllowingStateLoss();
778 getFragmentManager().executePendingTransactions();
782 private void updateTilesList() {
783 // Generally the items that are will be changing from these updates will
784 // not be in the top list of tiles, so run it in the background and the
785 // SettingsDrawerActivity will pick up on the updates automatically.
786 AsyncTask.execute(new Runnable() {
794 private void doUpdateTilesList() {
795 PackageManager pm = getPackageManager();
796 final UserManager um = UserManager.get(this);
797 final boolean isAdmin = um.isAdminUser();
799 String packageName = getPackageName();
800 setTileEnabled(new ComponentName(packageName, WifiSettingsActivity.class.getName()),
801 pm.hasSystemFeature(PackageManager.FEATURE_WIFI), isAdmin);
803 setTileEnabled(new ComponentName(packageName,
804 Settings.BluetoothSettingsActivity.class.getName()),
805 pm.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH), isAdmin);
807 setTileEnabled(new ComponentName(packageName,
808 Settings.DataUsageSummaryActivity.class.getName()),
809 Utils.isBandwidthControlEnabled(), isAdmin);
811 setTileEnabled(new ComponentName(packageName,
812 Settings.SimSettingsActivity.class.getName()),
813 Utils.showSimCardTile(this), isAdmin);
815 setTileEnabled(new ComponentName(packageName,
816 Settings.PowerUsageSummaryActivity.class.getName()),
817 mBatteryPresent, isAdmin);
819 setTileEnabled(new ComponentName(packageName,
820 Settings.UserSettingsActivity.class.getName()),
821 UserHandle.MU_ENABLED && UserManager.supportsMultipleUsers()
822 && !Utils.isMonkeyRunning(), isAdmin);
824 setTileEnabled(new ComponentName(packageName,
825 Settings.NetworkDashboardActivity.class.getName()),
826 !UserManager.isDeviceInDemoMode(this), isAdmin);
828 setTileEnabled(new ComponentName(packageName,
829 Settings.ConnectedDeviceDashboardActivity.class.getName()),
830 !UserManager.isDeviceInDemoMode(this), isAdmin);
832 setTileEnabled(new ComponentName(packageName,
833 Settings.DateTimeSettingsActivity.class.getName()),
834 !UserManager.isDeviceInDemoMode(this), isAdmin);
835 NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
836 setTileEnabled(new ComponentName(packageName,
837 Settings.PaymentSettingsActivity.class.getName()),
838 pm.hasSystemFeature(PackageManager.FEATURE_NFC)
839 && pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)
840 && adapter != null && adapter.isEnabled(), isAdmin);
842 setTileEnabled(new ComponentName(packageName,
843 Settings.PrintSettingsActivity.class.getName()),
844 pm.hasSystemFeature(PackageManager.FEATURE_PRINTING), isAdmin);
846 final boolean showDev = mDevelopmentPreferences.getBoolean(
847 DevelopmentSettings.PREF_SHOW, android.os.Build.TYPE.equals("eng"))
848 && !um.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES);
849 setTileEnabled(new ComponentName(packageName,
850 Settings.DevelopmentSettingsActivity.class.getName()),
853 // Enable/disable backup settings depending on whether the user is admin.
854 setTileEnabled(new ComponentName(packageName,
855 BackupSettingsActivity.class.getName()), true, isAdmin);
857 setTileEnabled(new ComponentName(packageName,
858 Settings.WifiDisplaySettingsActivity.class.getName()),
859 WifiDisplaySettings.isAvailable(this), isAdmin);
861 if (UserHandle.MU_ENABLED && !isAdmin) {
863 // When on restricted users, disable all extra categories (but only the settings ones).
864 final List<DashboardCategory> categories = mDashboardFeatureProvider.getAllCategories();
865 synchronized (categories) {
866 for (DashboardCategory category : categories) {
867 final int tileCount = category.getTilesCount();
868 for (int i = 0; i < tileCount; i++) {
869 final ComponentName component = category.getTile(i).intent.getComponent();
871 final String name = component.getClassName();
872 final boolean isEnabledForRestricted = ArrayUtils.contains(
873 SettingsGateway.SETTINGS_FOR_RESTRICTED, name);
874 if (packageName.equals(component.getPackageName())
875 && !isEnabledForRestricted) {
876 setTileEnabled(component, false, isAdmin);
883 // Final step, refresh categories.
887 private void setTileEnabled(ComponentName component, boolean enabled, boolean isAdmin) {
888 if (UserHandle.MU_ENABLED && !isAdmin && getPackageName().equals(component.getPackageName())
889 && !ArrayUtils.contains(SettingsGateway.SETTINGS_FOR_RESTRICTED,
890 component.getClassName())) {
893 setTileEnabled(component, enabled);
896 private void getMetaData() {
898 ActivityInfo ai = getPackageManager().getActivityInfo(getComponentName(),
899 PackageManager.GET_META_DATA);
900 if (ai == null || ai.metaData == null) return;
901 mFragmentClass = ai.metaData.getString(META_DATA_KEY_FRAGMENT_CLASS);
902 } catch (NameNotFoundException nnfe) {
904 Log.d(LOG_TAG, "Cannot get Metadata for: " + getComponentName().toString());
908 // give subclasses access to the Next button
909 public boolean hasNextButton() {
910 return mNextButton != null;
913 public Button getNextButton() {
918 public boolean shouldUpRecreateTask(Intent targetIntent) {
919 return super.shouldUpRecreateTask(new Intent(this, SettingsActivity.class));
922 public void startSuggestion(Intent intent) {
923 if (intent == null || ActivityManager.isUserAMonkey()) {
926 mCurrentSuggestion = intent.getComponent();
927 startActivityForResult(intent, REQUEST_SUGGESTION);
931 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
932 if (requestCode == REQUEST_SUGGESTION && mCurrentSuggestion != null
933 && resultCode != RESULT_CANCELED) {
934 getPackageManager().setComponentEnabledSetting(mCurrentSuggestion,
935 PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
937 super.onActivityResult(requestCode, resultCode, data);
941 Bitmap getBitmapFromXmlResource(int drawableRes) {
942 Drawable drawable = getResources().getDrawable(drawableRes, getTheme());
943 Canvas canvas = new Canvas();
944 Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
945 drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
946 canvas.setBitmap(bitmap);
947 drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
948 drawable.draw(canvas);
954 public void onClick(View v) {
955 Intent intent = new Intent(this, SearchActivity.class);
956 startActivity(intent);