AccountSetupOptions.java revision a4482e865dd3b219be672898df13dbbf1f4ae48d
1/*
2 * Copyright (C) 2008 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.email.activity.setup;
18
19import com.android.email.Email;
20import com.android.email.R;
21import com.android.email.mail.Store;
22import com.android.email.mail.store.ExchangeStore;
23import com.android.email.provider.EmailContent;
24
25import android.accounts.AccountManagerCallback;
26import android.accounts.AccountManagerFuture;
27import android.accounts.AuthenticatorException;
28import android.accounts.OperationCanceledException;
29import android.app.Activity;
30import android.app.AlertDialog;
31import android.content.DialogInterface;
32import android.content.Intent;
33import android.os.Bundle;
34import android.os.Handler;
35import android.util.Log;
36import android.view.View;
37import android.view.View.OnClickListener;
38import android.widget.ArrayAdapter;
39import android.widget.CheckBox;
40import android.widget.Spinner;
41
42import java.io.IOException;
43
44public class AccountSetupOptions extends Activity implements OnClickListener {
45
46    private static final String EXTRA_ACCOUNT = "account";
47    private static final String EXTRA_MAKE_DEFAULT = "makeDefault";
48    private static final String EXTRA_EAS_FLOW = "easFlow";
49
50    private Spinner mCheckFrequencyView;
51    private Spinner mSyncWindowView;
52    private CheckBox mDefaultView;
53    private CheckBox mNotifyView;
54    private CheckBox mSyncContactsView;
55    private EmailContent.Account mAccount;
56    private boolean mEasFlowMode;
57    private Handler mHandler = new Handler();
58
59    public static void actionOptions(Activity fromActivity, EmailContent.Account account,
60            boolean makeDefault, boolean easFlowMode) {
61        Intent i = new Intent(fromActivity, AccountSetupOptions.class);
62        i.putExtra(EXTRA_ACCOUNT, account);
63        i.putExtra(EXTRA_MAKE_DEFAULT, makeDefault);
64        i.putExtra(EXTRA_EAS_FLOW, easFlowMode);
65        fromActivity.startActivity(i);
66    }
67
68    @Override
69    public void onCreate(Bundle savedInstanceState) {
70        super.onCreate(savedInstanceState);
71        setContentView(R.layout.account_setup_options);
72
73        mCheckFrequencyView = (Spinner)findViewById(R.id.account_check_frequency);
74        mSyncWindowView = (Spinner) findViewById(R.id.account_sync_window);
75        mDefaultView = (CheckBox)findViewById(R.id.account_default);
76        mNotifyView = (CheckBox)findViewById(R.id.account_notify);
77        mSyncContactsView = (CheckBox) findViewById(R.id.account_sync_contacts);
78
79        findViewById(R.id.next).setOnClickListener(this);
80
81        mAccount = (EmailContent.Account) getIntent().getParcelableExtra(EXTRA_ACCOUNT);
82        boolean makeDefault = getIntent().getBooleanExtra(EXTRA_MAKE_DEFAULT, false);
83
84        // Generate spinner entries using XML arrays used by the preferences
85        int frequencyValuesId;
86        int frequencyEntriesId;
87        Store.StoreInfo info = Store.StoreInfo.getStoreInfo(mAccount.getStoreUri(this), this);
88        if (info.mPushSupported) {
89            frequencyValuesId = R.array.account_settings_check_frequency_values_push;
90            frequencyEntriesId = R.array.account_settings_check_frequency_entries_push;
91        } else {
92            frequencyValuesId = R.array.account_settings_check_frequency_values;
93            frequencyEntriesId = R.array.account_settings_check_frequency_entries;
94        }
95        CharSequence[] frequencyValues = getResources().getTextArray(frequencyValuesId);
96        CharSequence[] frequencyEntries = getResources().getTextArray(frequencyEntriesId);
97
98        // Now create the array used by the Spinner
99        SpinnerOption[] checkFrequencies = new SpinnerOption[frequencyEntries.length];
100        for (int i = 0; i < frequencyEntries.length; i++) {
101            checkFrequencies[i] = new SpinnerOption(
102                    Integer.valueOf(frequencyValues[i].toString()), frequencyEntries[i].toString());
103        }
104
105        ArrayAdapter<SpinnerOption> checkFrequenciesAdapter = new ArrayAdapter<SpinnerOption>(this,
106                android.R.layout.simple_spinner_item, checkFrequencies);
107        checkFrequenciesAdapter
108                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
109        mCheckFrequencyView.setAdapter(checkFrequenciesAdapter);
110
111        if (info.mVisibleLimitDefault == -1) {
112            enableEASSyncWindowSpinner();
113        }
114
115        // Note:  It is OK to use mAccount.mIsDefault here *only* because the account
116        // has not been written to the DB yet.  Ordinarily, call Account.getDefaultAccountId().
117        if (mAccount.mIsDefault || makeDefault) {
118            mDefaultView.setChecked(true);
119        }
120        mNotifyView.setChecked(
121                (mAccount.getFlags() & EmailContent.Account.FLAGS_NOTIFY_NEW_MAIL) != 0);
122        SpinnerOption.setSpinnerOptionValue(mCheckFrequencyView, mAccount
123                .getSyncInterval());
124
125        // Setup any additional items to support EAS & EAS flow mode
126        mEasFlowMode = getIntent().getBooleanExtra(EXTRA_EAS_FLOW, false);
127        if ("eas".equals(info.mScheme)) {
128            // "also sync contacts" == "true"
129            mSyncContactsView.setVisibility(View.VISIBLE);
130            mSyncContactsView.setChecked(true);
131        }
132    }
133
134    AccountManagerCallback<Bundle> mAccountManagerCallback = new AccountManagerCallback<Bundle>() {
135        public void run(AccountManagerFuture<Bundle> future) {
136            try {
137                Bundle bundle = future.getResult();
138                bundle.keySet();
139                mHandler.post(new Runnable() {
140                    public void run() {
141                        finishOnDone();
142                    }
143                });
144                return;
145            } catch (OperationCanceledException e) {
146                Log.d(Email.LOG_TAG, "addAccount was canceled");
147            } catch (IOException e) {
148                Log.d(Email.LOG_TAG, "addAccount failed: " + e);
149            } catch (AuthenticatorException e) {
150                Log.d(Email.LOG_TAG, "addAccount failed: " + e);
151            }
152            showErrorDialog(R.string.account_setup_failed_dlg_auth_message,
153                    R.string.system_account_create_failed);
154        }
155    };
156
157    private void showErrorDialog(final int msgResId, final Object... args) {
158        mHandler.post(new Runnable() {
159            public void run() {
160                new AlertDialog.Builder(AccountSetupOptions.this)
161                        .setIcon(android.R.drawable.ic_dialog_alert)
162                        .setTitle(getString(R.string.account_setup_failed_dlg_title))
163                        .setMessage(getString(msgResId, args))
164                        .setCancelable(true)
165                        .setPositiveButton(
166                                getString(R.string.account_setup_failed_dlg_edit_details_action),
167                                new DialogInterface.OnClickListener() {
168                                    public void onClick(DialogInterface dialog, int which) {
169                                       finish();
170                                    }
171                                })
172                        .show();
173            }
174        });
175    }
176    private void finishOnDone() {
177        AccountSettingsUtils.commitSettings(this, mAccount);
178        Email.setServicesEnabled(this);
179        AccountSetupNames.actionSetNames(this, mAccount.mId, mEasFlowMode);
180        // Start up SyncManager (if it isn't already running)
181        startService(new Intent(getApplicationContext(), com.android.exchange.SyncManager.class));
182        finish();
183    }
184
185    private void onDone() {
186        mAccount.setDisplayName(mAccount.getEmailAddress());
187        int newFlags = mAccount.getFlags() & ~(EmailContent.Account.FLAGS_NOTIFY_NEW_MAIL);
188        if (mNotifyView.isChecked()) {
189            newFlags |= EmailContent.Account.FLAGS_NOTIFY_NEW_MAIL;
190        }
191        mAccount.setFlags(newFlags);
192        mAccount.setSyncInterval((Integer)((SpinnerOption)mCheckFrequencyView
193                .getSelectedItem()).value);
194        if (mSyncWindowView.getVisibility() == View.VISIBLE) {
195            int window = (Integer)((SpinnerOption)mSyncWindowView.getSelectedItem()).value;
196            mAccount.setSyncLookback(window);
197        }
198        mAccount.setDefaultAccount(mDefaultView.isChecked());
199
200        // Call EAS to store account information for use by AccountManager
201        if (!mAccount.isSaved()
202                && mAccount.mHostAuthRecv != null
203                && mAccount.mHostAuthRecv.mProtocol.equals("eas")) {
204            boolean alsoSyncContacts = mSyncContactsView.isChecked();
205            ExchangeStore.addSystemAccount(this, mAccount,
206                    alsoSyncContacts, mAccountManagerCallback);
207        } else {
208            finishOnDone();
209       }
210    }
211
212    public void onClick(View v) {
213        switch (v.getId()) {
214            case R.id.next:
215                onDone();
216                break;
217        }
218    }
219
220    /**
221     * Enable an additional spinner using the arrays normally handled by preferences
222     */
223    private void enableEASSyncWindowSpinner() {
224        // Show everything
225        findViewById(R.id.account_sync_window_label).setVisibility(View.VISIBLE);
226        mSyncWindowView.setVisibility(View.VISIBLE);
227
228        // Generate spinner entries using XML arrays used by the preferences
229        CharSequence[] windowValues = getResources().getTextArray(
230                R.array.account_settings_mail_window_values);
231        CharSequence[] windowEntries = getResources().getTextArray(
232                R.array.account_settings_mail_window_entries);
233
234        // Now create the array used by the Spinner
235        SpinnerOption[] windowOptions = new SpinnerOption[windowEntries.length];
236        for (int i = 0; i < windowEntries.length; i++) {
237            windowOptions[i] = new SpinnerOption(
238                    Integer.valueOf(windowValues[i].toString()), windowEntries[i].toString());
239        }
240
241        ArrayAdapter<SpinnerOption> windowOptionsAdapter = new ArrayAdapter<SpinnerOption>(this,
242                android.R.layout.simple_spinner_item, windowOptions);
243        windowOptionsAdapter
244                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
245        mSyncWindowView.setAdapter(windowOptionsAdapter);
246
247        SpinnerOption.setSpinnerOptionValue(mSyncWindowView, mAccount.getSyncLookback());
248    }
249}
250