OSDN Git Service

[automerger skipped] Merge changes from topic "security_fix_settings" into oc-dev...
[android-x86/packages-apps-Settings.git] / src / com / android / settings / SettingsActivity.java
1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.android.settings;
18
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;
69 import java.util.Set;
70
71 public class SettingsActivity extends SettingsDrawerActivity
72         implements PreferenceManager.OnPreferenceTreeClickListener,
73         PreferenceFragment.OnPreferenceStartFragmentCallback,
74         ButtonBarHandler, FragmentManager.OnBackStackChangedListener, OnClickListener {
75
76     private static final String LOG_TAG = "Settings";
77
78     // Constants for state save/restore
79     private static final String SAVE_KEY_CATEGORIES = ":settings:categories";
80     @VisibleForTesting
81     static final String SAVE_KEY_SHOW_HOME_AS_UP = ":settings:show_home_as_up";
82
83     /**
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
88      * activity.
89      */
90     public static final String EXTRA_SHOW_FRAGMENT = ":settings:show_fragment";
91
92     /**
93      * The metrics category constant for logging source when a setting fragment is opened.
94      */
95     public static final String EXTRA_SOURCE_METRICS_CATEGORY = ":settings:source_metrics";
96
97     /**
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
101      * of the activity.
102      */
103     public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS = ":settings:show_fragment_args";
104
105     /**
106      * Fragment "key" argument passed thru {@link #EXTRA_SHOW_FRAGMENT_ARGUMENTS}
107      */
108     public static final String EXTRA_FRAGMENT_ARG_KEY = ":settings:fragment_args_key";
109
110     public static final String BACK_STACK_PREFS = ":settings:prefs";
111
112     // extras that allow any preference activity to be launched as part of a wizard
113
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";
117
118     // add a Skip button?
119     private static final String EXTRA_PREFS_SHOW_SKIP = "extra_prefs_show_skip";
120
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";
125
126     /**
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
129      * that fragment.
130      */
131     public static final String EXTRA_SHOW_FRAGMENT_TITLE = ":settings:show_fragment_title";
132     /**
133      * The package name used to resolve the title resource id.
134      */
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";
141
142     public static final String EXTRA_SHOW_FRAGMENT_AS_SUBSETTING =
143             ":settings:show_fragment_as_subsetting";
144
145     @Deprecated
146     public static final String EXTRA_HIDE_DRAWER = ":settings:hide_drawer";
147
148     public static final String META_DATA_KEY_FRAGMENT_CLASS =
149         "com.android.settings.FRAGMENT_CLASS";
150
151     private static final String EXTRA_UI_OPTIONS = "settings:ui_options";
152
153     private static final int REQUEST_SUGGESTION = 42;
154
155     private String mFragmentClass;
156
157     private CharSequence mInitialTitle;
158     private int mInitialTitleResId;
159
160     private static final String[] LIKE_SHORTCUT_INTENT_ACTION_ARRAY = {
161             "android.settings.APPLICATION_DETAILS_SETTINGS"
162     };
163
164     private SharedPreferences mDevelopmentPreferences;
165     private SharedPreferences.OnSharedPreferenceChangeListener mDevelopmentPreferencesListener;
166
167     private boolean mBatteryPresent = true;
168     private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
169         @Override
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);
174
175                 if (mBatteryPresent != batteryPresent) {
176                     mBatteryPresent = batteryPresent;
177                     updateTilesList();
178                 }
179             }
180         }
181     };
182
183     private SwitchBar mSwitchBar;
184
185     private Button mNextButton;
186
187     @VisibleForTesting
188     boolean mDisplayHomeAsUpEnabled;
189
190     private boolean mIsShowingDashboard;
191     private boolean mIsShortcut;
192
193     private ViewGroup mContent;
194
195     private MetricsFeatureProvider mMetricsFeatureProvider;
196
197     // Categories
198     private ArrayList<DashboardCategory> mCategories = new ArrayList<>();
199
200     private DashboardFeatureProvider mDashboardFeatureProvider;
201     private ComponentName mCurrentSuggestion;
202
203     public SwitchBar getSwitchBar() {
204         return mSwitchBar;
205     }
206
207     @Override
208     public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) {
209         startPreferencePanel(caller, pref.getFragment(), pref.getExtras(), -1, pref.getTitle(),
210                 null, 0);
211         return true;
212     }
213
214     @Override
215     public boolean onPreferenceTreeClick(Preference preference) {
216         return false;
217     }
218
219     @Override
220     public SharedPreferences getSharedPreferences(String name, int mode) {
221         if (name.equals(getPackageName() + "_preferences")) {
222             return new SharedPreferencesLogger(this, getMetricsTag());
223         }
224         return super.getSharedPreferences(name, mode);
225     }
226
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);
231         }
232         if (tag.startsWith("com.android.settings.")) {
233             tag = tag.replace("com.android.settings.", "");
234         }
235         return tag;
236     }
237
238     private static boolean isShortCutIntent(final Intent intent) {
239         Set<String> categories = intent.getCategories();
240         return (categories != null) && categories.contains("com.android.settings.SHORTCUT");
241     }
242
243     private static boolean isLikeShortCutIntent(final Intent intent) {
244         String action = intent.getAction();
245         if (action == null) {
246             return false;
247         }
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;
250         }
251         return false;
252     }
253
254     @Override
255     protected void onCreate(Bundle savedState) {
256         super.onCreate(savedState);
257         long startTime = System.currentTimeMillis();
258
259         final FeatureFactory factory = FeatureFactory.getFactory(this);
260
261         mDashboardFeatureProvider = factory.getDashboardFeatureProvider(this);
262         mMetricsFeatureProvider = factory.getMetricsFeatureProvider();
263
264         // Should happen before any call to getIntent()
265         getMetaData();
266
267         final Intent intent = getIntent();
268         if (intent.hasExtra(EXTRA_UI_OPTIONS)) {
269             getWindow().setUiOptions(intent.getIntExtra(EXTRA_UI_OPTIONS, 0));
270         }
271
272         mDevelopmentPreferences = getSharedPreferences(DevelopmentSettings.PREF_FILE,
273                 Context.MODE_PRIVATE);
274
275         // Getting Intent properties can only be done after the super.onCreate(...)
276         final String initialFragmentName = intent.getStringExtra(EXTRA_SHOW_FRAGMENT);
277
278         mIsShortcut = isShortCutIntent(intent) || isLikeShortCutIntent(intent) ||
279                 intent.getBooleanExtra(EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, false);
280
281         final ComponentName cn = intent.getComponent();
282         final String className = cn.getClassName();
283
284         mIsShowingDashboard = className.equals(Settings.class.getName());
285
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);
291
292         // If this is a sub settings, then apply the SubSettings Theme for the ActionBar content
293         // insets
294         if (isSubSettings) {
295             setTheme(R.style.Theme_SubSettings);
296         }
297
298         setContentView(mIsShowingDashboard ?
299                 R.layout.settings_main_dashboard : R.layout.settings_main_prefs);
300
301         mContent = findViewById(R.id.main_content);
302
303         getFragmentManager().addOnBackStackChangedListener(this);
304
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);
309
310             ArrayList<DashboardCategory> categories =
311                     savedState.getParcelableArrayList(SAVE_KEY_CATEGORIES);
312             if (categories != null) {
313                 mCategories.clear();
314                 mCategories.addAll(categories);
315                 setTitleFromBackStack();
316             }
317
318             mDisplayHomeAsUpEnabled = savedState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
319
320         } else {
321             launchSettingFragment(initialFragmentName, isSubSettings, intent);
322         }
323
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);
330
331             // Please forgive me for what I am about to do.
332             //
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);
338         }
339
340         ActionBar actionBar = getActionBar();
341         if (actionBar != null) {
342             actionBar.setDisplayHomeAsUpEnabled(mDisplayHomeAsUpEnabled);
343             actionBar.setHomeButtonEnabled(mDisplayHomeAsUpEnabled);
344         }
345         mSwitchBar = findViewById(R.id.switch_bar);
346         if (mSwitchBar != null) {
347             mSwitchBar.setMetricsTag(getMetricsTag());
348         }
349
350         // see if we should show Back/Next buttons
351         if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_BUTTON_BAR, false)) {
352
353             View buttonBar = findViewById(R.id.button_bar);
354             if (buttonBar != null) {
355                 buttonBar.setVisibility(View.VISIBLE);
356
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);
361                         finish();
362                     }
363                 });
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);
368                         finish();
369                     }
370                 });
371                 mNextButton = (Button)findViewById(R.id.next_button);
372                 mNextButton.setOnClickListener(new OnClickListener() {
373                     public void onClick(View v) {
374                         setResult(RESULT_OK, null);
375                         finish();
376                     }
377                 });
378
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);
384                     }
385                     else {
386                         mNextButton.setText(buttonText);
387                     }
388                 }
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);
393                     }
394                     else {
395                         backButton.setText(buttonText);
396                     }
397                 }
398                 if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_SKIP, false)) {
399                     skipButton.setVisibility(View.VISIBLE);
400                 }
401             }
402         }
403
404         if (DEBUG_TIMING) {
405             Log.d(LOG_TAG, "onCreate took " + (System.currentTimeMillis() - startTime) + " ms");
406         }
407     }
408
409     @VisibleForTesting
410     void setSearchBarVisibility() {
411         findViewById(R.id.search_bar).setVisibility(
412                 Utils.isDeviceProvisioned(this) ? View.VISIBLE : View.INVISIBLE);
413     }
414
415     @VisibleForTesting
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
419             if (mIsShortcut) {
420                 mDisplayHomeAsUpEnabled = isSubSettings;
421             } else if (isSubSettings) {
422                 mDisplayHomeAsUpEnabled = true;
423             } else {
424                 mDisplayHomeAsUpEnabled = false;
425             }
426             setTitleFromIntent(intent);
427
428             Bundle initialArguments = intent.getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
429             switchToFragment(initialFragmentName, initialArguments, true, false,
430                 mInitialTitleResId, mInitialTitle, false);
431         } else {
432             // Show search icon as up affordance if we are displaying the main Dashboard
433             mDisplayHomeAsUpEnabled = true;
434             mInitialTitleResId = R.string.dashboard_title;
435
436             switchToFragment(DashboardSummary.class.getName(), null /* args */, false, false,
437                 mInitialTitleResId, mInitialTitle, false);
438         }
439     }
440
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;
446
447             final String initialTitleResPackageName = intent.getStringExtra(
448                     EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME);
449             if (initialTitleResPackageName != null) {
450                 try {
451                     Context authContext = createPackageContextAsUser(initialTitleResPackageName,
452                             0 /* flags */, new UserHandle(UserHandle.myUserId()));
453                     mInitialTitle = authContext.getResources().getText(mInitialTitleResId);
454                     setTitle(mInitialTitle);
455                     mInitialTitleResId = -1;
456                     return;
457                 } catch (NameNotFoundException e) {
458                     Log.w(LOG_TAG, "Could not find package" + initialTitleResPackageName);
459                 }
460             } else {
461                 setTitle(mInitialTitleResId);
462             }
463         } else {
464             mInitialTitleResId = -1;
465             final String initialTitle = intent.getStringExtra(EXTRA_SHOW_FRAGMENT_TITLE);
466             mInitialTitle = (initialTitle != null) ? initialTitle : getTitle();
467             setTitle(mInitialTitle);
468         }
469     }
470
471     @Override
472     public void onBackStackChanged() {
473         setTitleFromBackStack();
474     }
475
476     private void setTitleFromBackStack() {
477         final int count = getFragmentManager().getBackStackEntryCount();
478
479         if (count == 0) {
480             if (mInitialTitleResId > 0) {
481                 setTitle(mInitialTitleResId);
482             } else {
483                 setTitle(mInitialTitle);
484             }
485             return;
486         }
487
488         FragmentManager.BackStackEntry bse = getFragmentManager().getBackStackEntryAt(count - 1);
489         setTitleFromBackStackEntry(bse);
490     }
491
492     private void setTitleFromBackStackEntry(FragmentManager.BackStackEntry bse) {
493         final CharSequence title;
494         final int titleRes = bse.getBreadCrumbTitleRes();
495         if (titleRes > 0) {
496             title = getText(titleRes);
497         } else {
498             title = bse.getBreadCrumbTitle();
499         }
500         if (title != null) {
501             setTitle(title);
502         }
503     }
504
505     @Override
506     protected void onSaveInstanceState(Bundle outState) {
507         super.onSaveInstanceState(outState);
508         saveState(outState);
509     }
510
511     /**
512      * For testing purposes to avoid crashes from final variables in Activity's onSaveInstantState.
513      */
514     @VisibleForTesting
515     void saveState(Bundle outState) {
516         if (mCategories.size() > 0) {
517             outState.putParcelableArrayList(SAVE_KEY_CATEGORIES, mCategories);
518         }
519
520         outState.putBoolean(SAVE_KEY_SHOW_HOME_AS_UP, mDisplayHomeAsUpEnabled);
521     }
522
523     @Override
524     protected void onRestoreInstanceState(Bundle savedInstanceState) {
525         super.onRestoreInstanceState(savedInstanceState);
526
527         mDisplayHomeAsUpEnabled = savedInstanceState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
528     }
529
530     @Override
531     protected void onResume() {
532         super.onResume();
533
534         mDevelopmentPreferencesListener = (sharedPreferences, key) -> updateTilesList();
535         mDevelopmentPreferences.registerOnSharedPreferenceChangeListener(
536                 mDevelopmentPreferencesListener);
537
538         registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
539
540         updateTilesList();
541     }
542
543     @Override
544     protected void onPause() {
545         super.onPause();
546         mDevelopmentPreferences.unregisterOnSharedPreferenceChangeListener(
547                 mDevelopmentPreferencesListener);
548         mDevelopmentPreferencesListener = null;
549         unregisterReceiver(mBatteryInfoReceiver);
550     }
551
552     @Override
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);
557     }
558
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;
564         }
565         return false;
566     }
567
568     @Override
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();
578             if (args != null) {
579                 args = new Bundle(args);
580             } else {
581                 args = new Bundle();
582             }
583             args.putParcelable("intent", superIntent);
584             modIntent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
585             return modIntent;
586         }
587         return superIntent;
588     }
589
590     /**
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.
593      */
594     private String getStartingFragmentClass(Intent intent) {
595         if (mFragmentClass != null) return mFragmentClass;
596
597         String intentClass = intent.getComponent().getClassName();
598         if (intentClass.equals(getClass().getName())) return null;
599
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();
605         }
606
607         return intentClass;
608     }
609
610     /**
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
615      * fragment.
616      *
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
620      * fragment.
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.
628      */
629     public void startPreferencePanel(Fragment caller, String fragmentClass, Bundle args,
630             int titleRes, CharSequence titleText, Fragment resultTo, int resultRequestCode) {
631         String title = null;
632         if (titleRes < 0) {
633             if (titleText != null) {
634                 title = titleText.toString();
635             } else {
636                 // There not much we can do in that case
637                 title = "";
638             }
639         }
640         Utils.startWithFragment(this, fragmentClass, args, resultTo, resultRequestCode,
641                 titleRes, title, mIsShortcut, mMetricsFeatureProvider.getMetricsCategory(caller));
642     }
643
644     /**
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.
649      *
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.
655      */
656     public void startPreferencePanelAsUser(Fragment caller, String fragmentClass,
657             Bundle args, int titleRes, CharSequence titleText, UserHandle userHandle) {
658         // This is a workaround.
659         //
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.
664         //
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);
670         } else {
671             String title = null;
672             if (titleRes < 0) {
673                 if (titleText != null) {
674                     title = titleText.toString();
675                 } else {
676                     // There not much we can do in that case
677                     title = "";
678                 }
679             }
680             Utils.startWithFragmentAsUser(this, fragmentClass, args, titleRes, title,
681                     mIsShortcut, mMetricsFeatureProvider.getMetricsCategory(caller), userHandle);
682         }
683     }
684
685     /**
686      * Called by a preference panel fragment to finish itself.
687      *
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.
693      */
694     public void finishPreferencePanel(Fragment caller, int resultCode, Intent resultData) {
695         setResult(resultCode, resultData);
696         finish();
697     }
698
699     /**
700      * Start a new fragment.
701      *
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.
705      */
706     public void startPreferenceFragment(Fragment fragment, boolean push) {
707         FragmentTransaction transaction = getFragmentManager().beginTransaction();
708         transaction.replace(R.id.main_content, fragment);
709         if (push) {
710             transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
711             transaction.addToBackStack(BACK_STACK_PREFS);
712         } else {
713             transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
714         }
715         transaction.commitAllowingStateLoss();
716     }
717
718     /**
719      * Switch to a specific Fragment with taking care of validation, Title and BackStack
720      */
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: "
725                     + fragmentName);
726         }
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);
732         }
733         if (addToBackStack) {
734             transaction.addToBackStack(SettingsActivity.BACK_STACK_PREFS);
735         }
736         if (titleResId > 0) {
737             transaction.setBreadCrumbTitle(titleResId);
738         } else if (title != null) {
739             transaction.setBreadCrumbTitle(title);
740         }
741         transaction.commitAllowingStateLoss();
742         getFragmentManager().executePendingTransactions();
743         return f;
744     }
745
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() {
751             @Override
752             public void run() {
753                 doUpdateTilesList();
754             }
755         });
756     }
757
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;
767
768         somethingChanged = setTileEnabled(new ComponentName(packageName,
769                         Settings.BluetoothSettingsActivity.class.getName()),
770                 pm.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH), isAdmin)
771                 || somethingChanged;
772
773         boolean isDataPlanFeatureEnabled = FeatureFactory.getFactory(this)
774                 .getDataPlanFeatureProvider()
775                 .isEnabled();
776
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
779         // reverse.
780
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()),
788                 false /* enabled */,
789                 isAdmin) || somethingChanged;
790
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;
800
801         somethingChanged = setTileEnabled(new ComponentName(packageName,
802                         Settings.SimSettingsActivity.class.getName()),
803                 Utils.showSimCardTile(this), isAdmin)
804                 || somethingChanged;
805
806         somethingChanged = setTileEnabled(new ComponentName(packageName,
807                         Settings.PowerUsageSummaryActivity.class.getName()),
808                 mBatteryPresent, isAdmin) || somethingChanged;
809
810         somethingChanged = setTileEnabled(new ComponentName(packageName,
811                         Settings.UserSettingsActivity.class.getName()),
812                 UserHandle.MU_ENABLED && UserManager.supportsMultipleUsers()
813                         && !Utils.isMonkeyRunning(), isAdmin)
814                 || somethingChanged;
815
816         somethingChanged = setTileEnabled(new ComponentName(packageName,
817                         Settings.NetworkDashboardActivity.class.getName()),
818                 !UserManager.isDeviceInDemoMode(this), isAdmin)
819                 || somethingChanged;
820
821         somethingChanged = setTileEnabled(new ComponentName(packageName,
822                         Settings.ConnectedDeviceDashboardActivity.class.getName()),
823                 !UserManager.isDeviceInDemoMode(this), isAdmin)
824                 || somethingChanged;
825
826         somethingChanged = setTileEnabled(new ComponentName(packageName,
827                         Settings.DateTimeSettingsActivity.class.getName()),
828                 !UserManager.isDeviceInDemoMode(this), isAdmin)
829                 || somethingChanged;
830
831         somethingChanged = setTileEnabled(new ComponentName(packageName,
832                         Settings.PrintSettingsActivity.class.getName()),
833                 pm.hasSystemFeature(PackageManager.FEATURE_PRINTING), isAdmin)
834                 || somethingChanged;
835
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()),
841                 showDev, isAdmin)
842                 || somethingChanged;
843
844         // Enable/disable backup settings depending on whether the user is admin.
845         somethingChanged = setTileEnabled(new ComponentName(packageName,
846                 BackupSettingsActivity.class.getName()), true, isAdmin)
847                 || somethingChanged;
848
849         somethingChanged = setTileEnabled(new ComponentName(packageName,
850                         Settings.WifiDisplaySettingsActivity.class.getName()),
851                 WifiDisplaySettings.isAvailable(this), isAdmin)
852                 || somethingChanged;
853
854         if (UserHandle.MU_ENABLED && !isAdmin) {
855
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();
863
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)
870                                     || somethingChanged;
871                         }
872                     }
873                 }
874             }
875         }
876
877         // Final step, refresh categories.
878         if (somethingChanged) {
879             Log.d(LOG_TAG, "Enabled state changed for some tiles, reloading all categories");
880             updateCategories();
881         } else {
882             Log.d(LOG_TAG, "No enabled state changed, skipping updateCategory call");
883         }
884     }
885
886     /**
887      * @return whether or not the enabled state actually changed.
888      */
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())) {
893             enabled = false;
894         }
895         return setTileEnabled(component, enabled);
896     }
897
898     private void getMetaData() {
899         try {
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) {
905             // No recovery
906             Log.d(LOG_TAG, "Cannot get Metadata for: " + getComponentName().toString());
907         }
908     }
909
910     // give subclasses access to the Next button
911     public boolean hasNextButton() {
912         return mNextButton != null;
913     }
914
915     public Button getNextButton() {
916         return mNextButton;
917     }
918
919     @Override
920     public boolean shouldUpRecreateTask(Intent targetIntent) {
921         return super.shouldUpRecreateTask(new Intent(this, SettingsActivity.class));
922     }
923
924     public void startSuggestion(Intent intent) {
925         if (intent == null || ActivityManager.isUserAMonkey()) {
926             return;
927         }
928         mCurrentSuggestion = intent.getComponent();
929         startActivityForResult(intent, REQUEST_SUGGESTION);
930     }
931
932     @Override
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);
938         }
939         super.onActivityResult(requestCode, resultCode, data);
940     }
941
942     @VisibleForTesting
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);
951
952         return bitmap;
953     }
954
955     @Override
956     public void onClick(View v) {
957         Intent intent = new Intent(this, SearchActivity.class);
958         startActivity(intent);
959     }
960 }