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.search.SearchActivity;
67 import com.android.settings.search.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";
92 * When starting this activity, the invoking Intent can contain this extra
93 * string to specify which fragment should be initially displayed.
94 * <p/>Starting from Key Lime Pie, when this argument is passed in, the activity
95 * will call isValidFragment() to confirm that the fragment class name is valid for this
98 public static final String EXTRA_SHOW_FRAGMENT = ":settings:show_fragment";
101 * The metrics category constant for logging source when a setting fragment is opened.
103 public static final String EXTRA_SOURCE_METRICS_CATEGORY = ":settings:source_metrics";
106 * When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
107 * this extra can also be specified to supply a Bundle of arguments to pass
108 * to that fragment when it is instantiated during the initial creation
111 public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS = ":settings:show_fragment_args";
114 * Fragment "key" argument passed thru {@link #EXTRA_SHOW_FRAGMENT_ARGUMENTS}
116 public static final String EXTRA_FRAGMENT_ARG_KEY = ":settings:fragment_args_key";
118 public static final String BACK_STACK_PREFS = ":settings:prefs";
120 // extras that allow any preference activity to be launched as part of a wizard
122 // show Back and Next buttons? takes boolean parameter
123 // Back will then return RESULT_CANCELED and Next RESULT_OK
124 protected static final String EXTRA_PREFS_SHOW_BUTTON_BAR = "extra_prefs_show_button_bar";
126 // add a Skip button?
127 private static final String EXTRA_PREFS_SHOW_SKIP = "extra_prefs_show_skip";
129 // specify custom text for the Back or Next buttons, or cause a button to not appear
130 // at all by setting it to null
131 protected static final String EXTRA_PREFS_SET_NEXT_TEXT = "extra_prefs_set_next_text";
132 protected static final String EXTRA_PREFS_SET_BACK_TEXT = "extra_prefs_set_back_text";
135 * When starting this activity and using {@link #EXTRA_SHOW_FRAGMENT},
136 * those extra can also be specify to supply the title or title res id to be shown for
139 public static final String EXTRA_SHOW_FRAGMENT_TITLE = ":settings:show_fragment_title";
141 * The package name used to resolve the title resource id.
143 public static final String EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME =
144 ":settings:show_fragment_title_res_package_name";
145 public static final String EXTRA_SHOW_FRAGMENT_TITLE_RESID =
146 ":settings:show_fragment_title_resid";
147 public static final String EXTRA_SHOW_FRAGMENT_AS_SHORTCUT =
148 ":settings:show_fragment_as_shortcut";
150 public static final String EXTRA_SHOW_FRAGMENT_AS_SUBSETTING =
151 ":settings:show_fragment_as_subsetting";
154 public static final String EXTRA_HIDE_DRAWER = ":settings:hide_drawer";
156 public static final String META_DATA_KEY_FRAGMENT_CLASS =
157 "com.android.settings.FRAGMENT_CLASS";
159 private static final String EXTRA_UI_OPTIONS = "settings:ui_options";
161 private static final int REQUEST_SUGGESTION = 42;
163 private String mFragmentClass;
165 private CharSequence mInitialTitle;
166 private int mInitialTitleResId;
168 private static final String[] LIKE_SHORTCUT_INTENT_ACTION_ARRAY = {
169 "android.settings.APPLICATION_DETAILS_SETTINGS"
172 private SharedPreferences mDevelopmentPreferences;
173 private SharedPreferences.OnSharedPreferenceChangeListener mDevelopmentPreferencesListener;
175 private boolean mBatteryPresent = true;
176 private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
178 public void onReceive(Context context, Intent intent) {
179 String action = intent.getAction();
180 if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
181 boolean batteryPresent = Utils.isBatteryPresent(intent);
183 if (mBatteryPresent != batteryPresent) {
184 mBatteryPresent = batteryPresent;
191 private DynamicIndexableContentMonitor mDynamicIndexableContentMonitor;
193 private SwitchBar mSwitchBar;
195 private Button mNextButton;
198 boolean mDisplayHomeAsUpEnabled;
200 private boolean mIsShowingDashboard;
201 private boolean mIsShortcut;
203 private ViewGroup mContent;
205 private MetricsFeatureProvider mMetricsFeatureProvider;
208 private ArrayList<DashboardCategory> mCategories = new ArrayList<>();
210 private DashboardFeatureProvider mDashboardFeatureProvider;
211 private ComponentName mCurrentSuggestion;
213 public SwitchBar getSwitchBar() {
218 public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) {
219 startPreferencePanel(caller, pref.getFragment(), pref.getExtras(), -1, pref.getTitle(),
225 public boolean onPreferenceTreeClick(Preference preference) {
230 public SharedPreferences getSharedPreferences(String name, int mode) {
231 if (name.equals(getPackageName() + "_preferences")) {
232 return new SharedPreferencesLogger(this, getMetricsTag());
234 return super.getSharedPreferences(name, mode);
237 private String getMetricsTag() {
238 String tag = getClass().getName();
239 if (getIntent() != null && getIntent().hasExtra(EXTRA_SHOW_FRAGMENT)) {
240 tag = getIntent().getStringExtra(EXTRA_SHOW_FRAGMENT);
242 if (tag.startsWith("com.android.settings.")) {
243 tag = tag.replace("com.android.settings.", "");
248 private static boolean isShortCutIntent(final Intent intent) {
249 Set<String> categories = intent.getCategories();
250 return (categories != null) && categories.contains("com.android.settings.SHORTCUT");
253 private static boolean isLikeShortCutIntent(final Intent intent) {
254 String action = intent.getAction();
255 if (action == null) {
258 for (int i = 0; i < LIKE_SHORTCUT_INTENT_ACTION_ARRAY.length; i++) {
259 if (LIKE_SHORTCUT_INTENT_ACTION_ARRAY[i].equals(action)) return true;
265 protected void onCreate(Bundle savedState) {
266 super.onCreate(savedState);
267 long startTime = System.currentTimeMillis();
269 final FeatureFactory factory = FeatureFactory.getFactory(this);
271 mDashboardFeatureProvider = factory.getDashboardFeatureProvider(this);
272 mMetricsFeatureProvider = factory.getMetricsFeatureProvider();
274 // Should happen before any call to getIntent()
277 final Intent intent = getIntent();
278 if (intent.hasExtra(EXTRA_UI_OPTIONS)) {
279 getWindow().setUiOptions(intent.getIntExtra(EXTRA_UI_OPTIONS, 0));
282 mDevelopmentPreferences = getSharedPreferences(DevelopmentSettings.PREF_FILE,
283 Context.MODE_PRIVATE);
285 // Getting Intent properties can only be done after the super.onCreate(...)
286 final String initialFragmentName = intent.getStringExtra(EXTRA_SHOW_FRAGMENT);
288 mIsShortcut = isShortCutIntent(intent) || isLikeShortCutIntent(intent) ||
289 intent.getBooleanExtra(EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, false);
291 final ComponentName cn = intent.getComponent();
292 final String className = cn.getClassName();
294 mIsShowingDashboard = className.equals(Settings.class.getName());
296 // This is a "Sub Settings" when:
297 // - this is a real SubSettings
298 // - or :settings:show_fragment_as_subsetting is passed to the Intent
299 final boolean isSubSettings = this instanceof SubSettings ||
300 intent.getBooleanExtra(EXTRA_SHOW_FRAGMENT_AS_SUBSETTING, false);
302 // If this is a sub settings, then apply the SubSettings Theme for the ActionBar content
305 setTheme(R.style.Theme_SubSettings);
308 setContentView(mIsShowingDashboard ?
309 R.layout.settings_main_dashboard : R.layout.settings_main_prefs);
311 mContent = findViewById(R.id.main_content);
313 getFragmentManager().addOnBackStackChangedListener(this);
315 if (savedState != null) {
316 // We are restarting from a previous saved state; used that to initialize, instead
317 // of starting fresh.
318 setTitleFromIntent(intent);
320 ArrayList<DashboardCategory> categories =
321 savedState.getParcelableArrayList(SAVE_KEY_CATEGORIES);
322 if (categories != null) {
324 mCategories.addAll(categories);
325 setTitleFromBackStack();
328 mDisplayHomeAsUpEnabled = savedState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
331 launchSettingFragment(initialFragmentName, isSubSettings, intent);
334 if (mIsShowingDashboard) {
335 findViewById(R.id.search_bar).setVisibility(View.VISIBLE);
336 findViewById(R.id.action_bar).setVisibility(View.GONE);
337 Toolbar toolbar = findViewById(R.id.search_action_bar);
338 toolbar.setOnClickListener(this);
339 setActionBar(toolbar);
341 // Please forgive me for what I am about to do.
343 // Need to make the navigation icon non-clickable so that the entire card is clickable
344 // and goes to the search UI. Also set the background to null so there's no ripple.
345 View navView = toolbar.getNavigationView();
346 navView.setClickable(false);
347 navView.setBackground(null);
350 ActionBar actionBar = getActionBar();
351 if (actionBar != null) {
352 actionBar.setDisplayHomeAsUpEnabled(mDisplayHomeAsUpEnabled);
353 actionBar.setHomeButtonEnabled(mDisplayHomeAsUpEnabled);
355 mSwitchBar = findViewById(R.id.switch_bar);
356 if (mSwitchBar != null) {
357 mSwitchBar.setMetricsTag(getMetricsTag());
360 // see if we should show Back/Next buttons
361 if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_BUTTON_BAR, false)) {
363 View buttonBar = findViewById(R.id.button_bar);
364 if (buttonBar != null) {
365 buttonBar.setVisibility(View.VISIBLE);
367 Button backButton = (Button)findViewById(R.id.back_button);
368 backButton.setOnClickListener(new OnClickListener() {
369 public void onClick(View v) {
370 setResult(RESULT_CANCELED, null);
374 Button skipButton = (Button)findViewById(R.id.skip_button);
375 skipButton.setOnClickListener(new OnClickListener() {
376 public void onClick(View v) {
377 setResult(RESULT_OK, null);
381 mNextButton = (Button)findViewById(R.id.next_button);
382 mNextButton.setOnClickListener(new OnClickListener() {
383 public void onClick(View v) {
384 setResult(RESULT_OK, null);
389 // set our various button parameters
390 if (intent.hasExtra(EXTRA_PREFS_SET_NEXT_TEXT)) {
391 String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_NEXT_TEXT);
392 if (TextUtils.isEmpty(buttonText)) {
393 mNextButton.setVisibility(View.GONE);
396 mNextButton.setText(buttonText);
399 if (intent.hasExtra(EXTRA_PREFS_SET_BACK_TEXT)) {
400 String buttonText = intent.getStringExtra(EXTRA_PREFS_SET_BACK_TEXT);
401 if (TextUtils.isEmpty(buttonText)) {
402 backButton.setVisibility(View.GONE);
405 backButton.setText(buttonText);
408 if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_SKIP, false)) {
409 skipButton.setVisibility(View.VISIBLE);
415 Log.d(LOG_TAG, "onCreate took " + (System.currentTimeMillis() - startTime) + " ms");
420 void launchSettingFragment(String initialFragmentName, boolean isSubSettings, Intent intent) {
421 if (!mIsShowingDashboard && initialFragmentName != null) {
422 // UP will be shown only if it is a sub settings
424 mDisplayHomeAsUpEnabled = isSubSettings;
425 } else if (isSubSettings) {
426 mDisplayHomeAsUpEnabled = true;
428 mDisplayHomeAsUpEnabled = false;
430 setTitleFromIntent(intent);
432 Bundle initialArguments = intent.getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
433 switchToFragment(initialFragmentName, initialArguments, true, false,
434 mInitialTitleResId, mInitialTitle, false);
436 // Show search icon as up affordance if we are displaying the main Dashboard
437 mDisplayHomeAsUpEnabled = true;
438 mInitialTitleResId = R.string.dashboard_title;
440 switchToFragment(DashboardSummary.class.getName(), null /* args */, false, false,
441 mInitialTitleResId, mInitialTitle, false);
445 private void setTitleFromIntent(Intent intent) {
446 final int initialTitleResId = intent.getIntExtra(EXTRA_SHOW_FRAGMENT_TITLE_RESID, -1);
447 if (initialTitleResId > 0) {
448 mInitialTitle = null;
449 mInitialTitleResId = initialTitleResId;
451 final String initialTitleResPackageName = intent.getStringExtra(
452 EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME);
453 if (initialTitleResPackageName != null) {
455 Context authContext = createPackageContextAsUser(initialTitleResPackageName,
456 0 /* flags */, new UserHandle(UserHandle.myUserId()));
457 mInitialTitle = authContext.getResources().getText(mInitialTitleResId);
458 setTitle(mInitialTitle);
459 mInitialTitleResId = -1;
461 } catch (NameNotFoundException e) {
462 Log.w(LOG_TAG, "Could not find package" + initialTitleResPackageName);
465 setTitle(mInitialTitleResId);
468 mInitialTitleResId = -1;
469 final String initialTitle = intent.getStringExtra(EXTRA_SHOW_FRAGMENT_TITLE);
470 mInitialTitle = (initialTitle != null) ? initialTitle : getTitle();
471 setTitle(mInitialTitle);
476 public void onBackStackChanged() {
477 setTitleFromBackStack();
480 private void setTitleFromBackStack() {
481 final int count = getFragmentManager().getBackStackEntryCount();
484 if (mInitialTitleResId > 0) {
485 setTitle(mInitialTitleResId);
487 setTitle(mInitialTitle);
492 FragmentManager.BackStackEntry bse = getFragmentManager().getBackStackEntryAt(count - 1);
493 setTitleFromBackStackEntry(bse);
496 private void setTitleFromBackStackEntry(FragmentManager.BackStackEntry bse) {
497 final CharSequence title;
498 final int titleRes = bse.getBreadCrumbTitleRes();
500 title = getText(titleRes);
502 title = bse.getBreadCrumbTitle();
510 protected void onSaveInstanceState(Bundle outState) {
511 super.onSaveInstanceState(outState);
516 * For testing purposes to avoid crashes from final variables in Activity's onSaveInstantState.
519 void saveState(Bundle outState) {
520 if (mCategories.size() > 0) {
521 outState.putParcelableArrayList(SAVE_KEY_CATEGORIES, mCategories);
524 outState.putBoolean(SAVE_KEY_SHOW_HOME_AS_UP, mDisplayHomeAsUpEnabled);
528 protected void onRestoreInstanceState(Bundle savedInstanceState) {
529 super.onRestoreInstanceState(savedInstanceState);
531 mDisplayHomeAsUpEnabled = savedInstanceState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
535 protected void onResume() {
538 mDevelopmentPreferencesListener = (sharedPreferences, key) -> updateTilesList();
539 mDevelopmentPreferences.registerOnSharedPreferenceChangeListener(
540 mDevelopmentPreferencesListener);
542 registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
543 if (mDynamicIndexableContentMonitor == null) {
544 mDynamicIndexableContentMonitor = new DynamicIndexableContentMonitor();
546 mDynamicIndexableContentMonitor.register(this, LOADER_ID_INDEXABLE_CONTENT_MONITOR);
552 protected void onPause() {
554 mDevelopmentPreferences.unregisterOnSharedPreferenceChangeListener(
555 mDevelopmentPreferencesListener);
556 mDevelopmentPreferencesListener = null;
557 unregisterReceiver(mBatteryInfoReceiver);
558 if (mDynamicIndexableContentMonitor != null) {
559 mDynamicIndexableContentMonitor.unregister(this, LOADER_ID_INDEXABLE_CONTENT_MONITOR);
564 public void setTaskDescription(ActivityManager.TaskDescription taskDescription) {
565 final Bitmap icon = getBitmapFromXmlResource(R.drawable.ic_launcher_settings);
566 taskDescription.setIcon(icon);
567 super.setTaskDescription(taskDescription);
570 protected boolean isValidFragment(String fragmentName) {
571 // Almost all fragments are wrapped in this,
572 // except for a few that have their own activities.
573 for (int i = 0; i < SettingsGateway.ENTRY_FRAGMENTS.length; i++) {
574 if (SettingsGateway.ENTRY_FRAGMENTS[i].equals(fragmentName)) return true;
580 public Intent getIntent() {
581 Intent superIntent = super.getIntent();
582 String startingFragment = getStartingFragmentClass(superIntent);
583 // This is called from super.onCreate, isMultiPane() is not yet reliable
584 // Do not use onIsHidingHeaders either, which relies itself on this method
585 if (startingFragment != null) {
586 Intent modIntent = new Intent(superIntent);
587 modIntent.putExtra(EXTRA_SHOW_FRAGMENT, startingFragment);
588 Bundle args = superIntent.getExtras();
590 args = new Bundle(args);
594 args.putParcelable("intent", superIntent);
595 modIntent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
602 * Checks if the component name in the intent is different from the Settings class and
603 * returns the class name to load as a fragment.
605 private String getStartingFragmentClass(Intent intent) {
606 if (mFragmentClass != null) return mFragmentClass;
608 String intentClass = intent.getComponent().getClassName();
609 if (intentClass.equals(getClass().getName())) return null;
611 if ("com.android.settings.ManageApplications".equals(intentClass)
612 || "com.android.settings.RunningServices".equals(intentClass)
613 || "com.android.settings.applications.StorageUse".equals(intentClass)) {
614 // Old names of manage apps.
615 intentClass = com.android.settings.applications.ManageApplications.class.getName();
622 * Start a new fragment containing a preference panel. If the preferences
623 * are being displayed in multi-pane mode, the given fragment class will
624 * be instantiated and placed in the appropriate pane. If running in
625 * single-pane mode, a new activity will be launched in which to show the
628 * @param fragmentClass Full name of the class implementing the fragment.
629 * @param args Any desired arguments to supply to the fragment.
630 * @param titleRes Optional resource identifier of the title of this
632 * @param titleText Optional text of the title of this fragment.
633 * @param resultTo Optional fragment that result data should be sent to.
634 * If non-null, resultTo.onActivityResult() will be called when this
635 * preference panel is done. The launched panel must use
636 * {@link #finishPreferencePanel(Fragment, int, Intent)} when done.
637 * @param resultRequestCode If resultTo is non-null, this is the caller's
638 * request code to be received with the result.
640 public void startPreferencePanel(Fragment caller, String fragmentClass, Bundle args,
641 int titleRes, CharSequence titleText, Fragment resultTo, int resultRequestCode) {
644 if (titleText != null) {
645 title = titleText.toString();
647 // There not much we can do in that case
651 Utils.startWithFragment(this, fragmentClass, args, resultTo, resultRequestCode,
652 titleRes, title, mIsShortcut, mMetricsFeatureProvider.getMetricsCategory(caller));
656 * Start a new fragment in a new activity containing a preference panel for a given user. If the
657 * preferences are being displayed in multi-pane mode, the given fragment class will be
658 * instantiated and placed in the appropriate pane. If running in single-pane mode, a new
659 * activity will be launched in which to show the fragment.
661 * @param fragmentClass Full name of the class implementing the fragment.
662 * @param args Any desired arguments to supply to the fragment.
663 * @param titleRes Optional resource identifier of the title of this fragment.
664 * @param titleText Optional text of the title of this fragment.
665 * @param userHandle The user for which the panel has to be started.
667 public void startPreferencePanelAsUser(Fragment caller, String fragmentClass,
668 Bundle args, int titleRes, CharSequence titleText, UserHandle userHandle) {
669 // This is a workaround.
671 // Calling startWithFragmentAsUser() without specifying FLAG_ACTIVITY_NEW_TASK to the intent
672 // starting the fragment could cause a native stack corruption. See b/17523189. However,
673 // adding that flag and start the preference panel with the same UserHandler will make it
674 // impossible to use back button to return to the previous screen. See b/20042570.
676 // We work around this issue by adding FLAG_ACTIVITY_NEW_TASK to the intent, while doing
677 // another check here to call startPreferencePanel() instead of startWithFragmentAsUser()
678 // when we're calling it as the same user.
679 if (userHandle.getIdentifier() == UserHandle.myUserId()) {
680 startPreferencePanel(caller, fragmentClass, args, titleRes, titleText, null, 0);
684 if (titleText != null) {
685 title = titleText.toString();
687 // There not much we can do in that case
691 Utils.startWithFragmentAsUser(this, fragmentClass, args, titleRes, title,
692 mIsShortcut, mMetricsFeatureProvider.getMetricsCategory(caller), userHandle);
697 * Called by a preference panel fragment to finish itself.
699 * @param caller The fragment that is asking to be finished.
700 * @param resultCode Optional result code to send back to the original
701 * launching fragment.
702 * @param resultData Optional result data to send back to the original
703 * launching fragment.
705 public void finishPreferencePanel(Fragment caller, int resultCode, Intent resultData) {
706 setResult(resultCode, resultData);
711 * Start a new fragment.
713 * @param fragment The fragment to start
714 * @param push If true, the current fragment will be pushed onto the back stack. If false,
715 * the current fragment will be replaced.
717 public void startPreferenceFragment(Fragment fragment, boolean push) {
718 FragmentTransaction transaction = getFragmentManager().beginTransaction();
719 transaction.replace(R.id.main_content, fragment);
721 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
722 transaction.addToBackStack(BACK_STACK_PREFS);
724 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
726 transaction.commitAllowingStateLoss();
730 * Switch to a specific Fragment with taking care of validation, Title and BackStack
732 private Fragment switchToFragment(String fragmentName, Bundle args, boolean validate,
733 boolean addToBackStack, int titleResId, CharSequence title, boolean withTransition) {
734 if (validate && !isValidFragment(fragmentName)) {
735 throw new IllegalArgumentException("Invalid fragment for this activity: "
738 Fragment f = Fragment.instantiate(this, fragmentName, args);
739 FragmentTransaction transaction = getFragmentManager().beginTransaction();
740 transaction.replace(R.id.main_content, f);
741 if (withTransition) {
742 TransitionManager.beginDelayedTransition(mContent);
744 if (addToBackStack) {
745 transaction.addToBackStack(SettingsActivity.BACK_STACK_PREFS);
747 if (titleResId > 0) {
748 transaction.setBreadCrumbTitle(titleResId);
749 } else if (title != null) {
750 transaction.setBreadCrumbTitle(title);
752 transaction.commitAllowingStateLoss();
753 getFragmentManager().executePendingTransactions();
757 private void updateTilesList() {
758 // Generally the items that are will be changing from these updates will
759 // not be in the top list of tiles, so run it in the background and the
760 // SettingsDrawerActivity will pick up on the updates automatically.
761 AsyncTask.execute(new Runnable() {
769 private void doUpdateTilesList() {
770 PackageManager pm = getPackageManager();
771 final UserManager um = UserManager.get(this);
772 final boolean isAdmin = um.isAdminUser();
774 String packageName = getPackageName();
775 setTileEnabled(new ComponentName(packageName, WifiSettingsActivity.class.getName()),
776 pm.hasSystemFeature(PackageManager.FEATURE_WIFI), isAdmin);
778 setTileEnabled(new ComponentName(packageName,
779 Settings.BluetoothSettingsActivity.class.getName()),
780 pm.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH), isAdmin);
782 setTileEnabled(new ComponentName(packageName,
783 Settings.DataUsageSummaryActivity.class.getName()),
784 Utils.isBandwidthControlEnabled(), isAdmin);
786 setTileEnabled(new ComponentName(packageName,
787 Settings.SimSettingsActivity.class.getName()),
788 Utils.showSimCardTile(this), isAdmin);
790 setTileEnabled(new ComponentName(packageName,
791 Settings.PowerUsageSummaryActivity.class.getName()),
792 mBatteryPresent, isAdmin);
794 setTileEnabled(new ComponentName(packageName,
795 Settings.UserSettingsActivity.class.getName()),
796 UserHandle.MU_ENABLED && UserManager.supportsMultipleUsers()
797 && !Utils.isMonkeyRunning(), isAdmin);
799 setTileEnabled(new ComponentName(packageName,
800 Settings.NetworkDashboardActivity.class.getName()),
801 !UserManager.isDeviceInDemoMode(this), isAdmin);
803 setTileEnabled(new ComponentName(packageName,
804 Settings.ConnectedDeviceDashboardActivity.class.getName()),
805 !UserManager.isDeviceInDemoMode(this), isAdmin);
807 setTileEnabled(new ComponentName(packageName,
808 Settings.DateTimeSettingsActivity.class.getName()),
809 !UserManager.isDeviceInDemoMode(this), isAdmin);
810 NfcAdapter adapter = NfcAdapter.getDefaultAdapter(this);
811 setTileEnabled(new ComponentName(packageName,
812 Settings.PaymentSettingsActivity.class.getName()),
813 pm.hasSystemFeature(PackageManager.FEATURE_NFC)
814 && pm.hasSystemFeature(PackageManager.FEATURE_NFC_HOST_CARD_EMULATION)
815 && adapter != null && adapter.isEnabled(), isAdmin);
817 setTileEnabled(new ComponentName(packageName,
818 Settings.PrintSettingsActivity.class.getName()),
819 pm.hasSystemFeature(PackageManager.FEATURE_PRINTING), isAdmin);
821 final boolean showDev = mDevelopmentPreferences.getBoolean(
822 DevelopmentSettings.PREF_SHOW, android.os.Build.TYPE.equals("eng"))
823 && !um.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES);
824 setTileEnabled(new ComponentName(packageName,
825 Settings.DevelopmentSettingsActivity.class.getName()),
828 // Enable/disable backup settings depending on whether the user is admin.
829 setTileEnabled(new ComponentName(packageName,
830 BackupSettingsActivity.class.getName()), true, isAdmin);
832 setTileEnabled(new ComponentName(packageName,
833 Settings.WifiDisplaySettingsActivity.class.getName()),
834 WifiDisplaySettings.isAvailable(this), isAdmin);
836 if (UserHandle.MU_ENABLED && !isAdmin) {
838 // When on restricted users, disable all extra categories (but only the settings ones).
839 final List<DashboardCategory> categories = mDashboardFeatureProvider.getAllCategories();
840 synchronized (categories) {
841 for (DashboardCategory category : categories) {
842 final int tileCount = category.getTilesCount();
843 for (int i = 0; i < tileCount; i++) {
844 final ComponentName component = category.getTile(i).intent.getComponent();
846 final String name = component.getClassName();
847 final boolean isEnabledForRestricted = ArrayUtils.contains(
848 SettingsGateway.SETTINGS_FOR_RESTRICTED, name);
849 if (packageName.equals(component.getPackageName())
850 && !isEnabledForRestricted) {
851 setTileEnabled(component, false, isAdmin);
858 // Final step, refresh categories.
862 private void setTileEnabled(ComponentName component, boolean enabled, boolean isAdmin) {
863 if (UserHandle.MU_ENABLED && !isAdmin && getPackageName().equals(component.getPackageName())
864 && !ArrayUtils.contains(SettingsGateway.SETTINGS_FOR_RESTRICTED,
865 component.getClassName())) {
868 setTileEnabled(component, enabled);
871 private void getMetaData() {
873 ActivityInfo ai = getPackageManager().getActivityInfo(getComponentName(),
874 PackageManager.GET_META_DATA);
875 if (ai == null || ai.metaData == null) return;
876 mFragmentClass = ai.metaData.getString(META_DATA_KEY_FRAGMENT_CLASS);
877 } catch (NameNotFoundException nnfe) {
879 Log.d(LOG_TAG, "Cannot get Metadata for: " + getComponentName().toString());
883 // give subclasses access to the Next button
884 public boolean hasNextButton() {
885 return mNextButton != null;
888 public Button getNextButton() {
893 public boolean shouldUpRecreateTask(Intent targetIntent) {
894 return super.shouldUpRecreateTask(new Intent(this, SettingsActivity.class));
897 public void startSuggestion(Intent intent) {
898 if (intent == null || ActivityManager.isUserAMonkey()) {
901 mCurrentSuggestion = intent.getComponent();
902 startActivityForResult(intent, REQUEST_SUGGESTION);
906 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
907 if (requestCode == REQUEST_SUGGESTION && mCurrentSuggestion != null
908 && resultCode != RESULT_CANCELED) {
909 getPackageManager().setComponentEnabledSetting(mCurrentSuggestion,
910 PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
912 super.onActivityResult(requestCode, resultCode, data);
916 Bitmap getBitmapFromXmlResource(int drawableRes) {
917 Drawable drawable = getResources().getDrawable(drawableRes, getTheme());
918 Canvas canvas = new Canvas();
919 Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
920 drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
921 canvas.setBitmap(bitmap);
922 drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
923 drawable.draw(canvas);
929 public void onClick(View v) {
930 Intent intent = new Intent(this, SearchActivity.class);
931 startActivity(intent);