2 * Copyright (C) 2008 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.settings.accounts;
19 import android.accounts.Account;
20 import android.accounts.AccountManager;
21 import android.accounts.AuthenticatorDescription;
22 import android.app.ActionBar;
23 import android.app.Activity;
24 import android.content.ContentResolver;
25 import android.content.Intent;
26 import android.content.SyncAdapterType;
27 import android.content.SyncInfo;
28 import android.content.SyncStatusInfo;
29 import android.content.pm.ActivityInfo;
30 import android.content.pm.ApplicationInfo;
31 import android.content.pm.PackageManager;
32 import android.content.pm.PackageManager.NameNotFoundException;
33 import android.content.pm.ResolveInfo;
34 import android.graphics.drawable.Drawable;
35 import android.os.Bundle;
36 import android.os.UserHandle;
37 import android.preference.Preference;
38 import android.preference.Preference.OnPreferenceClickListener;
39 import android.preference.PreferenceScreen;
40 import android.util.Log;
41 import android.view.LayoutInflater;
42 import android.view.Menu;
43 import android.view.MenuInflater;
44 import android.view.MenuItem;
45 import android.view.View;
46 import android.view.ViewGroup;
47 import android.widget.ListView;
48 import android.widget.TextView;
50 import com.android.settings.AccountPreference;
51 import com.android.settings.R;
52 import com.android.settings.SettingsActivity;
53 import com.android.settings.Utils;
54 import com.android.settings.location.LocationSettings;
56 import java.util.ArrayList;
57 import java.util.Date;
58 import java.util.HashSet;
59 import java.util.List;
61 import static android.content.Intent.EXTRA_USER;
63 /** Manages settings for Google Account. */
64 public class ManageAccountsSettings extends AccountPreferenceBase
65 implements AuthenticatorHelper.OnAccountsUpdateListener {
66 private static final String ACCOUNT_KEY = "account"; // to pass to auth settings
67 public static final String KEY_ACCOUNT_TYPE = "account_type";
68 public static final String KEY_ACCOUNT_LABEL = "account_label";
70 // Action name for the broadcast intent when the Google account preferences page is launching
71 // the location settings.
72 private static final String LAUNCHING_LOCATION_SETTINGS =
73 "com.android.settings.accounts.LAUNCHING_LOCATION_SETTINGS";
75 private static final int MENU_SYNC_NOW_ID = Menu.FIRST;
76 private static final int MENU_SYNC_CANCEL_ID = Menu.FIRST + 1;
78 private static final int REQUEST_SHOW_SYNC_SETTINGS = 1;
80 private String[] mAuthorities;
81 private TextView mErrorInfoView;
83 // If an account type is set, then show only accounts of that type
84 private String mAccountType;
85 // Temporary hack, to deal with backward compatibility
86 // mFirstAccount is used for the injected preferences
87 private Account mFirstAccount;
90 public void onCreate(Bundle icicle) {
91 super.onCreate(icicle);
93 Bundle args = getArguments();
94 if (args != null && args.containsKey(KEY_ACCOUNT_TYPE)) {
95 mAccountType = args.getString(KEY_ACCOUNT_TYPE);
97 addPreferencesFromResource(R.xml.manage_accounts_settings);
98 setHasOptionsMenu(true);
102 public void onResume() {
104 mAuthenticatorHelper.listenToAccountUpdates();
105 updateAuthDescriptions();
106 showAccountsIfNeeded();
111 public View onCreateView(LayoutInflater inflater, ViewGroup container,
112 Bundle savedInstanceState) {
113 final View view = inflater.inflate(R.layout.manage_accounts_screen, container, false);
114 final ListView list = (ListView) view.findViewById(android.R.id.list);
115 Utils.prepareCustomPreferencesList(container, view, list, false);
120 public void onActivityCreated(Bundle savedInstanceState) {
121 super.onActivityCreated(savedInstanceState);
123 final Activity activity = getActivity();
124 final View view = getView();
126 mErrorInfoView = (TextView)view.findViewById(R.id.sync_settings_error_info);
127 mErrorInfoView.setVisibility(View.GONE);
129 mAuthorities = activity.getIntent().getStringArrayExtra(AUTHORITIES_FILTER_KEY);
131 Bundle args = getArguments();
132 if (args != null && args.containsKey(KEY_ACCOUNT_LABEL)) {
133 getActivity().setTitle(args.getString(KEY_ACCOUNT_LABEL));
138 public void onPause() {
140 mAuthenticatorHelper.stopListeningToAccountUpdates();
144 public void onStop() {
146 final Activity activity = getActivity();
147 activity.getActionBar().setDisplayOptions(0, ActionBar.DISPLAY_SHOW_CUSTOM);
148 activity.getActionBar().setCustomView(null);
152 public boolean onPreferenceTreeClick(PreferenceScreen preferences, Preference preference) {
153 if (preference instanceof AccountPreference) {
154 startAccountSettings((AccountPreference) preference);
161 private void startAccountSettings(AccountPreference acctPref) {
162 Bundle args = new Bundle();
163 args.putParcelable(AccountSyncSettings.ACCOUNT_KEY, acctPref.getAccount());
164 args.putParcelable(EXTRA_USER, mUserHandle);
165 ((SettingsActivity) getActivity()).startPreferencePanel(
166 AccountSyncSettings.class.getCanonicalName(), args,
167 R.string.account_sync_settings_title, acctPref.getAccount().name,
168 this, REQUEST_SHOW_SYNC_SETTINGS);
172 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
173 menu.add(0, MENU_SYNC_NOW_ID, 0, getString(R.string.sync_menu_sync_now))
174 .setIcon(R.drawable.ic_menu_refresh_holo_dark);
175 menu.add(0, MENU_SYNC_CANCEL_ID, 0, getString(R.string.sync_menu_sync_cancel))
176 .setIcon(com.android.internal.R.drawable.ic_menu_close_clear_cancel);
177 super.onCreateOptionsMenu(menu, inflater);
181 public void onPrepareOptionsMenu(Menu menu) {
182 super.onPrepareOptionsMenu(menu);
183 boolean syncActive = !ContentResolver.getCurrentSyncsAsUser(
184 mUserHandle.getIdentifier()).isEmpty();
185 menu.findItem(MENU_SYNC_NOW_ID).setVisible(!syncActive);
186 menu.findItem(MENU_SYNC_CANCEL_ID).setVisible(syncActive);
190 public boolean onOptionsItemSelected(MenuItem item) {
191 switch (item.getItemId()) {
192 case MENU_SYNC_NOW_ID:
193 requestOrCancelSyncForAccounts(true);
195 case MENU_SYNC_CANCEL_ID:
196 requestOrCancelSyncForAccounts(false);
199 return super.onOptionsItemSelected(item);
202 private void requestOrCancelSyncForAccounts(boolean sync) {
203 final int userId = mUserHandle.getIdentifier();
204 SyncAdapterType[] syncAdapters = ContentResolver.getSyncAdapterTypesAsUser(userId);
205 Bundle extras = new Bundle();
206 extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
207 int count = getPreferenceScreen().getPreferenceCount();
209 for (int i = 0; i < count; i++) {
210 Preference pref = getPreferenceScreen().getPreference(i);
211 if (pref instanceof AccountPreference) {
212 Account account = ((AccountPreference) pref).getAccount();
213 // For all available sync authorities, sync those that are enabled for the account
214 for (int j = 0; j < syncAdapters.length; j++) {
215 SyncAdapterType sa = syncAdapters[j];
216 if (syncAdapters[j].accountType.equals(mAccountType)
217 && ContentResolver.getSyncAutomaticallyAsUser(account, sa.authority,
220 ContentResolver.requestSyncAsUser(account, sa.authority, userId,
223 ContentResolver.cancelSyncAsUser(account, sa.authority, userId);
232 protected void onSyncStateUpdated() {
234 // Catch any delayed delivery of update messages
235 final Activity activity = getActivity();
236 if (activity != null) {
237 activity.invalidateOptionsMenu();
242 * Shows the sync state of the accounts. Note: it must be called after the accounts have been
243 * loaded, @see #showAccountsIfNeeded().
245 private void showSyncState() {
246 // Catch any delayed delivery of update messages
247 if (getActivity() == null || getActivity().isFinishing()) return;
249 final int userId = mUserHandle.getIdentifier();
251 // iterate over all the preferences, setting the state properly for each
252 List<SyncInfo> currentSyncs = ContentResolver.getCurrentSyncsAsUser(userId);
254 boolean anySyncFailed = false; // true if sync on any account failed
255 Date date = new Date();
257 // only track userfacing sync adapters when deciding if account is synced or not
258 final SyncAdapterType[] syncAdapters = ContentResolver.getSyncAdapterTypesAsUser(userId);
259 HashSet<String> userFacing = new HashSet<String>();
260 for (int k = 0, n = syncAdapters.length; k < n; k++) {
261 final SyncAdapterType sa = syncAdapters[k];
262 if (sa.isUserVisible()) {
263 userFacing.add(sa.authority);
266 for (int i = 0, count = getPreferenceScreen().getPreferenceCount(); i < count; i++) {
267 Preference pref = getPreferenceScreen().getPreference(i);
268 if (! (pref instanceof AccountPreference)) {
272 AccountPreference accountPref = (AccountPreference) pref;
273 Account account = accountPref.getAccount();
275 long lastSuccessTime = 0;
276 boolean syncIsFailing = false;
277 final ArrayList<String> authorities = accountPref.getAuthorities();
278 boolean syncingNow = false;
279 if (authorities != null) {
280 for (String authority : authorities) {
281 SyncStatusInfo status = ContentResolver.getSyncStatusAsUser(account, authority,
283 boolean syncEnabled = isSyncEnabled(userId, account, authority);
284 boolean authorityIsPending = ContentResolver.isSyncPending(account, authority);
285 boolean activelySyncing = isSyncing(currentSyncs, account, authority);
286 boolean lastSyncFailed = status != null
288 && status.lastFailureTime != 0
289 && status.getLastFailureMesgAsInt(0)
290 != ContentResolver.SYNC_ERROR_SYNC_ALREADY_IN_PROGRESS;
291 if (lastSyncFailed && !activelySyncing && !authorityIsPending) {
292 syncIsFailing = true;
293 anySyncFailed = true;
295 syncingNow |= activelySyncing;
296 if (status != null && lastSuccessTime < status.lastSuccessTime) {
297 lastSuccessTime = status.lastSuccessTime;
299 syncCount += syncEnabled && userFacing.contains(authority) ? 1 : 0;
302 if (Log.isLoggable(TAG, Log.VERBOSE)) {
303 Log.v(TAG, "no syncadapters found for " + account);
307 accountPref.setSyncStatus(AccountPreference.SYNC_ERROR, true);
308 } else if (syncCount == 0) {
309 accountPref.setSyncStatus(AccountPreference.SYNC_DISABLED, true);
310 } else if (syncCount > 0) {
312 accountPref.setSyncStatus(AccountPreference.SYNC_IN_PROGRESS, true);
314 accountPref.setSyncStatus(AccountPreference.SYNC_ENABLED, true);
315 if (lastSuccessTime > 0) {
316 accountPref.setSyncStatus(AccountPreference.SYNC_ENABLED, false);
317 date.setTime(lastSuccessTime);
318 final String timeString = formatSyncDate(date);
319 accountPref.setSummary(getResources().getString(
320 R.string.last_synced, timeString));
324 accountPref.setSyncStatus(AccountPreference.SYNC_DISABLED, true);
328 mErrorInfoView.setVisibility(anySyncFailed ? View.VISIBLE : View.GONE);
332 private boolean isSyncing(List<SyncInfo> currentSyncs, Account account, String authority) {
333 final int count = currentSyncs.size();
334 for (int i = 0; i < count; i++) {
335 SyncInfo syncInfo = currentSyncs.get(i);
336 if (syncInfo.account.equals(account) && syncInfo.authority.equals(authority)) {
343 private boolean isSyncEnabled(int userId, Account account, String authority) {
344 return ContentResolver.getSyncAutomaticallyAsUser(account, authority, userId)
345 && ContentResolver.getMasterSyncAutomaticallyAsUser(userId)
346 && (ContentResolver.getIsSyncableAsUser(account, authority, userId) > 0);
350 public void onAccountsUpdate(UserHandle userHandle) {
351 showAccountsIfNeeded();
352 onSyncStateUpdated();
355 private void showAccountsIfNeeded() {
356 if (getActivity() == null) return;
357 Account[] accounts = AccountManager.get(getActivity()).getAccountsAsUser(
358 mUserHandle.getIdentifier());
359 getPreferenceScreen().removeAll();
360 mFirstAccount = null;
361 addPreferencesFromResource(R.xml.manage_accounts_settings);
362 for (int i = 0, n = accounts.length; i < n; i++) {
363 final Account account = accounts[i];
364 // If an account type is specified for this screen, skip other types
365 if (mAccountType != null && !account.type.equals(mAccountType)) continue;
366 final ArrayList<String> auths = getAuthoritiesForAccountType(account.type);
368 boolean showAccount = true;
369 if (mAuthorities != null && auths != null) {
371 for (String requestedAuthority : mAuthorities) {
372 if (auths.contains(requestedAuthority)) {
380 final Drawable icon = getDrawableForType(account.type);
381 final AccountPreference preference =
382 new AccountPreference(getActivity(), account, icon, auths, false);
383 getPreferenceScreen().addPreference(preference);
384 if (mFirstAccount == null) {
385 mFirstAccount = account;
389 if (mAccountType != null && mFirstAccount != null) {
390 addAuthenticatorSettings();
392 // There's no account, close activity
397 private void addAuthenticatorSettings() {
398 PreferenceScreen prefs = addPreferencesForType(mAccountType, getPreferenceScreen());
400 updatePreferenceIntents(prefs);
404 /** Listens to a preference click event and starts a fragment */
405 private class FragmentStarter
406 implements Preference.OnPreferenceClickListener {
407 private final String mClass;
408 private final int mTitleRes;
411 * @param className the class name of the fragment to be started.
412 * @param title the title resource id of the started preference panel.
414 public FragmentStarter(String className, int title) {
420 public boolean onPreferenceClick(Preference preference) {
421 ((SettingsActivity) getActivity()).startPreferencePanel(
422 mClass, null, mTitleRes, null, null, 0);
423 // Hack: announce that the Google account preferences page is launching the location
425 if (mClass.equals(LocationSettings.class.getName())) {
426 Intent intent = new Intent(LAUNCHING_LOCATION_SETTINGS);
427 getActivity().sendBroadcast(
428 intent, android.Manifest.permission.WRITE_SECURE_SETTINGS);
435 * Filters through the preference list provided by GoogleLoginService.
437 * This method removes all the invalid intent from the list, adds account name as extra into the
438 * intent, and hack the location settings to start it as a fragment.
440 private void updatePreferenceIntents(PreferenceScreen prefs) {
441 final PackageManager pm = getActivity().getPackageManager();
442 for (int i = 0; i < prefs.getPreferenceCount();) {
443 Preference pref = prefs.getPreference(i);
444 Intent intent = pref.getIntent();
445 if (intent != null) {
446 // Hack. Launch "Location" as fragment instead of as activity.
448 // When "Location" is launched as activity via Intent, there's no "Up" button at the
449 // top left, and if there's another running instance of "Location" activity, the
450 // back stack would usually point to some other place so the user won't be able to
451 // go back to the previous page by "back" key. Using fragment is a much easier
452 // solution to those problems.
454 // If we set Intent to null and assign a fragment to the PreferenceScreen item here,
455 // in order to make it work as expected, we still need to modify the container
456 // PreferenceActivity, override onPreferenceStartFragment() and call
457 // startPreferencePanel() there. In order to inject the title string there, more
458 // dirty further hack is still needed. It's much easier and cleaner to listen to
459 // preference click event here directly.
460 if (intent.getAction().equals(
461 android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)) {
462 // The OnPreferenceClickListener overrides the click event completely. No intent
464 pref.setOnPreferenceClickListener(new FragmentStarter(
465 LocationSettings.class.getName(),
466 R.string.location_settings_title));
468 ResolveInfo ri = pm.resolveActivityAsUser(intent,
469 PackageManager.MATCH_DEFAULT_ONLY, mUserHandle.getIdentifier());
471 prefs.removePreference(pref);
474 intent.putExtra(ACCOUNT_KEY, mFirstAccount);
475 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
476 pref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
478 public boolean onPreferenceClick(Preference preference) {
479 Intent prefIntent = preference.getIntent();
481 * Check the intent to see if it resolves to a exported=false
482 * activity that doesn't share a uid with the authenticator.
484 * Otherwise the intent is considered unsafe in that it will be
485 * exploiting the fact that settings has system privileges.
487 if (isSafeIntent(pm, prefIntent)) {
488 getActivity().startActivityAsUser(prefIntent, mUserHandle);
491 "Refusing to launch authenticator intent because"
492 + "it exploits Settings permissions: "
506 * Determines if the supplied Intent is safe. A safe intent is one that is
507 * will launch a exported=true activity or owned by the same uid as the
508 * authenticator supplying the intent.
510 private boolean isSafeIntent(PackageManager pm, Intent intent) {
511 AuthenticatorDescription authDesc =
512 mAuthenticatorHelper.getAccountTypeDescription(mAccountType);
513 ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
514 if (resolveInfo == null) {
517 ActivityInfo resolvedActivityInfo = resolveInfo.activityInfo;
518 ApplicationInfo resolvedAppInfo = resolvedActivityInfo.applicationInfo;
520 ApplicationInfo authenticatorAppInf = pm.getApplicationInfo(authDesc.packageName, 0);
521 return resolvedActivityInfo.exported
522 || resolvedAppInfo.uid == authenticatorAppInf.uid;
523 } catch (NameNotFoundException e) {
525 "Intent considered unsafe due to exception.",
532 protected void onAuthDescriptionsUpdated() {
533 // Update account icons for all account preference items
534 for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
535 Preference pref = getPreferenceScreen().getPreference(i);
536 if (pref instanceof AccountPreference) {
537 AccountPreference accPref = (AccountPreference) pref;
538 accPref.setSummary(getLabelForType(accPref.getAccount().type));