OSDN Git Service

Merge "DO NOT MERGE. ActivityPicker shouldn't grant permissions." 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.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;
54
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;
72
73 import java.util.ArrayList;
74 import java.util.List;
75 import java.util.Set;
76
77 public class SettingsActivity extends SettingsDrawerActivity
78         implements PreferenceManager.OnPreferenceTreeClickListener,
79         PreferenceFragment.OnPreferenceStartFragmentCallback,
80         ButtonBarHandler, FragmentManager.OnBackStackChangedListener, OnClickListener {
81
82     private static final String LOG_TAG = "Settings";
83
84     public static final int LOADER_ID_INDEXABLE_CONTENT_MONITOR = 1;
85
86     // Constants for state save/restore
87     private static final String SAVE_KEY_CATEGORIES = ":settings:categories";
88     @VisibleForTesting
89     static final String SAVE_KEY_SHOW_HOME_AS_UP = ":settings:show_home_as_up";
90
91     /**
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
96      * activity.
97      */
98     public static final String EXTRA_SHOW_FRAGMENT = ":settings:show_fragment";
99
100     /**
101      * The metrics category constant for logging source when a setting fragment is opened.
102      */
103     public static final String EXTRA_SOURCE_METRICS_CATEGORY = ":settings:source_metrics";
104
105     /**
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
109      * of the activity.
110      */
111     public static final String EXTRA_SHOW_FRAGMENT_ARGUMENTS = ":settings:show_fragment_args";
112
113     /**
114      * Fragment "key" argument passed thru {@link #EXTRA_SHOW_FRAGMENT_ARGUMENTS}
115      */
116     public static final String EXTRA_FRAGMENT_ARG_KEY = ":settings:fragment_args_key";
117
118     public static final String BACK_STACK_PREFS = ":settings:prefs";
119
120     // extras that allow any preference activity to be launched as part of a wizard
121
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";
125
126     // add a Skip button?
127     private static final String EXTRA_PREFS_SHOW_SKIP = "extra_prefs_show_skip";
128
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";
133
134     /**
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
137      * that fragment.
138      */
139     public static final String EXTRA_SHOW_FRAGMENT_TITLE = ":settings:show_fragment_title";
140     /**
141      * The package name used to resolve the title resource id.
142      */
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";
149
150     public static final String EXTRA_SHOW_FRAGMENT_AS_SUBSETTING =
151             ":settings:show_fragment_as_subsetting";
152
153     @Deprecated
154     public static final String EXTRA_HIDE_DRAWER = ":settings:hide_drawer";
155
156     public static final String META_DATA_KEY_FRAGMENT_CLASS =
157         "com.android.settings.FRAGMENT_CLASS";
158
159     private static final String EXTRA_UI_OPTIONS = "settings:ui_options";
160
161     private static final int REQUEST_SUGGESTION = 42;
162
163     private String mFragmentClass;
164
165     private CharSequence mInitialTitle;
166     private int mInitialTitleResId;
167
168     private static final String[] LIKE_SHORTCUT_INTENT_ACTION_ARRAY = {
169             "android.settings.APPLICATION_DETAILS_SETTINGS"
170     };
171
172     private SharedPreferences mDevelopmentPreferences;
173     private SharedPreferences.OnSharedPreferenceChangeListener mDevelopmentPreferencesListener;
174
175     private boolean mBatteryPresent = true;
176     private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
177         @Override
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);
182
183                 if (mBatteryPresent != batteryPresent) {
184                     mBatteryPresent = batteryPresent;
185                     updateTilesList();
186                 }
187             }
188         }
189     };
190
191     private DynamicIndexableContentMonitor mDynamicIndexableContentMonitor;
192
193     private SwitchBar mSwitchBar;
194
195     private Button mNextButton;
196
197     @VisibleForTesting
198     boolean mDisplayHomeAsUpEnabled;
199
200     private boolean mIsShowingDashboard;
201     private boolean mIsShortcut;
202
203     private ViewGroup mContent;
204
205     private MetricsFeatureProvider mMetricsFeatureProvider;
206
207     // Categories
208     private ArrayList<DashboardCategory> mCategories = new ArrayList<>();
209
210     private DashboardFeatureProvider mDashboardFeatureProvider;
211     private ComponentName mCurrentSuggestion;
212
213     public SwitchBar getSwitchBar() {
214         return mSwitchBar;
215     }
216
217     @Override
218     public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) {
219         startPreferencePanel(caller, pref.getFragment(), pref.getExtras(), -1, pref.getTitle(),
220                 null, 0);
221         return true;
222     }
223
224     @Override
225     public boolean onPreferenceTreeClick(Preference preference) {
226         return false;
227     }
228
229     @Override
230     public SharedPreferences getSharedPreferences(String name, int mode) {
231         if (name.equals(getPackageName() + "_preferences")) {
232             return new SharedPreferencesLogger(this, getMetricsTag());
233         }
234         return super.getSharedPreferences(name, mode);
235     }
236
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);
241         }
242         if (tag.startsWith("com.android.settings.")) {
243             tag = tag.replace("com.android.settings.", "");
244         }
245         return tag;
246     }
247
248     private static boolean isShortCutIntent(final Intent intent) {
249         Set<String> categories = intent.getCategories();
250         return (categories != null) && categories.contains("com.android.settings.SHORTCUT");
251     }
252
253     private static boolean isLikeShortCutIntent(final Intent intent) {
254         String action = intent.getAction();
255         if (action == null) {
256             return false;
257         }
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;
260         }
261         return false;
262     }
263
264     @Override
265     protected void onCreate(Bundle savedState) {
266         super.onCreate(savedState);
267         long startTime = System.currentTimeMillis();
268
269         final FeatureFactory factory = FeatureFactory.getFactory(this);
270
271         mDashboardFeatureProvider = factory.getDashboardFeatureProvider(this);
272         mMetricsFeatureProvider = factory.getMetricsFeatureProvider();
273
274         // Should happen before any call to getIntent()
275         getMetaData();
276
277         final Intent intent = getIntent();
278         if (intent.hasExtra(EXTRA_UI_OPTIONS)) {
279             getWindow().setUiOptions(intent.getIntExtra(EXTRA_UI_OPTIONS, 0));
280         }
281
282         mDevelopmentPreferences = getSharedPreferences(DevelopmentSettings.PREF_FILE,
283                 Context.MODE_PRIVATE);
284
285         // Getting Intent properties can only be done after the super.onCreate(...)
286         final String initialFragmentName = intent.getStringExtra(EXTRA_SHOW_FRAGMENT);
287
288         mIsShortcut = isShortCutIntent(intent) || isLikeShortCutIntent(intent) ||
289                 intent.getBooleanExtra(EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, false);
290
291         final ComponentName cn = intent.getComponent();
292         final String className = cn.getClassName();
293
294         mIsShowingDashboard = className.equals(Settings.class.getName());
295
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);
301
302         // If this is a sub settings, then apply the SubSettings Theme for the ActionBar content
303         // insets
304         if (isSubSettings) {
305             setTheme(R.style.Theme_SubSettings);
306         }
307
308         setContentView(mIsShowingDashboard ?
309                 R.layout.settings_main_dashboard : R.layout.settings_main_prefs);
310
311         mContent = findViewById(R.id.main_content);
312
313         getFragmentManager().addOnBackStackChangedListener(this);
314
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);
319
320             ArrayList<DashboardCategory> categories =
321                     savedState.getParcelableArrayList(SAVE_KEY_CATEGORIES);
322             if (categories != null) {
323                 mCategories.clear();
324                 mCategories.addAll(categories);
325                 setTitleFromBackStack();
326             }
327
328             mDisplayHomeAsUpEnabled = savedState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
329
330         } else {
331             launchSettingFragment(initialFragmentName, isSubSettings, intent);
332         }
333
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);
340
341             // Please forgive me for what I am about to do.
342             //
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);
348         }
349
350         ActionBar actionBar = getActionBar();
351         if (actionBar != null) {
352             actionBar.setDisplayHomeAsUpEnabled(mDisplayHomeAsUpEnabled);
353             actionBar.setHomeButtonEnabled(mDisplayHomeAsUpEnabled);
354         }
355         mSwitchBar = findViewById(R.id.switch_bar);
356         if (mSwitchBar != null) {
357             mSwitchBar.setMetricsTag(getMetricsTag());
358         }
359
360         // see if we should show Back/Next buttons
361         if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_BUTTON_BAR, false)) {
362
363             View buttonBar = findViewById(R.id.button_bar);
364             if (buttonBar != null) {
365                 buttonBar.setVisibility(View.VISIBLE);
366
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);
371                         finish();
372                     }
373                 });
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);
378                         finish();
379                     }
380                 });
381                 mNextButton = (Button)findViewById(R.id.next_button);
382                 mNextButton.setOnClickListener(new OnClickListener() {
383                     public void onClick(View v) {
384                         setResult(RESULT_OK, null);
385                         finish();
386                     }
387                 });
388
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);
394                     }
395                     else {
396                         mNextButton.setText(buttonText);
397                     }
398                 }
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);
403                     }
404                     else {
405                         backButton.setText(buttonText);
406                     }
407                 }
408                 if (intent.getBooleanExtra(EXTRA_PREFS_SHOW_SKIP, false)) {
409                     skipButton.setVisibility(View.VISIBLE);
410                 }
411             }
412         }
413
414         if (DEBUG_TIMING) {
415             Log.d(LOG_TAG, "onCreate took " + (System.currentTimeMillis() - startTime) + " ms");
416         }
417     }
418
419     @VisibleForTesting
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
423             if (mIsShortcut) {
424                 mDisplayHomeAsUpEnabled = isSubSettings;
425             } else if (isSubSettings) {
426                 mDisplayHomeAsUpEnabled = true;
427             } else {
428                 mDisplayHomeAsUpEnabled = false;
429             }
430             setTitleFromIntent(intent);
431
432             Bundle initialArguments = intent.getBundleExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS);
433             switchToFragment(initialFragmentName, initialArguments, true, false,
434                 mInitialTitleResId, mInitialTitle, false);
435         } else {
436             // Show search icon as up affordance if we are displaying the main Dashboard
437             mDisplayHomeAsUpEnabled = true;
438             mInitialTitleResId = R.string.dashboard_title;
439
440             switchToFragment(DashboardSummary.class.getName(), null /* args */, false, false,
441                 mInitialTitleResId, mInitialTitle, false);
442         }
443     }
444
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;
450
451             final String initialTitleResPackageName = intent.getStringExtra(
452                     EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME);
453             if (initialTitleResPackageName != null) {
454                 try {
455                     Context authContext = createPackageContextAsUser(initialTitleResPackageName,
456                             0 /* flags */, new UserHandle(UserHandle.myUserId()));
457                     mInitialTitle = authContext.getResources().getText(mInitialTitleResId);
458                     setTitle(mInitialTitle);
459                     mInitialTitleResId = -1;
460                     return;
461                 } catch (NameNotFoundException e) {
462                     Log.w(LOG_TAG, "Could not find package" + initialTitleResPackageName);
463                 }
464             } else {
465                 setTitle(mInitialTitleResId);
466             }
467         } else {
468             mInitialTitleResId = -1;
469             final String initialTitle = intent.getStringExtra(EXTRA_SHOW_FRAGMENT_TITLE);
470             mInitialTitle = (initialTitle != null) ? initialTitle : getTitle();
471             setTitle(mInitialTitle);
472         }
473     }
474
475     @Override
476     public void onBackStackChanged() {
477         setTitleFromBackStack();
478     }
479
480     private void setTitleFromBackStack() {
481         final int count = getFragmentManager().getBackStackEntryCount();
482
483         if (count == 0) {
484             if (mInitialTitleResId > 0) {
485                 setTitle(mInitialTitleResId);
486             } else {
487                 setTitle(mInitialTitle);
488             }
489             return;
490         }
491
492         FragmentManager.BackStackEntry bse = getFragmentManager().getBackStackEntryAt(count - 1);
493         setTitleFromBackStackEntry(bse);
494     }
495
496     private void setTitleFromBackStackEntry(FragmentManager.BackStackEntry bse) {
497         final CharSequence title;
498         final int titleRes = bse.getBreadCrumbTitleRes();
499         if (titleRes > 0) {
500             title = getText(titleRes);
501         } else {
502             title = bse.getBreadCrumbTitle();
503         }
504         if (title != null) {
505             setTitle(title);
506         }
507     }
508
509     @Override
510     protected void onSaveInstanceState(Bundle outState) {
511         super.onSaveInstanceState(outState);
512         saveState(outState);
513     }
514
515     /**
516      * For testing purposes to avoid crashes from final variables in Activity's onSaveInstantState.
517      */
518     @VisibleForTesting
519     void saveState(Bundle outState) {
520         if (mCategories.size() > 0) {
521             outState.putParcelableArrayList(SAVE_KEY_CATEGORIES, mCategories);
522         }
523
524         outState.putBoolean(SAVE_KEY_SHOW_HOME_AS_UP, mDisplayHomeAsUpEnabled);
525     }
526
527     @Override
528     protected void onRestoreInstanceState(Bundle savedInstanceState) {
529         super.onRestoreInstanceState(savedInstanceState);
530
531         mDisplayHomeAsUpEnabled = savedInstanceState.getBoolean(SAVE_KEY_SHOW_HOME_AS_UP);
532     }
533
534     @Override
535     protected void onResume() {
536         super.onResume();
537
538         mDevelopmentPreferencesListener = (sharedPreferences, key) -> updateTilesList();
539         mDevelopmentPreferences.registerOnSharedPreferenceChangeListener(
540                 mDevelopmentPreferencesListener);
541
542         registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
543         if (mDynamicIndexableContentMonitor == null) {
544             mDynamicIndexableContentMonitor = new DynamicIndexableContentMonitor();
545         }
546         mDynamicIndexableContentMonitor.register(this, LOADER_ID_INDEXABLE_CONTENT_MONITOR);
547
548         updateTilesList();
549     }
550
551     @Override
552     protected void onPause() {
553         super.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);
560         }
561     }
562
563     @Override
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);
568     }
569
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;
575         }
576         return false;
577     }
578
579     @Override
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();
589             if (args != null) {
590                 args = new Bundle(args);
591             } else {
592                 args = new Bundle();
593             }
594             args.putParcelable("intent", superIntent);
595             modIntent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
596             return modIntent;
597         }
598         return superIntent;
599     }
600
601     /**
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.
604      */
605     private String getStartingFragmentClass(Intent intent) {
606         if (mFragmentClass != null) return mFragmentClass;
607
608         String intentClass = intent.getComponent().getClassName();
609         if (intentClass.equals(getClass().getName())) return null;
610
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();
616         }
617
618         return intentClass;
619     }
620
621     /**
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
626      * fragment.
627      *
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
631      * fragment.
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.
639      */
640     public void startPreferencePanel(Fragment caller, String fragmentClass, Bundle args,
641             int titleRes, CharSequence titleText, Fragment resultTo, int resultRequestCode) {
642         String title = null;
643         if (titleRes < 0) {
644             if (titleText != null) {
645                 title = titleText.toString();
646             } else {
647                 // There not much we can do in that case
648                 title = "";
649             }
650         }
651         Utils.startWithFragment(this, fragmentClass, args, resultTo, resultRequestCode,
652                 titleRes, title, mIsShortcut, mMetricsFeatureProvider.getMetricsCategory(caller));
653     }
654
655     /**
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.
660      *
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.
666      */
667     public void startPreferencePanelAsUser(Fragment caller, String fragmentClass,
668             Bundle args, int titleRes, CharSequence titleText, UserHandle userHandle) {
669         // This is a workaround.
670         //
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.
675         //
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);
681         } else {
682             String title = null;
683             if (titleRes < 0) {
684                 if (titleText != null) {
685                     title = titleText.toString();
686                 } else {
687                     // There not much we can do in that case
688                     title = "";
689                 }
690             }
691             Utils.startWithFragmentAsUser(this, fragmentClass, args, titleRes, title,
692                     mIsShortcut, mMetricsFeatureProvider.getMetricsCategory(caller), userHandle);
693         }
694     }
695
696     /**
697      * Called by a preference panel fragment to finish itself.
698      *
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.
704      */
705     public void finishPreferencePanel(Fragment caller, int resultCode, Intent resultData) {
706         setResult(resultCode, resultData);
707         finish();
708     }
709
710     /**
711      * Start a new fragment.
712      *
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.
716      */
717     public void startPreferenceFragment(Fragment fragment, boolean push) {
718         FragmentTransaction transaction = getFragmentManager().beginTransaction();
719         transaction.replace(R.id.main_content, fragment);
720         if (push) {
721             transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
722             transaction.addToBackStack(BACK_STACK_PREFS);
723         } else {
724             transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
725         }
726         transaction.commitAllowingStateLoss();
727     }
728
729     /**
730      * Switch to a specific Fragment with taking care of validation, Title and BackStack
731      */
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: "
736                     + fragmentName);
737         }
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);
743         }
744         if (addToBackStack) {
745             transaction.addToBackStack(SettingsActivity.BACK_STACK_PREFS);
746         }
747         if (titleResId > 0) {
748             transaction.setBreadCrumbTitle(titleResId);
749         } else if (title != null) {
750             transaction.setBreadCrumbTitle(title);
751         }
752         transaction.commitAllowingStateLoss();
753         getFragmentManager().executePendingTransactions();
754         return f;
755     }
756
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() {
762             @Override
763             public void run() {
764                 doUpdateTilesList();
765             }
766         });
767     }
768
769     private void doUpdateTilesList() {
770         PackageManager pm = getPackageManager();
771         final UserManager um = UserManager.get(this);
772         final boolean isAdmin = um.isAdminUser();
773
774         String packageName = getPackageName();
775         setTileEnabled(new ComponentName(packageName, WifiSettingsActivity.class.getName()),
776                 pm.hasSystemFeature(PackageManager.FEATURE_WIFI), isAdmin);
777
778         setTileEnabled(new ComponentName(packageName,
779                         Settings.BluetoothSettingsActivity.class.getName()),
780                 pm.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH), isAdmin);
781
782         setTileEnabled(new ComponentName(packageName,
783                         Settings.DataUsageSummaryActivity.class.getName()),
784                 Utils.isBandwidthControlEnabled(), isAdmin);
785
786         setTileEnabled(new ComponentName(packageName,
787                         Settings.SimSettingsActivity.class.getName()),
788                 Utils.showSimCardTile(this), isAdmin);
789
790         setTileEnabled(new ComponentName(packageName,
791                         Settings.PowerUsageSummaryActivity.class.getName()),
792                 mBatteryPresent, isAdmin);
793
794         setTileEnabled(new ComponentName(packageName,
795                         Settings.UserSettingsActivity.class.getName()),
796                 UserHandle.MU_ENABLED && UserManager.supportsMultipleUsers()
797                         && !Utils.isMonkeyRunning(), isAdmin);
798
799         setTileEnabled(new ComponentName(packageName,
800                         Settings.NetworkDashboardActivity.class.getName()),
801                 !UserManager.isDeviceInDemoMode(this), isAdmin);
802
803         setTileEnabled(new ComponentName(packageName,
804                         Settings.ConnectedDeviceDashboardActivity.class.getName()),
805                 !UserManager.isDeviceInDemoMode(this), isAdmin);
806
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);
816
817         setTileEnabled(new ComponentName(packageName,
818                         Settings.PrintSettingsActivity.class.getName()),
819                 pm.hasSystemFeature(PackageManager.FEATURE_PRINTING), isAdmin);
820
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()),
826                 showDev, isAdmin);
827
828         // Enable/disable backup settings depending on whether the user is admin.
829         setTileEnabled(new ComponentName(packageName,
830                         BackupSettingsActivity.class.getName()), true, isAdmin);
831
832         setTileEnabled(new ComponentName(packageName,
833                         Settings.WifiDisplaySettingsActivity.class.getName()),
834                 WifiDisplaySettings.isAvailable(this), isAdmin);
835
836         if (UserHandle.MU_ENABLED && !isAdmin) {
837
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();
845
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);
852                         }
853                     }
854                 }
855             }
856         }
857
858         // Final step, refresh categories.
859         updateCategories();
860     }
861
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())) {
866             enabled = false;
867         }
868         setTileEnabled(component, enabled);
869     }
870
871     private void getMetaData() {
872         try {
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) {
878             // No recovery
879             Log.d(LOG_TAG, "Cannot get Metadata for: " + getComponentName().toString());
880         }
881     }
882
883     // give subclasses access to the Next button
884     public boolean hasNextButton() {
885         return mNextButton != null;
886     }
887
888     public Button getNextButton() {
889         return mNextButton;
890     }
891
892     @Override
893     public boolean shouldUpRecreateTask(Intent targetIntent) {
894         return super.shouldUpRecreateTask(new Intent(this, SettingsActivity.class));
895     }
896
897     public void startSuggestion(Intent intent) {
898         if (intent == null || ActivityManager.isUserAMonkey()) {
899             return;
900         }
901         mCurrentSuggestion = intent.getComponent();
902         startActivityForResult(intent, REQUEST_SUGGESTION);
903     }
904
905     @Override
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);
911         }
912         super.onActivityResult(requestCode, resultCode, data);
913     }
914
915     @VisibleForTesting
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);
924
925         return bitmap;
926     }
927
928     @Override
929     public void onClick(View v) {
930         Intent intent = new Intent(this, SearchActivity.class);
931         startActivity(intent);
932     }
933 }