GeneralPreferencesFragment.java revision 9b8cd1e564984874f2a6f5cc9bdc68cda8aa15ce
1/*
2 * Copyright (C) 2010 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
17package com.android.browser.preferences;
18
19import com.android.browser.BrowserBookmarksPage;
20import com.android.browser.BrowserHomepagePreference;
21import com.android.browser.BrowserPreferencesPage;
22import com.android.browser.PreferenceKeys;
23import com.android.browser.R;
24import com.android.browser.widget.BookmarkThumbnailWidgetProvider;
25
26import android.accounts.Account;
27import android.accounts.AccountManager;
28import android.accounts.AccountManagerCallback;
29import android.accounts.AccountManagerFuture;
30import android.app.AlertDialog;
31import android.app.Dialog;
32import android.app.DialogFragment;
33import android.content.Context;
34import android.content.DialogInterface;
35import android.content.SharedPreferences;
36import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
37import android.os.AsyncTask;
38import android.os.Bundle;
39import android.preference.Preference;
40import android.preference.Preference.OnPreferenceClickListener;
41import android.preference.PreferenceFragment;
42import android.preference.PreferenceManager;
43import android.preference.PreferenceScreen;
44import android.provider.BrowserContract;
45import android.util.Log;
46
47public class GeneralPreferencesFragment extends PreferenceFragment
48        implements OnPreferenceClickListener, Preference.OnPreferenceChangeListener {
49    static final String TAG = "PersonalPreferencesFragment";
50
51    static final String PREF_CHROME_SYNC = "sync_with_chrome";
52
53    Preference mChromeSync;
54    boolean mEnabled;
55    SharedPreferences mSharedPrefs;
56    Account[] mAccounts;
57
58    @Override
59    public void onCreate(Bundle savedInstanceState) {
60        super.onCreate(savedInstanceState);
61
62        // Load the XML preferences file
63        addPreferencesFromResource(R.xml.general_preferences);
64
65        Preference e = findPreference(PreferenceKeys.PREF_HOMEPAGE);
66        e.setOnPreferenceChangeListener(this);
67        e.setSummary(getPreferenceScreen().getSharedPreferences()
68                .getString(PreferenceKeys.PREF_HOMEPAGE, null));
69        ((BrowserHomepagePreference) e).setCurrentPage(
70                getActivity().getIntent().getStringExtra(BrowserPreferencesPage.CURRENT_PAGE));
71        mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
72        mSharedPrefs.registerOnSharedPreferenceChangeListener(mListener);
73    }
74
75    @Override
76    public boolean onPreferenceChange(Preference pref, Object objValue) {
77        if (getActivity() == null) {
78            // We aren't attached, so don't accept preferences changes from the
79            // invisible UI.
80            Log.w("PageContentPreferencesFragment", "onPreferenceChange called from detached fragment!");
81            return false;
82        }
83
84        if (pref.getKey().equals(PreferenceKeys.PREF_HOMEPAGE)) {
85            pref.setSummary((String) objValue);
86            return true;
87        }
88
89        return false;
90    }
91
92    @Override
93    public void onResume() {
94        super.onResume();
95
96        // Setup the proper state for the sync with chrome item
97        mChromeSync = findPreference(PREF_CHROME_SYNC);
98        refreshUi();
99    }
100
101    @Override
102    public void onDestroy() {
103        super.onDestroy();
104
105        mSharedPrefs.unregisterOnSharedPreferenceChangeListener(mListener);
106    }
107
108    OnSharedPreferenceChangeListener mListener
109            = new OnSharedPreferenceChangeListener() {
110        @Override
111        public void onSharedPreferenceChanged(
112                SharedPreferences sharedPreferences, String key) {
113            if (BrowserBookmarksPage.PREF_ACCOUNT_NAME.equals(key)
114                    || BrowserBookmarksPage.PREF_ACCOUNT_TYPE.equals(key)) {
115                refreshUi();
116            }
117        }
118
119    };
120
121    private AccountManagerCallback<Bundle> mCallback =
122            new AccountManagerCallback<Bundle>() {
123
124        @Override
125        public void run(AccountManagerFuture<Bundle> future) {
126            try {
127                Bundle bundle = future.getResult();
128                String name = bundle.getString(AccountManager.KEY_ACCOUNT_NAME);
129                String type = bundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
130                Account account = new Account(name, type);
131                mAccounts = new Account[] { account };
132                ImportWizard wizard = ImportWizard.newInstance(mAccounts);
133                wizard.show(getFragmentManager(), null);
134            } catch (Exception ex) {
135                // Canceled or failed to login, doesn't matter to us
136            }
137        }
138    };
139
140    OnPreferenceClickListener mAddAccount = new OnPreferenceClickListener() {
141
142        @Override
143        public boolean onPreferenceClick(Preference preference) {
144            AccountManager am = AccountManager.get(getActivity());
145            am.addAccount("com.google", null, null, null, getActivity(),
146                    mCallback, null);
147            return true;
148        }
149    };
150
151    private class GetAccountsTask extends AsyncTask<Void, Void, String> {
152        private Context mContext;
153
154        GetAccountsTask(Context ctx) {
155            mContext = ctx;
156        }
157
158        @Override
159        protected String doInBackground(Void... unused) {
160            AccountManager am = (AccountManager) mContext.getSystemService(Context.ACCOUNT_SERVICE);
161            Account[] accounts = am.getAccountsByType("com.google");
162            if (accounts == null || accounts.length == 0) {
163                // No Google accounts setup, don't offer Chrome sync
164                if (mChromeSync != null) {
165                    mChromeSync.setOnPreferenceClickListener(mAddAccount);
166                }
167            } else {
168                // Google accounts are present.
169                mAccounts = accounts;
170                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
171                Bundle args = mChromeSync.getExtras();
172                args.putParcelableArray("accounts", accounts);
173                mEnabled = BrowserContract.Settings.isSyncEnabled(mContext);
174                mChromeSync.setOnPreferenceClickListener(GeneralPreferencesFragment.this);
175
176                if (!mEnabled) {
177                    // Setup a link to the enable wizard
178                    return mContext.getResources().getString(
179                            R.string.pref_personal_sync_with_chrome_summary);
180                } else {
181                    // Chrome sync is enabled, setup a link to account switcher
182                    String accountName = prefs.getString(
183                            BrowserBookmarksPage.PREF_ACCOUNT_NAME, null);
184                    args.putString("curAccount", accountName);
185                    return accountName;
186                }
187            }
188
189            return null;
190        }
191
192        @Override
193        protected void onPostExecute(String summary) {
194            if (summary != null) {
195                mChromeSync.setSummary(summary);
196            }
197        }
198    }
199
200    void refreshUi() {
201        new GetAccountsTask(getActivity()).execute();
202
203        PreferenceScreen autoFillSettings =
204                (PreferenceScreen)findPreference(PreferenceKeys.PREF_AUTOFILL_PROFILE);
205        autoFillSettings.setDependency(PreferenceKeys.PREF_AUTOFILL_ENABLED);
206    }
207
208    @Override
209    public boolean onPreferenceClick(Preference preference) {
210        if (mAccounts == null) {
211            Log.w(TAG, "NULL accounts!");
212            return true;
213        }
214        DialogFragment frag;
215        if (mEnabled) {
216            frag = new AccountChooserDialog();
217            frag.setArguments(preference.getExtras());
218        } else {
219            frag = ImportWizard.newInstance(mAccounts);
220        }
221        frag.show(getFragmentManager(), null);
222        return true;
223    }
224
225    public static class AccountChooserDialog extends DialogFragment
226            implements DialogInterface.OnClickListener {
227
228        AlertDialog mDialog;
229
230        @Override
231        public Dialog onCreateDialog(Bundle savedInstanceState) {
232            Bundle args = getArguments();
233            Account[] accounts = (Account[]) args.getParcelableArray("accounts");
234            String curAccount = args.getString("curAccount");
235            int length = accounts.length;
236            int curAccountOffset = 0;
237            CharSequence[] accountNames = new CharSequence[length];
238            for (int i = 0; i < length; i++) {
239                String name = accounts[i].name;
240                if (name.equals(curAccount)) {
241                    curAccountOffset = i;
242                }
243                accountNames[i] = name;
244            }
245
246            mDialog = new AlertDialog.Builder(getActivity())
247                    .setIcon(android.R.drawable.ic_dialog_alert)
248                    .setTitle(R.string.account_chooser_dialog_title)
249                    .setSingleChoiceItems(accountNames, curAccountOffset, this)
250                    .create();
251            return mDialog;
252        }
253
254        @Override
255        public void onClick(DialogInterface dialog, int which) {
256            String accountName = mDialog.getListView().getAdapter().getItem(which).toString();
257            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
258            prefs.edit().putString(BrowserBookmarksPage.PREF_ACCOUNT_NAME, accountName).apply();
259            dismiss();
260        }
261    }
262}
263