FdnSetting.java revision 5efb112905b222d1a5b2e1052a94b7a7dfbe66d2
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.phone.settings.fdn;
18
19import android.app.ActionBar;
20import android.app.AlertDialog;
21import android.content.DialogInterface;
22import android.os.AsyncResult;
23import android.os.Bundle;
24import android.os.Handler;
25import android.os.Message;
26import android.util.Log;
27import android.preference.PreferenceActivity;
28import android.preference.PreferenceScreen;
29import android.view.MenuItem;
30import android.view.WindowManager;
31import android.widget.Toast;
32
33import com.android.internal.telephony.CommandException;
34import com.android.internal.telephony.Phone;
35import com.android.phone.CallFeaturesSetting;
36import com.android.phone.PhoneGlobals;
37import com.android.phone.R;
38import com.android.phone.SubscriptionInfoHelper;
39
40/**
41 * FDN settings UI for the Phone app.
42 * Rewritten to look and behave closer to the other preferences.
43 */
44public class FdnSetting extends PreferenceActivity
45        implements EditPinPreference.OnPinEnteredListener, DialogInterface.OnCancelListener {
46
47    private static final String LOG_TAG = PhoneGlobals.LOG_TAG;
48    private static final boolean DBG = false;
49
50    private SubscriptionInfoHelper mSubscriptionInfoHelper;
51    private Phone mPhone;
52
53    /**
54     * Events we handle.
55     * The first is used for toggling FDN enable, the second for the PIN change.
56     */
57    private static final int EVENT_PIN2_ENTRY_COMPLETE = 100;
58    private static final int EVENT_PIN2_CHANGE_COMPLETE = 200;
59
60    // String keys for preference lookup
61    private static final String BUTTON_FDN_ENABLE_KEY = "button_fdn_enable_key";
62    private static final String BUTTON_CHANGE_PIN2_KEY = "button_change_pin2_key";
63    private static final String FDN_LIST_PREF_SCREEN_KEY = "fdn_list_pref_screen_key";
64
65    private EditPinPreference mButtonEnableFDN;
66    private EditPinPreference mButtonChangePin2;
67
68    // State variables
69    private String mOldPin;
70    private String mNewPin;
71    private String mPuk2;
72    private static final int PIN_CHANGE_OLD = 0;
73    private static final int PIN_CHANGE_NEW = 1;
74    private static final int PIN_CHANGE_REENTER = 2;
75    private static final int PIN_CHANGE_PUK = 3;
76    private static final int PIN_CHANGE_NEW_PIN_FOR_PUK = 4;
77    private static final int PIN_CHANGE_REENTER_PIN_FOR_PUK = 5;
78    private int mPinChangeState;
79    private boolean mIsPuk2Locked;    // Indicates we know that we are PUK2 blocked.
80
81    private static final String SKIP_OLD_PIN_KEY = "skip_old_pin_key";
82    private static final String PIN_CHANGE_STATE_KEY = "pin_change_state_key";
83    private static final String OLD_PIN_KEY = "old_pin_key";
84    private static final String NEW_PIN_KEY = "new_pin_key";
85    private static final String DIALOG_MESSAGE_KEY = "dialog_message_key";
86    private static final String DIALOG_PIN_ENTRY_KEY = "dialog_pin_entry_key";
87
88    // size limits for the pin.
89    private static final int MIN_PIN_LENGTH = 4;
90    private static final int MAX_PIN_LENGTH = 8;
91
92    /**
93     * Delegate to the respective handlers.
94     */
95    @Override
96    public void onPinEntered(EditPinPreference preference, boolean positiveResult) {
97        if (preference == mButtonEnableFDN) {
98            toggleFDNEnable(positiveResult);
99        } else if (preference == mButtonChangePin2){
100            updatePINChangeState(positiveResult);
101        }
102    }
103
104    /**
105     * Attempt to toggle FDN activation.
106     */
107    private void toggleFDNEnable(boolean positiveResult) {
108        if (!positiveResult) {
109            return;
110        }
111
112        // validate the pin first, before submitting it to the RIL for FDN enable.
113        String password = mButtonEnableFDN.getText();
114        if (validatePin (password, false)) {
115            // get the relevant data for the icc call
116            boolean isEnabled = mPhone.getIccCard().getIccFdnEnabled();
117            Message onComplete = mFDNHandler.obtainMessage(EVENT_PIN2_ENTRY_COMPLETE);
118
119            // make fdn request
120            mPhone.getIccCard().setIccFdnEnabled(!isEnabled, password, onComplete);
121        } else {
122            // throw up error if the pin is invalid.
123            displayMessage(R.string.invalidPin2);
124        }
125
126        mButtonEnableFDN.setText("");
127    }
128
129    /**
130     * Attempt to change the pin.
131     */
132    private void updatePINChangeState(boolean positiveResult) {
133        if (DBG) log("updatePINChangeState positive=" + positiveResult
134                + " mPinChangeState=" + mPinChangeState
135                + " mSkipOldPin=" + mIsPuk2Locked);
136
137        if (!positiveResult) {
138            // reset the state on cancel, either to expect PUK2 or PIN2
139            if (!mIsPuk2Locked) {
140                resetPinChangeState();
141            } else {
142                resetPinChangeStateForPUK2();
143            }
144            return;
145        }
146
147        // Progress through the dialog states, generally in this order:
148        //   1. Enter old pin
149        //   2. Enter new pin
150        //   3. Re-Enter new pin
151        // While handling any error conditions that may show up in between.
152        // Also handle the PUK2 entry, if it is requested.
153        //
154        // In general, if any invalid entries are made, the dialog re-
155        // appears with text to indicate what the issue is.
156        switch (mPinChangeState) {
157            case PIN_CHANGE_OLD:
158                mOldPin = mButtonChangePin2.getText();
159                mButtonChangePin2.setText("");
160                // if the pin is not valid, display a message and reset the state.
161                if (validatePin (mOldPin, false)) {
162                    mPinChangeState = PIN_CHANGE_NEW;
163                    displayPinChangeDialog();
164                } else {
165                    displayPinChangeDialog(R.string.invalidPin2, true);
166                }
167                break;
168            case PIN_CHANGE_NEW:
169                mNewPin = mButtonChangePin2.getText();
170                mButtonChangePin2.setText("");
171                // if the new pin is not valid, display a message and reset the state.
172                if (validatePin (mNewPin, false)) {
173                    mPinChangeState = PIN_CHANGE_REENTER;
174                    displayPinChangeDialog();
175                } else {
176                    displayPinChangeDialog(R.string.invalidPin2, true);
177                }
178                break;
179            case PIN_CHANGE_REENTER:
180                // if the re-entered pin is not valid, display a message and reset the state.
181                if (!mNewPin.equals(mButtonChangePin2.getText())) {
182                    mPinChangeState = PIN_CHANGE_NEW;
183                    mButtonChangePin2.setText("");
184                    displayPinChangeDialog(R.string.mismatchPin2, true);
185                } else {
186                    // If the PIN is valid, then we submit the change PIN request.
187                    mButtonChangePin2.setText("");
188                    Message onComplete = mFDNHandler.obtainMessage(
189                            EVENT_PIN2_CHANGE_COMPLETE);
190                    mPhone.getIccCard().changeIccFdnPassword(
191                            mOldPin, mNewPin, onComplete);
192                }
193                break;
194            case PIN_CHANGE_PUK: {
195                    // Doh! too many incorrect requests, PUK requested.
196                    mPuk2 = mButtonChangePin2.getText();
197                    mButtonChangePin2.setText("");
198                    // if the puk is not valid, display
199                    // a message and reset the state.
200                    if (validatePin (mPuk2, true)) {
201                        mPinChangeState = PIN_CHANGE_NEW_PIN_FOR_PUK;
202                        displayPinChangeDialog();
203                    } else {
204                        displayPinChangeDialog(R.string.invalidPuk2, true);
205                    }
206                }
207                break;
208            case PIN_CHANGE_NEW_PIN_FOR_PUK:
209                mNewPin = mButtonChangePin2.getText();
210                mButtonChangePin2.setText("");
211                // if the new pin is not valid, display
212                // a message and reset the state.
213                if (validatePin (mNewPin, false)) {
214                    mPinChangeState = PIN_CHANGE_REENTER_PIN_FOR_PUK;
215                    displayPinChangeDialog();
216                } else {
217                    displayPinChangeDialog(R.string.invalidPin2, true);
218                }
219                break;
220            case PIN_CHANGE_REENTER_PIN_FOR_PUK:
221                // if the re-entered pin is not valid, display
222                // a message and reset the state.
223                if (!mNewPin.equals(mButtonChangePin2.getText())) {
224                    mPinChangeState = PIN_CHANGE_NEW_PIN_FOR_PUK;
225                    mButtonChangePin2.setText("");
226                    displayPinChangeDialog(R.string.mismatchPin2, true);
227                } else {
228                    // Both puk2 and new pin2 are ready to submit
229                    mButtonChangePin2.setText("");
230                    Message onComplete = mFDNHandler.obtainMessage(
231                            EVENT_PIN2_CHANGE_COMPLETE);
232                    mPhone.getIccCard().supplyPuk2(mPuk2, mNewPin, onComplete);
233                }
234                break;
235        }
236    }
237
238    /**
239     * Handler for asynchronous replies from the sim.
240     */
241    private final Handler mFDNHandler = new Handler() {
242        @Override
243        public void handleMessage(Message msg) {
244            switch (msg.what) {
245
246                // when we are enabling FDN, either we are unsuccessful and display
247                // a toast, or just update the UI.
248                case EVENT_PIN2_ENTRY_COMPLETE: {
249                        AsyncResult ar = (AsyncResult) msg.obj;
250                        if (ar.exception != null && ar.exception instanceof CommandException) {
251                            int attemptsRemaining = msg.arg1;
252                            // see if PUK2 is requested and alert the user accordingly.
253                            CommandException.Error e =
254                                    ((CommandException) ar.exception).getCommandError();
255                            switch (e) {
256                                case SIM_PUK2:
257                                    // make sure we set the PUK2 state so that we can skip
258                                    // some redundant behaviour.
259                                    displayMessage(R.string.fdn_enable_puk2_requested,
260                                            attemptsRemaining);
261                                    resetPinChangeStateForPUK2();
262                                    break;
263                                case PASSWORD_INCORRECT:
264                                    displayMessage(R.string.pin2_invalid, attemptsRemaining);
265                                    break;
266                                default:
267                                    displayMessage(R.string.fdn_failed, attemptsRemaining);
268                                    break;
269                            }
270                        }
271                        updateEnableFDN();
272                    }
273                    break;
274
275                // when changing the pin we need to pay attention to whether or not
276                // the error requests a PUK (usually after too many incorrect tries)
277                // Set the state accordingly.
278                case EVENT_PIN2_CHANGE_COMPLETE: {
279                        if (DBG)
280                            log("Handle EVENT_PIN2_CHANGE_COMPLETE");
281                        AsyncResult ar = (AsyncResult) msg.obj;
282                        if (ar.exception != null) {
283                            int attemptsRemaining = msg.arg1;
284                            log("Handle EVENT_PIN2_CHANGE_COMPLETE attemptsRemaining="
285                                    + attemptsRemaining);
286                            CommandException ce = (CommandException) ar.exception;
287                            if (ce.getCommandError() == CommandException.Error.SIM_PUK2) {
288                                // throw an alert dialog on the screen, displaying the
289                                // request for a PUK2.  set the cancel listener to
290                                // FdnSetting.onCancel().
291                                AlertDialog a = new AlertDialog.Builder(FdnSetting.this)
292                                    .setMessage(R.string.puk2_requested)
293                                    .setCancelable(true)
294                                    .setOnCancelListener(FdnSetting.this)
295                                    .create();
296                                a.getWindow().addFlags(
297                                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
298                                a.show();
299                            } else {
300                                // set the correct error message depending upon the state.
301                                // Reset the state depending upon or knowledge of the PUK state.
302                                if (!mIsPuk2Locked) {
303                                    displayMessage(R.string.badPin2, attemptsRemaining);
304                                    resetPinChangeState();
305                                } else {
306                                    displayMessage(R.string.badPuk2, attemptsRemaining);
307                                    resetPinChangeStateForPUK2();
308                                }
309                            }
310                        } else {
311                            if (mPinChangeState == PIN_CHANGE_PUK) {
312                                displayMessage(R.string.pin2_unblocked);
313                            } else {
314                                displayMessage(R.string.pin2_changed);
315                            }
316
317                            // reset to normal behaviour on successful change.
318                            resetPinChangeState();
319                        }
320                    }
321                    break;
322            }
323        }
324    };
325
326    /**
327     * Cancel listener for the PUK2 request alert dialog.
328     */
329    @Override
330    public void onCancel(DialogInterface dialog) {
331        // set the state of the preference and then display the dialog.
332        resetPinChangeStateForPUK2();
333        displayPinChangeDialog(0, true);
334    }
335
336    /**
337     * Display a toast for message, like the rest of the settings.
338     */
339    private final void displayMessage(int strId, int attemptsRemaining) {
340        String s = getString(strId);
341        if ((strId == R.string.badPin2) || (strId == R.string.badPuk2) ||
342                (strId == R.string.pin2_invalid)) {
343            if (attemptsRemaining >= 0) {
344                s = getString(strId) + getString(R.string.pin2_attempts, attemptsRemaining);
345            } else {
346                s = getString(strId);
347            }
348        }
349        log("displayMessage: attemptsRemaining=" + attemptsRemaining + " s=" + s);
350        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
351    }
352
353    private final void displayMessage(int strId) {
354        displayMessage(strId, -1);
355    }
356
357    /**
358     * The next two functions are for updating the message field on the dialog.
359     */
360    private final void displayPinChangeDialog() {
361        displayPinChangeDialog(0, true);
362    }
363
364    private final void displayPinChangeDialog(int strId, boolean shouldDisplay) {
365        int msgId;
366        switch (mPinChangeState) {
367            case PIN_CHANGE_OLD:
368                msgId = R.string.oldPin2Label;
369                break;
370            case PIN_CHANGE_NEW:
371            case PIN_CHANGE_NEW_PIN_FOR_PUK:
372                msgId = R.string.newPin2Label;
373                break;
374            case PIN_CHANGE_REENTER:
375            case PIN_CHANGE_REENTER_PIN_FOR_PUK:
376                msgId = R.string.confirmPin2Label;
377                break;
378            case PIN_CHANGE_PUK:
379            default:
380                msgId = R.string.label_puk2_code;
381                break;
382        }
383
384        // append the note / additional message, if needed.
385        if (strId != 0) {
386            mButtonChangePin2.setDialogMessage(getText(msgId) + "\n" + getText(strId));
387        } else {
388            mButtonChangePin2.setDialogMessage(msgId);
389        }
390
391        // only display if requested.
392        if (shouldDisplay) {
393            mButtonChangePin2.showPinDialog();
394        }
395    }
396
397    /**
398     * Reset the state of the pin change dialog.
399     */
400    private final void resetPinChangeState() {
401        if (DBG) log("resetPinChangeState");
402        mPinChangeState = PIN_CHANGE_OLD;
403        displayPinChangeDialog(0, false);
404        mOldPin = mNewPin = "";
405        mIsPuk2Locked = false;
406    }
407
408    /**
409     * Reset the state of the pin change dialog solely for PUK2 use.
410     */
411    private final void resetPinChangeStateForPUK2() {
412        if (DBG) log("resetPinChangeStateForPUK2");
413        mPinChangeState = PIN_CHANGE_PUK;
414        displayPinChangeDialog(0, false);
415        mOldPin = mNewPin = mPuk2 = "";
416        mIsPuk2Locked = true;
417    }
418
419    /**
420     * Validate the pin entry.
421     *
422     * @param pin This is the pin to validate
423     * @param isPuk Boolean indicating whether we are to treat
424     * the pin input as a puk.
425     */
426    private boolean validatePin(String pin, boolean isPuk) {
427
428        // for pin, we have 4-8 numbers, or puk, we use only 8.
429        int pinMinimum = isPuk ? MAX_PIN_LENGTH : MIN_PIN_LENGTH;
430
431        // check validity
432        if (pin == null || pin.length() < pinMinimum || pin.length() > MAX_PIN_LENGTH) {
433            return false;
434        } else {
435            return true;
436        }
437    }
438
439    /**
440     * Reflect the updated FDN state in the UI.
441     */
442    private void updateEnableFDN() {
443        if (mPhone.getIccCard().getIccFdnEnabled()) {
444            mButtonEnableFDN.setTitle(R.string.enable_fdn_ok);
445            mButtonEnableFDN.setSummary(R.string.fdn_enabled);
446            mButtonEnableFDN.setDialogTitle(R.string.disable_fdn);
447        } else {
448            mButtonEnableFDN.setTitle(R.string.disable_fdn_ok);
449            mButtonEnableFDN.setSummary(R.string.fdn_disabled);
450            mButtonEnableFDN.setDialogTitle(R.string.enable_fdn);
451        }
452    }
453
454    @Override
455    protected void onCreate(Bundle icicle) {
456        super.onCreate(icicle);
457
458        mSubscriptionInfoHelper = new SubscriptionInfoHelper(getIntent());
459        mPhone = mSubscriptionInfoHelper.getPhone();
460
461        addPreferencesFromResource(R.xml.fdn_setting);
462
463        //get UI object references
464        PreferenceScreen prefSet = getPreferenceScreen();
465        mButtonEnableFDN = (EditPinPreference) prefSet.findPreference(BUTTON_FDN_ENABLE_KEY);
466        mButtonChangePin2 = (EditPinPreference) prefSet.findPreference(BUTTON_CHANGE_PIN2_KEY);
467
468        //assign click listener and update state
469        mButtonEnableFDN.setOnPinEnteredListener(this);
470        updateEnableFDN();
471
472        mButtonChangePin2.setOnPinEnteredListener(this);
473
474        PreferenceScreen fdnListPref =
475                (PreferenceScreen) prefSet.findPreference(FDN_LIST_PREF_SCREEN_KEY);
476        fdnListPref.setIntent(mSubscriptionInfoHelper.getIntent(this, FdnList.class));
477
478        // Only reset the pin change dialog if we're not in the middle of changing it.
479        if (icicle == null) {
480            resetPinChangeState();
481        } else {
482            mIsPuk2Locked = icicle.getBoolean(SKIP_OLD_PIN_KEY);
483            mPinChangeState = icicle.getInt(PIN_CHANGE_STATE_KEY);
484            mOldPin = icicle.getString(OLD_PIN_KEY);
485            mNewPin = icicle.getString(NEW_PIN_KEY);
486            mButtonChangePin2.setDialogMessage(icicle.getString(DIALOG_MESSAGE_KEY));
487            mButtonChangePin2.setText(icicle.getString(DIALOG_PIN_ENTRY_KEY));
488        }
489
490        ActionBar actionBar = getActionBar();
491        if (actionBar != null) {
492            // android.R.id.home will be triggered in onOptionsItemSelected()
493            actionBar.setDisplayHomeAsUpEnabled(true);
494            mSubscriptionInfoHelper.setActionBarTitle(
495                    actionBar, getResources(), R.string.fdn_with_label);
496        }
497    }
498
499    @Override
500    protected void onResume() {
501        super.onResume();
502        mPhone = mSubscriptionInfoHelper.getPhone();
503        updateEnableFDN();
504    }
505
506    /**
507     * Save the state of the pin change.
508     */
509    @Override
510    protected void onSaveInstanceState(Bundle out) {
511        super.onSaveInstanceState(out);
512        out.putBoolean(SKIP_OLD_PIN_KEY, mIsPuk2Locked);
513        out.putInt(PIN_CHANGE_STATE_KEY, mPinChangeState);
514        out.putString(OLD_PIN_KEY, mOldPin);
515        out.putString(NEW_PIN_KEY, mNewPin);
516        out.putString(DIALOG_MESSAGE_KEY, mButtonChangePin2.getDialogMessage().toString());
517        out.putString(DIALOG_PIN_ENTRY_KEY, mButtonChangePin2.getText());
518    }
519
520    @Override
521    public boolean onOptionsItemSelected(MenuItem item) {
522        final int itemId = item.getItemId();
523        if (itemId == android.R.id.home) {  // See ActionBar#setDisplayHomeAsUpEnabled()
524            CallFeaturesSetting.goUpToTopLevelSetting(this, mSubscriptionInfoHelper);
525            return true;
526        }
527        return super.onOptionsItemSelected(item);
528    }
529
530    private void log(String msg) {
531        Log.d(LOG_TAG, "FdnSetting: " + msg);
532    }
533}
534
535