PhoneUtils.java revision bab058c1c34d10f0707cf654e9ed917f631925d1
1/*
2 * Copyright (C) 2006 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;
18
19import android.app.ActivityManagerNative;
20import android.app.AlertDialog;
21import android.app.Dialog;
22import android.app.KeyguardManager;
23import android.app.ProgressDialog;
24import android.content.ComponentName;
25import android.content.Context;
26import android.content.DialogInterface;
27import android.content.Intent;
28import android.content.ServiceConnection;
29import android.media.AudioManager;
30import android.net.Uri;
31import android.os.AsyncResult;
32import android.os.Handler;
33import android.os.IBinder;
34import android.os.Message;
35import android.os.RemoteException;
36import android.provider.Contacts;
37import android.telephony.PhoneNumberUtils;
38import android.text.TextUtils;
39import android.util.Log;
40import android.view.KeyEvent;
41import android.view.LayoutInflater;
42import android.view.View;
43import android.view.WindowManager;
44import android.widget.EditText;
45import android.widget.Toast;
46
47import com.android.internal.telephony.Call;
48import com.android.internal.telephony.CallStateException;
49import com.android.internal.telephony.CallerInfo;
50import com.android.internal.telephony.CallerInfoAsyncQuery;
51import com.android.internal.telephony.Connection;
52import com.android.internal.telephony.IExtendedNetworkService;
53import com.android.internal.telephony.MmiCode;
54import com.android.internal.telephony.Phone;
55
56import java.util.Hashtable;
57import java.util.Iterator;
58import java.util.List;
59
60/**
61 * Misc utilities for the Phone app.
62 */
63public class PhoneUtils {
64    private static final String LOG_TAG = "PhoneUtils";
65    private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 2);
66
67    /** Control stack trace for Audio Mode settings */
68    private static final boolean DBG_SETAUDIOMODE_STACK = false;
69
70    /** Identifier for the "Add Call" intent extra. */
71    static final String ADD_CALL_MODE_KEY = "add_call_mode";
72
73    // Return codes from placeCall()
74    static final int CALL_STATUS_DIALED = 0;  // The number was successfully dialed
75    static final int CALL_STATUS_DIALED_MMI = 1;  // The specified number was an MMI code
76    static final int CALL_STATUS_FAILED = 2;  // The call failed
77
78    // State of the Phone's audio modes
79    // Each state can move to the other states, but within the state only certain
80    //  transitions for AudioManager.setMode() are allowed.
81    static final int AUDIO_IDLE = 0;  /** audio behaviour at phone idle */
82    static final int AUDIO_RINGING = 1;  /** audio behaviour while ringing */
83    static final int AUDIO_OFFHOOK = 2;  /** audio behaviour while in call. */
84    private static int sAudioBehaviourState = AUDIO_IDLE;
85
86    /** Speaker state, persisting between wired headset connection events */
87    private static boolean sIsSpeakerEnabled = false;
88
89    /** Hash table to store mute (Boolean) values based upon the connection.*/
90    private static Hashtable<Connection, Boolean> sConnectionMuteTable =
91        new Hashtable<Connection, Boolean>();
92
93    /** Static handler for the connection/mute tracking */
94    private static ConnectionHandler mConnectionHandler;
95
96    /** Phone state changed event*/
97    private static final int PHONE_STATE_CHANGED = -1;
98
99    /** Define for not a special CNAP string */
100    private static final int CNAP_SPECIAL_CASE_NO = -1;
101
102    // Extended network service interface instance
103    private static IExtendedNetworkService mNwService = null;
104    // used to cancel MMI command after 15 seconds timeout for NWService requirement
105    private static Message mMmiTimeoutCbMsg = null;
106
107    /**
108     * Handler that tracks the connections and updates the value of the
109     * Mute settings for each connection as needed.
110     */
111    private static class ConnectionHandler extends Handler {
112        public void handleMessage(Message msg) {
113            AsyncResult ar = (AsyncResult) msg.obj;
114            switch (msg.what) {
115                case PHONE_STATE_CHANGED:
116                    if (DBG) log("ConnectionHandler: updating mute state for each connection");
117
118                    Phone phone = (Phone) ar.userObj;
119
120                    // update the foreground connections, if there are new connections.
121                    List<Connection> fgConnections = phone.getForegroundCall().getConnections();
122                    for (Connection cn : fgConnections) {
123                        if (sConnectionMuteTable.get(cn) == null) {
124                            sConnectionMuteTable.put(cn, Boolean.FALSE);
125                        }
126                    }
127
128                    // update the background connections, if there are new connections.
129                    List<Connection> bgConnections = phone.getBackgroundCall().getConnections();
130                    for (Connection cn : bgConnections) {
131                        if (sConnectionMuteTable.get(cn) == null) {
132                            sConnectionMuteTable.put(cn, Boolean.FALSE);
133                        }
134                    }
135
136                    // Check to see if there are any lingering connections here
137                    // (disconnected connections), use old-school iterators to avoid
138                    // concurrent modification exceptions.
139                    Connection cn;
140                    for (Iterator<Connection> cnlist = sConnectionMuteTable.keySet().iterator();
141                            cnlist.hasNext();) {
142                        cn = cnlist.next();
143                        if (!fgConnections.contains(cn) && !bgConnections.contains(cn)) {
144                            if (DBG) log("connection: " + cn + "not accounted for, removing.");
145                            cnlist.remove();
146                        }
147                    }
148
149                    // Restore the mute state of the foreground call if we're not IDLE,
150                    // otherwise just clear the mute state. This is really saying that
151                    // as long as there is one or more connections, we should update
152                    // the mute state with the earliest connection on the foreground
153                    // call, and that with no connections, we should be back to a
154                    // non-mute state.
155                    if (phone.getState() != Phone.State.IDLE) {
156                        restoreMuteState(phone);
157                    } else {
158                        setMuteInternal(phone, false);
159                    }
160
161                    break;
162            }
163        }
164    }
165
166
167    private static ServiceConnection ExtendedNetworkServiceConnection = new ServiceConnection() {
168        public void onServiceConnected(ComponentName name, IBinder iBinder) {
169            if (DBG) log("Extended NW onServiceConnected");
170            mNwService = IExtendedNetworkService.Stub.asInterface(iBinder);
171        }
172
173        public void onServiceDisconnected(ComponentName arg0) {
174            if (DBG) log("Extended NW onServiceDisconnected");
175            mNwService = null;
176        }
177    };
178
179    /**
180     * Register the ConnectionHandler with the phone, to receive connection events
181     */
182    public static void initializeConnectionHandler(Phone phone) {
183        if (mConnectionHandler == null) {
184            mConnectionHandler = new ConnectionHandler();
185        }
186
187        phone.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, phone);
188        // Extended NW service
189        Intent intent = new Intent("com.android.ussd.IExtendedNetworkService");
190        phone.getContext().bindService(intent,
191                ExtendedNetworkServiceConnection, Context.BIND_AUTO_CREATE);
192        if (DBG) log("Extended NW bindService IExtendedNetworkService");
193
194    }
195
196    /** This class is never instantiated. */
197    private PhoneUtils() {
198    }
199
200    //static method to set the audio control state.
201    static void setAudioControlState(int newState) {
202        sAudioBehaviourState = newState;
203    }
204
205    /**
206     * Answer the currently-ringing call.
207     *
208     * @return true if we answered the call, or false if there wasn't
209     *         actually a ringing incoming call, or some other error occurred.
210     *
211     * @see answerAndEndHolding()
212     * @see answerAndEndActive()
213     */
214    static boolean answerCall(Phone phone) {
215        if (DBG) log("answerCall()...");
216
217        // If the ringer is currently ringing and/or vibrating, stop it
218        // right now (before actually answering the call.)
219        PhoneApp.getInstance().getRinger().stopRing();
220
221        PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK);
222
223        boolean answered = false;
224        Call call = phone.getRingingCall();
225
226        if (phone.getPhoneName().equals("CDMA")) {
227            // Stop any signalInfo tone being played when a Call waiting gets answered
228            if (call.getState() == Call.State.WAITING) {
229                final CallNotifier notifier = PhoneApp.getInstance().notifier;
230                notifier.stopSignalInfoTone();
231            }
232        }
233
234        if (call != null && call.isRinging()) {
235            if (DBG) log("answerCall: call state = " + call.getState());
236            try {
237                //if (DBG) log("sPhone.acceptCall");
238                phone.acceptCall();
239                answered = true;
240                setAudioMode(phone.getContext(), AudioManager.MODE_IN_CALL);
241                if (phone.getPhoneName().equals("CDMA")) {
242                    PhoneApp app = PhoneApp.getInstance();
243                    if (app.cdmaPhoneCallState.getCurrentCallState()
244                            == CdmaPhoneCallState.PhoneCallState.IDLE) {
245                        // This is the FIRST incoming call being answered.
246                        // Set the Phone Call State to SINGLE_ACTIVE
247                        app.cdmaPhoneCallState.setCurrentCallState(
248                                CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
249                    } else {
250                        // This is the CALL WAITING call being answered.
251                        // Set the Phone Call State to CONF_CALL
252                        app.cdmaPhoneCallState.setCurrentCallState(
253                                CdmaPhoneCallState.PhoneCallState.CONF_CALL);
254                    }
255                }
256            } catch (CallStateException ex) {
257                Log.w(LOG_TAG, "answerCall: caught " + ex, ex);
258            }
259        }
260        return answered;
261    }
262
263    /**
264     * Smart "hang up" helper method which hangs up exactly one connection,
265     * based on the current Phone state, as follows:
266     * <ul>
267     * <li>If there's a ringing call, hang that up.
268     * <li>Else if there's a foreground call, hang that up.
269     * <li>Else if there's a background call, hang that up.
270     * <li>Otherwise do nothing.
271     * </ul>
272     * @return true if we successfully hung up, or false
273     *              if there were no active calls at all.
274     */
275    static boolean hangup(Phone phone) {
276        boolean hungup = false;
277        Call ringing = phone.getRingingCall();
278        Call fg = phone.getForegroundCall();
279        Call bg = phone.getBackgroundCall();
280
281        if (!ringing.isIdle()) {
282            if (DBG) log("HANGUP ringing call");
283            hungup = hangup(ringing);
284        } else if (!fg.isIdle()) {
285            if (DBG) log("HANGUP foreground call");
286            hungup = hangup(fg);
287        } else if (!bg.isIdle()) {
288            if (DBG) log("HANGUP background call");
289            hungup = hangup(bg);
290        }
291
292        if (DBG) log("hungup=" + hungup);
293
294        return hungup;
295    }
296
297    static boolean hangupRingingCall(Phone phone) {
298        if (DBG) log("hangup ringing call");
299        Call ringing = phone.getRingingCall();
300
301        if (phone.getPhoneName().equals("CDMA")) {
302            // CDMA: Ringing call and Call waiting hangup is handled differently.
303            // For Call waiting we DO NOT call the conventional hangup(call) function
304            // as in CDMA we just want to hungup the Call waiting connection.
305            if (ringing.getState() == Call.State.INCOMING) {
306                if (DBG) log("hangup ringing call");
307                return hangup(ringing);
308            } else {
309                if (DBG) log("hangup Call waiting call");
310                final CallNotifier notifier = PhoneApp.getInstance().notifier;
311                notifier.onCdmaCallWaitingReject();
312                return true;
313            }
314        } else {
315            // GSM:  Ringing Call and Call waiting, both are hungup by calling
316            // hangup(call) function.
317            if (DBG) log("hangup ringing call");
318            return hangup(ringing);
319        }
320    }
321
322    static boolean hangupActiveCall(Phone phone) {
323        if (DBG) log("hangup active call");
324        return hangup(phone.getForegroundCall());
325    }
326
327    static boolean hangupHoldingCall(Phone phone) {
328        if (DBG) log("hangup holding call");
329        return hangup(phone.getBackgroundCall());
330    }
331
332    /**
333     * Trivial wrapper around Call.hangup(), except that we return a
334     * boolean success code rather than throwing CallStateException on
335     * failure.
336     *
337     * @return true if the call was successfully hung up, or false
338     *         if the call wasn't actually active.
339     */
340    static boolean hangup(Call call) {
341        try {
342            call.hangup();
343            return true;
344        } catch (CallStateException ex) {
345            Log.e(LOG_TAG, "Call hangup: caught " + ex, ex);
346        }
347
348        return false;
349    }
350
351    /**
352     * Trivial wrapper around Connection.hangup(), except that we silently
353     * do nothing (rather than throwing CallStateException) if the
354     * connection wasn't actually active.
355     */
356    static void hangup(Connection c) {
357        try {
358            if (c != null) {
359                c.hangup();
360            }
361        } catch (CallStateException ex) {
362            Log.w(LOG_TAG, "Connection hangup: caught " + ex, ex);
363        }
364    }
365
366    static boolean answerAndEndHolding(Phone phone) {
367        if (DBG) log("end holding & answer waiting: 1");
368        if (!hangupHoldingCall(phone)) {
369            Log.e(LOG_TAG, "end holding failed!");
370            return false;
371        }
372
373        if (DBG) log("end holding & answer waiting: 2");
374        return answerCall(phone);
375
376    }
377
378    static boolean answerAndEndActive(Phone phone) {
379        if (DBG) log("answerAndEndActive()...");
380
381        // Unlike the answerCall() method, we *don't* need to stop the
382        // ringer or change audio modes here since the user is already
383        // in-call, which means that the audio mode is already set
384        // correctly, and that we wouldn't have started the ringer in the
385        // first place.
386
387        // hanging up the active call also accepts the waiting call
388        return hangupActiveCall(phone);
389    }
390
391    /**
392     * Dial the number using the phone passed in.
393     *
394     * @param phone the Phone object.
395     * @param number the number to be dialed.
396     * @return either CALL_STATUS_DIALED, CALL_STATUS_DIALED_MMI, or CALL_STATUS_FAILED
397     */
398    static int placeCall(Phone phone, String number, Uri contactRef) {
399        int status = CALL_STATUS_DIALED;
400        try {
401            if (DBG) log("placeCall: '" + number + "'...");
402
403            Connection cn = phone.dial(number);
404            if (DBG) log("===> phone.dial() returned: " + cn);
405
406            // Presently, null is returned for MMI codes
407            if (cn == null) {
408                if (DBG) log("dialed MMI code: " + number);
409                status = CALL_STATUS_DIALED_MMI;
410                // Set dialed MMI command to service
411                if (mNwService != null) {
412                    try {
413                        mNwService.setMmiString(number);
414                        if (DBG) log("Extended NW bindService setUssdString (" + number + ")");
415                    } catch (RemoteException e) {
416                        mNwService = null;
417                    }
418                }
419
420            } else {
421                PhoneApp app = PhoneApp.getInstance();
422
423                if (phone.getPhoneName().equals("CDMA")) {
424                    if (app.cdmaPhoneCallState.getCurrentCallState()
425                            == CdmaPhoneCallState.PhoneCallState.IDLE) {
426                        // This is the first outgoing call. Set the Phone Call State to ACTIVE
427                        app.cdmaPhoneCallState.setCurrentCallState(
428                                CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
429                    } else {
430                        // This is the second outgoing call. Set the Phone Call State to 3WAY
431                        app.cdmaPhoneCallState.setCurrentCallState(
432                                CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
433                    }
434                }
435
436                PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK);
437
438                // phone.dial() succeeded: we're now in a normal phone call.
439                // attach the URI to the CallerInfo Object if it is there,
440                // otherwise just attach the Uri Reference.
441                // if the uri does not have a "content" scheme, then we treat
442                // it as if it does NOT have a unique reference.
443                String content = phone.getContext().getContentResolver().SCHEME_CONTENT;
444                if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
445                    Object userDataObject = cn.getUserData();
446                    if (userDataObject == null) {
447                        cn.setUserData(contactRef);
448                    } else {
449                        if (userDataObject instanceof CallerInfo) {
450                            ((CallerInfo) userDataObject).contactRefUri = contactRef;
451                        } else {
452                            ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
453                                contactRef;
454                        }
455                    }
456                }
457                setAudioMode(phone.getContext(), AudioManager.MODE_IN_CALL);
458            }
459        } catch (CallStateException ex) {
460            Log.w(LOG_TAG, "PhoneUtils: Exception from phone.dial()", ex);
461            status = CALL_STATUS_FAILED;
462        }
463
464        return status;
465    }
466
467    static void switchHoldingAndActive(Phone phone) {
468        try {
469            if (DBG) log("switchHoldingAndActive");
470            phone.switchHoldingAndActive();
471        } catch (CallStateException ex) {
472            Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex);
473        }
474    }
475
476    /**
477     * Restore the mute setting from the earliest connection of the
478     * foreground call.
479     */
480    static Boolean restoreMuteState(Phone phone) {
481        //get the earliest connection
482        Connection c = phone.getForegroundCall().getEarliestConnection();
483
484        // only do this if connection is not null.
485        if (c != null) {
486
487            // retrieve the mute value.
488            Boolean shouldMute;
489            if (phone.getPhoneName().equals("CDMA") &&
490                    PhoneApp.getInstance().cdmaPhoneCallState.getCurrentCallState() ==
491                    CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
492                shouldMute = sConnectionMuteTable.get(
493                        phone.getForegroundCall().getLatestConnection());
494            } else {
495                shouldMute = sConnectionMuteTable.get(
496                        phone.getForegroundCall().getEarliestConnection());
497            }
498            if (shouldMute == null) {
499                if (DBG) log("problem retrieving mute value for this connection.");
500                shouldMute = Boolean.FALSE;
501            }
502
503            // set the mute value and return the result.
504            setMute (phone, shouldMute.booleanValue());
505            return shouldMute;
506        }
507        return Boolean.valueOf(getMute (phone));
508    }
509
510    static void mergeCalls(Phone phone) {
511        if (phone.getPhoneName().equals("GSM")) {
512            try {
513                if (DBG) log("mergeCalls");
514                phone.conference();
515            } catch (CallStateException ex) {
516                Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex);
517            }
518        } else { // CDMA
519            PhoneApp app = PhoneApp.getInstance();
520            if (app.cdmaPhoneCallState.getCurrentCallState()
521                    == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
522                // Send flash cmd
523                // TODO(Moto): Need to change the call from switchHoldingAndActive to
524                // something meaningful as we are not actually trying to swap calls but
525                // instead are merging two calls by sending a Flash command.
526                switchHoldingAndActive(phone);
527
528                // Set the Phone Call State to conference
529                app.cdmaPhoneCallState.setCurrentCallState(
530                        CdmaPhoneCallState.PhoneCallState.CONF_CALL);
531            }
532        }
533    }
534
535    static void separateCall(Connection c) {
536        try {
537            if (DBG) log("separateCall: " + c.getAddress());
538            c.separate();
539        } catch (CallStateException ex) {
540            Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
541        }
542    }
543
544    /**
545     * Handle the MMIInitiate message and put up an alert that lets
546     * the user cancel the operation, if applicable.
547     *
548     * @param context context to get strings.
549     * @param mmiCode the MmiCode object being started.
550     * @param buttonCallbackMessage message to post when button is clicked.
551     * @param previousAlert a previous alert used in this activity.
552     * @return the dialog handle
553     */
554    static Dialog displayMMIInitiate(Context context,
555                                          MmiCode mmiCode,
556                                          Message buttonCallbackMessage,
557                                          Dialog previousAlert) {
558        if (DBG) log("displayMMIInitiate: " + mmiCode);
559        if (previousAlert != null) {
560            previousAlert.dismiss();
561        }
562
563        // The UI paradigm we are using now requests that all dialogs have
564        // user interaction, and that any other messages to the user should
565        // be by way of Toasts.
566        //
567        // In adhering to this request, all MMI initiating "OK" dialogs
568        // (non-cancelable MMIs) that end up being closed when the MMI
569        // completes (thereby showing a completion dialog) are being
570        // replaced with Toasts.
571        //
572        // As a side effect, moving to Toasts for the non-cancelable MMIs
573        // also means that buttonCallbackMessage (which was tied into "OK")
574        // is no longer invokable for these dialogs.  This is not a problem
575        // since the only callback messages we supported were for cancelable
576        // MMIs anyway.
577        //
578        // A cancelable MMI is really just a USSD request. The term
579        // "cancelable" here means that we can cancel the request when the
580        // system prompts us for a response, NOT while the network is
581        // processing the MMI request.  Any request to cancel a USSD while
582        // the network is NOT ready for a response may be ignored.
583        //
584        // With this in mind, we replace the cancelable alert dialog with
585        // a progress dialog, displayed until we receive a request from
586        // the the network.  For more information, please see the comments
587        // in the displayMMIComplete() method below.
588        //
589        // Anything that is NOT a USSD request is a normal MMI request,
590        // which will bring up a toast (desribed above).
591        // Optional code for Extended USSD running prompt
592        if (mNwService != null) {
593            if (DBG) log("running USSD code, displaying indeterminate progress.");
594            // create the indeterminate progress dialog and display it.
595            ProgressDialog pd = new ProgressDialog(context);
596            CharSequence textmsg = "";
597            try {
598                textmsg = mNwService.getMmiRunningText();
599
600            } catch (RemoteException e) {
601                mNwService = null;
602                textmsg = context.getText(R.string.ussdRunning);
603            }
604            if (DBG) log("Extended NW displayMMIInitiate (" + textmsg+ ")");
605            pd.setMessage(textmsg);
606            pd.setCancelable(false);
607            pd.setIndeterminate(true);
608            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
609            pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
610            pd.show();
611            // trigger a 15 seconds timeout to clear this progress dialog
612            mMmiTimeoutCbMsg = buttonCallbackMessage;
613            try {
614                mMmiTimeoutCbMsg.getTarget().sendMessageDelayed(buttonCallbackMessage, 15000);
615            } catch(NullPointerException e) {
616                mMmiTimeoutCbMsg = null;
617            }
618            return pd;
619        }
620
621        boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
622
623        if (!isCancelable) {
624            if (DBG) log("not a USSD code, displaying status toast.");
625            CharSequence text = context.getText(R.string.mmiStarted);
626            Toast.makeText(context, text, Toast.LENGTH_SHORT)
627                .show();
628            return null;
629        } else {
630            if (DBG) log("running USSD code, displaying indeterminate progress.");
631
632            // create the indeterminate progress dialog and display it.
633            ProgressDialog pd = new ProgressDialog(context);
634            pd.setMessage(context.getText(R.string.ussdRunning));
635            pd.setCancelable(false);
636            pd.setIndeterminate(true);
637            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
638
639            pd.show();
640
641            return pd;
642        }
643
644    }
645
646    /**
647     * Handle the MMIComplete message and fire off an intent to display
648     * the message.
649     *
650     * @param context context to get strings.
651     * @param mmiCode MMI result.
652     * @param previousAlert a previous alert used in this activity.
653     */
654    static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
655            Message dismissCallbackMessage,
656            AlertDialog previousAlert) {
657        CharSequence text;
658        int title = 0;  // title for the progress dialog, if needed.
659        MmiCode.State state = mmiCode.getState();
660
661        if (DBG) log("displayMMIComplete: state=" + state);
662        // Clear timeout trigger message
663        if(mMmiTimeoutCbMsg != null) {
664            try{
665                mMmiTimeoutCbMsg.getTarget().removeMessages(mMmiTimeoutCbMsg.what);
666                if (DBG) log("Extended NW displayMMIComplete removeMsg");
667            } catch (NullPointerException e) {
668            }
669            mMmiTimeoutCbMsg = null;
670        }
671
672
673        switch (state) {
674            case PENDING:
675                // USSD code asking for feedback from user.
676                text = mmiCode.getMessage();
677                if (DBG) log("- using text from PENDING MMI message: '" + text + "'");
678                break;
679            case CANCELLED:
680                text = context.getText(R.string.mmiCancelled);
681                break;
682            case COMPLETE:
683                if (PhoneApp.getInstance().getPUKEntryActivity() != null) {
684                    // if an attempt to unPUK the device was made, we specify
685                    // the title and the message here.
686                    title = com.android.internal.R.string.PinMmi;
687                    text = context.getText(R.string.puk_unlocked);
688                    break;
689                }
690                // All other conditions for the COMPLETE mmi state will cause
691                // the case to fall through to message logic in common with
692                // the FAILED case.
693
694            case FAILED:
695                text = mmiCode.getMessage();
696                if (DBG) log("- using text from MMI message: '" + text + "'");
697                break;
698            default:
699                throw new IllegalStateException("Unexpected MmiCode state: " + state);
700        }
701
702        if (previousAlert != null) {
703            previousAlert.dismiss();
704        }
705
706        // Check to see if a UI exists for the PUK activation.  If it does
707        // exist, then it indicates that we're trying to unblock the PUK.
708        PhoneApp app = PhoneApp.getInstance();
709        if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
710            if (DBG) log("displaying PUK unblocking progress dialog.");
711
712            // create the progress dialog, make sure the flags and type are
713            // set correctly.
714            ProgressDialog pd = new ProgressDialog(app);
715            pd.setTitle(title);
716            pd.setMessage(text);
717            pd.setCancelable(false);
718            pd.setIndeterminate(true);
719            pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
720            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
721
722            // display the dialog
723            pd.show();
724
725            // indicate to the Phone app that the progress dialog has
726            // been assigned for the PUK unlock / SIM READY process.
727            app.setPukEntryProgressDialog(pd);
728
729        } else {
730            // In case of failure to unlock, we'll need to reset the
731            // PUK unlock activity, so that the user may try again.
732            if (app.getPUKEntryActivity() != null) {
733                app.setPukEntryActivity(null);
734            }
735
736            // A USSD in a pending state means that it is still
737            // interacting with the user.
738            if (state != MmiCode.State.PENDING) {
739                if (DBG) log("MMI code has finished running.");
740
741                // Replace response message with Extended Mmi wording
742                if (mNwService != null) {
743                    try {
744                        text = mNwService.getUserMessage(text);
745                    } catch (RemoteException e) {
746                        mNwService = null;
747                    }
748                    if (DBG) log("Extended NW displayMMIInitiate (" + text + ")");
749                    if (text == null || text.length() == 0)
750                        return;
751                }
752
753                // displaying system alert dialog on the screen instead of
754                // using another activity to display the message.  This
755                // places the message at the forefront of the UI.
756                AlertDialog newDialog = new AlertDialog.Builder(context)
757                        .setMessage(text)
758                        .setPositiveButton(R.string.ok, null)
759                        .setCancelable(true)
760                        .create();
761
762                newDialog.getWindow().setType(
763                        WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
764                newDialog.getWindow().addFlags(
765                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
766
767                newDialog.show();
768            } else {
769                if (DBG) log("USSD code has requested user input. Constructing input dialog.");
770
771                // USSD MMI code that is interacting with the user.  The
772                // basic set of steps is this:
773                //   1. User enters a USSD request
774                //   2. We recognize the request and displayMMIInitiate
775                //      (above) creates a progress dialog.
776                //   3. Request returns and we get a PENDING or COMPLETE
777                //      message.
778                //   4. These MMI messages are caught in the PhoneApp
779                //      (onMMIComplete) and the InCallScreen
780                //      (mHandler.handleMessage) which bring up this dialog
781                //      and closes the original progress dialog,
782                //      respectively.
783                //   5. If the message is anything other than PENDING,
784                //      we are done, and the alert dialog (directly above)
785                //      displays the outcome.
786                //   6. If the network is requesting more information from
787                //      the user, the MMI will be in a PENDING state, and
788                //      we display this dialog with the message.
789                //   7. User input, or cancel requests result in a return
790                //      to step 1.  Keep in mind that this is the only
791                //      time that a USSD should be canceled.
792
793                // inflate the layout with the scrolling text area for the dialog.
794                LayoutInflater inflater = (LayoutInflater) context.getSystemService(
795                        Context.LAYOUT_INFLATER_SERVICE);
796                View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
797
798                // get the input field.
799                final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
800
801                // specify the dialog's click listener, with SEND and CANCEL logic.
802                final DialogInterface.OnClickListener mUSSDDialogListener =
803                    new DialogInterface.OnClickListener() {
804                        public void onClick(DialogInterface dialog, int whichButton) {
805                            switch (whichButton) {
806                                case DialogInterface.BUTTON1:
807                                    phone.sendUssdResponse(inputText.getText().toString());
808                                    break;
809                                case DialogInterface.BUTTON2:
810                                    if (mmiCode.isCancelable()) {
811                                        mmiCode.cancel();
812                                    }
813                                    break;
814                            }
815                        }
816                    };
817
818                // build the dialog
819                final AlertDialog newDialog = new AlertDialog.Builder(context)
820                        .setMessage(text)
821                        .setView(dialogView)
822                        .setPositiveButton(R.string.send_button, mUSSDDialogListener)
823                        .setNegativeButton(R.string.cancel, mUSSDDialogListener)
824                        .setCancelable(false)
825                        .create();
826
827                // attach the key listener to the dialog's input field and make
828                // sure focus is set.
829                final View.OnKeyListener mUSSDDialogInputListener =
830                    new View.OnKeyListener() {
831                        public boolean onKey(View v, int keyCode, KeyEvent event) {
832                            switch (keyCode) {
833                                case KeyEvent.KEYCODE_CALL:
834                                case KeyEvent.KEYCODE_ENTER:
835                                    phone.sendUssdResponse(inputText.getText().toString());
836                                    newDialog.dismiss();
837                                    return true;
838                            }
839                            return false;
840                        }
841                    };
842                inputText.setOnKeyListener(mUSSDDialogInputListener);
843                inputText.requestFocus();
844
845                // set the window properties of the dialog
846                newDialog.getWindow().setType(
847                        WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
848                newDialog.getWindow().addFlags(
849                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
850
851                // now show the dialog!
852                newDialog.show();
853            }
854        }
855    }
856
857    /**
858     * Cancels the current pending MMI operation, if applicable.
859     * @return true if we canceled an MMI operation, or false
860     *         if the current pending MMI wasn't cancelable
861     *         or if there was no current pending MMI at all.
862     *
863     * @see displayMMIInitiate
864     */
865    static boolean cancelMmiCode(Phone phone) {
866        List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
867        int count = pendingMmis.size();
868        if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
869
870        boolean canceled = false;
871        if (count > 0) {
872            // assume that we only have one pending MMI operation active at a time.
873            // I don't think it's possible to enter multiple MMI codes concurrently
874            // in the phone UI, because during the MMI operation, an Alert panel
875            // is displayed, which prevents more MMI code from being entered.
876            MmiCode mmiCode = pendingMmis.get(0);
877            if (mmiCode.isCancelable()) {
878                mmiCode.cancel();
879                canceled = true;
880            }
881        }
882
883        //clear timeout message and pre-set MMI command
884        if (mNwService != null) {
885            try {
886                mNwService.clearMmiString();
887            } catch (RemoteException e) {
888                mNwService = null;
889            }
890        }
891        if (mMmiTimeoutCbMsg != null) {
892            mMmiTimeoutCbMsg = null;
893        }
894        return canceled;
895    }
896
897    public static class VoiceMailNumberMissingException extends Exception {
898        VoiceMailNumberMissingException() {
899            super();
900        }
901
902        VoiceMailNumberMissingException(String msg) {
903            super(msg);
904        }
905    }
906
907    /**
908     * Gets the phone number to be called from an intent.  Requires a Context
909     * to access the contacts database, and a Phone to access the voicemail
910     * number.
911     *
912     * <p>If <code>phone</code> is <code>null</code>, the function will return
913     * <code>null</code> for <code>voicemail:</code> URIs;
914     * if <code>context</code> is <code>null</code>, the function will return
915     * <code>null</code> for person/phone URIs.</p>
916     *
917     * @param context a context to use (or
918     * @param phone the phone on which the number would be called
919     * @param intent the intent
920     *
921     * @throws VoiceMailNumberMissingException if <code>intent</code> contains
922     *         a <code>voicemail:</code> URI, but <code>phone</code> does not
923     *         have a voicemail number set.
924     *
925     * @return the phone number that would be called by the intent,
926     *         or <code>null</code> if the number cannot be found.
927     */
928    static String getNumberFromIntent(Context context, Phone phone, Intent intent)
929            throws VoiceMailNumberMissingException {
930        final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
931
932        // Check for a voicemail-dailing request.  If the voicemail number is
933        // empty, throw a VoiceMailNumberMissingException.
934        if (intent.getData().getScheme().equals("voicemail") &&
935                (number == null || TextUtils.isEmpty(number)))
936            throw new VoiceMailNumberMissingException();
937
938        return number;
939    }
940
941    /**
942     * Returns the caller-id info corresponding to the specified Connection.
943     * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
944     * extract a phone number from the specified Connection, and feed that
945     * number into CallerInfo.getCallerInfo().)
946     *
947     * The returned CallerInfo may be null in certain error cases, like if the
948     * specified Connection was null, or if we weren't able to get a valid
949     * phone number from the Connection.
950     *
951     * Finally, if the getCallerInfo() call did succeed, we save the resulting
952     * CallerInfo object in the "userData" field of the Connection.
953     *
954     * NOTE: This API should be avoided, with preference given to the
955     * asynchronous startGetCallerInfo API.
956     */
957    static CallerInfo getCallerInfo(Context context, Connection c) {
958        CallerInfo info = null;
959
960        if (c != null) {
961            //See if there is a URI attached.  If there is, this means
962            //that there is no CallerInfo queried yet, so we'll need to
963            //replace the URI with a full CallerInfo object.
964            Object userDataObject = c.getUserData();
965            if (userDataObject instanceof Uri) {
966                info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
967                if (info != null) {
968                    c.setUserData(info);
969                }
970            } else {
971                if (userDataObject instanceof CallerInfoToken) {
972                    //temporary result, while query is running
973                    info = ((CallerInfoToken) userDataObject).currentInfo;
974                } else {
975                    //final query result
976                    info = (CallerInfo) userDataObject;
977                }
978                if (info == null) {
979                    // No URI, or Existing CallerInfo, so we'll have to make do with
980                    // querying a new CallerInfo using the connection's phone number.
981                    String number = c.getAddress();
982
983                    if (DBG) log("getCallerInfo: number = " + number);
984
985                    if (!TextUtils.isEmpty(number)) {
986                        info = CallerInfo.getCallerInfo(context, number);
987                        if (info != null) {
988                            c.setUserData(info);
989                        }
990                    }
991                }
992            }
993        }
994        return info;
995    }
996
997    /**
998     * Class returned by the startGetCallerInfo call to package a temporary
999     * CallerInfo Object, to be superceded by the CallerInfo Object passed
1000     * into the listener when the query with token mAsyncQueryToken is complete.
1001     */
1002    public static class CallerInfoToken {
1003        /**indicates that there will no longer be updates to this request.*/
1004        public boolean isFinal;
1005
1006        public CallerInfo currentInfo;
1007        public CallerInfoAsyncQuery asyncQuery;
1008    }
1009
1010    /**
1011     * Start a CallerInfo Query based on the earliest connection in the call.
1012     */
1013    static CallerInfoToken startGetCallerInfo(Context context, Call call,
1014            CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1015        PhoneApp app = PhoneApp.getInstance();
1016        Connection conn = null;
1017        if (app.phone.getPhoneName().equals("CDMA")) {
1018            conn = call.getLatestConnection();
1019        } else {
1020            conn = call.getEarliestConnection();
1021        }
1022
1023        return startGetCallerInfo(context, conn, listener, cookie);
1024    }
1025
1026    /**
1027     * place a temporary callerinfo object in the hands of the caller and notify
1028     * caller when the actual query is done.
1029     */
1030    static CallerInfoToken startGetCallerInfo(Context context, Connection c,
1031            CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1032        CallerInfoToken cit;
1033
1034        if (c == null) {
1035            //TODO: perhaps throw an exception here.
1036            cit = new CallerInfoToken();
1037            cit.asyncQuery = null;
1038            return cit;
1039        }
1040
1041        // There are now 3 states for the userdata.
1042        //   1. Uri - query has not been executed yet
1043        //   2. CallerInfoToken - query is executing, but has not completed.
1044        //   3. CallerInfo - query has executed.
1045        // In each case we have slightly different behaviour:
1046        //   1. If the query has not been executed yet (Uri or null), we start
1047        //      query execution asynchronously, and note it by attaching a
1048        //      CallerInfoToken as the userData.
1049        //   2. If the query is executing (CallerInfoToken), we've essentially
1050        //      reached a state where we've received multiple requests for the
1051        //      same callerInfo.  That means that once the query is complete,
1052        //      we'll need to execute the additional listener requested.
1053        //   3. If the query has already been executed (CallerInfo), we just
1054        //      return the CallerInfo object as expected.
1055        //   4. Regarding isFinal - there are cases where the CallerInfo object
1056        //      will not be attached, like when the number is empty (caller id
1057        //      blocking).  This flag is used to indicate that the
1058        //      CallerInfoToken object is going to be permanent since no
1059        //      query results will be returned.  In the case where a query
1060        //      has been completed, this flag is used to indicate to the caller
1061        //      that the data will not be updated since it is valid.
1062        //
1063        //      Note: For the case where a number is NOT retrievable, we leave
1064        //      the CallerInfo as null in the CallerInfoToken.  This is
1065        //      something of a departure from the original code, since the old
1066        //      code manufactured a CallerInfo object regardless of the query
1067        //      outcome.  From now on, we will append an empty CallerInfo
1068        //      object, to mirror previous behaviour, and to avoid Null Pointer
1069        //      Exceptions.
1070        Object userDataObject = c.getUserData();
1071        if (userDataObject instanceof Uri) {
1072            //create a dummy callerinfo, populate with what we know from URI.
1073            cit = new CallerInfoToken();
1074            cit.currentInfo = new CallerInfo();
1075            cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1076                    (Uri) userDataObject, sCallerInfoQueryListener, c);
1077            cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1078            cit.isFinal = false;
1079
1080            c.setUserData(cit);
1081
1082            if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
1083
1084        } else if (userDataObject == null) {
1085            // No URI, or Existing CallerInfo, so we'll have to make do with
1086            // querying a new CallerInfo using the connection's phone number.
1087            String number = c.getAddress();
1088            int cnapSpecialCase;
1089
1090            cit = new CallerInfoToken();
1091            cit.currentInfo = new CallerInfo();
1092
1093            if (DBG) log("startGetCallerInfo: number = " + number);
1094
1095            // handling case where number is null (caller id hidden) as well.
1096            if (!TextUtils.isEmpty(number)) {
1097                // Store CNAP information retrieved from the Connection
1098                cit.currentInfo.cnapName =  c.getCnapName();
1099                cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
1100                                                                 // by ContactInfo later
1101                cit.currentInfo.numberPresentation = c.getNumberPresentation();
1102                cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1103                if (DBG) log("startGetCallerInfo: CNAP Info from FW: name="
1104                        + cit.currentInfo.cnapName
1105                        + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1106                // Only when numberPresentation is ALLOWED, check the special string:
1107                if (cit.currentInfo.numberPresentation == Connection.PRESENTATION_ALLOWED) {
1108                    cnapSpecialCase = checkCnapSpecialCases(number);
1109                    if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
1110                        // For all special strings, change number & numberPresentation.
1111                        if (cnapSpecialCase == Connection.PRESENTATION_RESTRICTED) {
1112                            number = context.getString(R.string.private_num);
1113                        } else if (cnapSpecialCase == Connection.PRESENTATION_UNKNOWN) {
1114                            number = context.getString(R.string.unknown);
1115                        }
1116                        cit.currentInfo.numberPresentation = cnapSpecialCase;
1117                    }
1118                }
1119
1120                cit.currentInfo.phoneNumber = number;
1121                cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1122                        number, sCallerInfoQueryListener, c);
1123                cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1124                cit.isFinal = false;
1125            } else {
1126                // This is the case where we are querying on a number that
1127                // is null or empty, like a caller whose caller id is
1128                // blocked or empty (CLIR).  The previous behaviour was to
1129                // throw a null CallerInfo object back to the user, but
1130                // this departure is somewhat cleaner.
1131                if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
1132                cit.isFinal = true; // please see note on isFinal, above.
1133            }
1134
1135            c.setUserData(cit);
1136
1137            if (DBG) log("startGetCallerInfo: query based on number: " + number);
1138
1139        } else if (userDataObject instanceof CallerInfoToken) {
1140            // query is running, just tack on this listener to the queue.
1141            cit = (CallerInfoToken) userDataObject;
1142
1143            // handling case where number is null (caller id hidden) as well.
1144            if (cit.asyncQuery != null) {
1145                cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1146
1147                if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
1148                        listener.getClass().toString());
1149            } else {
1150                // handling case where number/name gets updated later on by the network
1151                String updatedNumber = c.getAddress();
1152                if (DBG) log("startGetCallerInfo: updatedNumber = " + updatedNumber);
1153                if (!TextUtils.isEmpty(updatedNumber)) {
1154                    cit.currentInfo.phoneNumber = updatedNumber;
1155
1156                    // Store CNAP information retrieved from the Connection
1157                    cit.currentInfo.cnapName =  c.getCnapName();
1158                    // This can still get overwritten by ContactInfo
1159                    cit.currentInfo.name = cit.currentInfo.cnapName;
1160                    cit.currentInfo.numberPresentation = c.getNumberPresentation();
1161                    cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1162
1163                    if (DBG) log("startGetCallerInfo: CNAP Info from FW: name="
1164                            + cit.currentInfo.cnapName
1165                            + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1166                    cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1167                            updatedNumber, sCallerInfoQueryListener, c);
1168                    cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1169                    cit.isFinal = false;
1170                } else {
1171                    if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
1172                    if (cit.currentInfo == null) {
1173                        cit.currentInfo = new CallerInfo();
1174                    }
1175                    cit.isFinal = true; // please see note on isFinal, above.
1176                }
1177            }
1178        } else {
1179            cit = new CallerInfoToken();
1180            cit.currentInfo = (CallerInfo) userDataObject;
1181            cit.asyncQuery = null;
1182            cit.isFinal = true;
1183            // since the query is already done, call the listener.
1184            if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
1185        }
1186        return cit;
1187    }
1188
1189    /**
1190     * Implemented for CallerInfo.OnCallerInfoQueryCompleteListener interface.
1191     * Updates the connection's userData when called.
1192     */
1193    private static final int QUERY_TOKEN = -1;
1194    static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
1195        new CallerInfoAsyncQuery.OnQueryCompleteListener () {
1196            public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
1197                if (DBG) log("query complete, updating connection.userdata");
1198
1199                // Added a check if CallerInfo is coming from ContactInfo or from Connection.
1200                // If no ContactInfo, then we want to use CNAP information coming from network
1201                if (DBG) log("- onQueryComplete: contactExists=" + ci.contactExists);
1202                if (ci.contactExists) {
1203                    ((Connection) cookie).setUserData(ci);
1204                } else {
1205                    CallerInfo newCi = getCallerInfo(null, (Connection) cookie);
1206                    if (newCi != null) {
1207                        newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1208                        ((Connection) cookie).setUserData(newCi);
1209                    }
1210                    else ((Connection) cookie).setUserData(ci);
1211                }
1212            }
1213        };
1214
1215    static void saveToContact(Context context, String number) {
1216        Intent intent = new Intent(Contacts.Intents.Insert.ACTION,
1217                Contacts.People.CONTENT_URI);
1218        intent.putExtra(Contacts.Intents.Insert.PHONE, number);
1219        context.startActivity(intent);
1220    }
1221
1222    /**
1223     * Returns a single "name" for the specified given a CallerInfo object.
1224     * If the name is null, return defaultString as the default value, usually
1225     * context.getString(R.string.unknown).
1226     */
1227    static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1228        if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1229
1230        String compactName = null;
1231        if (ci != null) {
1232            compactName = ci.name;
1233            if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1234                compactName = ci.phoneNumber;
1235            }
1236        }
1237        // TODO: figure out UNKNOWN, PRIVATE numbers?
1238        if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1239            compactName = context.getString(R.string.unknown);
1240        }
1241        return compactName;
1242    }
1243
1244    /**
1245     * Returns true if the specified Call is a "conference call", meaning
1246     * that it owns more than one Connection object.  This information is
1247     * used to trigger certain UI changes that appear when a conference
1248     * call is active (like displaying the label "Conference call", and
1249     * enabling the "Manage conference" UI.)
1250     *
1251     * Watch out: This method simply checks the number of Connections,
1252     * *not* their states.  So if a Call has (for example) one ACTIVE
1253     * connection and one DISCONNECTED connection, this method will return
1254     * true (which is unintuitive, since the Call isn't *really* a
1255     * conference call any more.)
1256     *
1257     * @return true if the specified call has more than one connection (in any state.)
1258     */
1259    static boolean isConferenceCall(Call call) {
1260        // CDMA phones don't have the same concept of "conference call" as
1261        // GSM phones do; there's no special "conference call" state of
1262        // the UI or a "manage conference" function.  (Instead, when
1263        // you're in a 3-way call, all we can do is display the "generic"
1264        // state of the UI.)  So as far as the in-call UI is concerned,
1265        // Conference corresponds to generic display.
1266        PhoneApp app = PhoneApp.getInstance();
1267        if (app.phone.getPhoneName().equals("CDMA")) {
1268            if (app.cdmaPhoneCallState.getCurrentCallState()
1269                    == CdmaPhoneCallState.PhoneCallState.CONF_CALL) {
1270                return true;
1271            }
1272        } else {
1273            List<Connection> connections = call.getConnections();
1274            if (connections != null && connections.size() > 1) {
1275                return true;
1276            }
1277        }
1278        return false;
1279
1280        // TODO: We may still want to change the semantics of this method
1281        // to say that a given call is only really a conference call if
1282        // the number of ACTIVE connections, not the total number of
1283        // connections, is greater than one.  (See warning comment in the
1284        // javadoc above.)
1285        // Here's an implementation of that:
1286        //        if (connections == null) {
1287        //            return false;
1288        //        }
1289        //        int numActiveConnections = 0;
1290        //        for (Connection conn : connections) {
1291        //            if (DBG) log("  - CONN: " + conn + ", state = " + conn.getState());
1292        //            if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
1293        //            if (numActiveConnections > 1) {
1294        //                return true;
1295        //            }
1296        //        }
1297        //        return false;
1298    }
1299
1300    /**
1301     * Launch the Dialer to start a new call.
1302     * This is just a wrapper around the ACTION_DIAL intent.
1303     */
1304    static void startNewCall(final Phone phone) {
1305        final KeyguardManager keyguardManager = PhoneApp.getInstance().getKeyguardManager();
1306        if (!keyguardManager.inKeyguardRestrictedInputMode()) {
1307            internalStartNewCall(phone);
1308        } else {
1309            keyguardManager.exitKeyguardSecurely(new KeyguardManager.OnKeyguardExitResult() {
1310                public void onKeyguardExitResult(boolean success) {
1311                    if (success) {
1312                        internalStartNewCall(phone);
1313                    }
1314                }
1315            });
1316        }
1317    }
1318
1319    private static void internalStartNewCall(Phone phone) {
1320        // Sanity-check that this is OK given the current state of the phone.
1321        if (!okToAddCall(phone)) {
1322            Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
1323            dumpCallState(phone);
1324            return;
1325        }
1326
1327        // if applicable, mute the call while we're showing the add call UI.
1328        if (!phone.getForegroundCall().isIdle()) {
1329            setMuteInternal(phone, true);
1330            // Inform the phone app that this mute state was NOT done
1331            // voluntarily by the User.
1332            PhoneApp.getInstance().setRestoreMuteOnInCallResume(true);
1333        }
1334
1335        Intent intent = new Intent(Intent.ACTION_DIAL);
1336        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1337
1338        // when we request the dialer come up, we also want to inform
1339        // it that we're going through the "add call" option from the
1340        // InCallScreen / PhoneUtils.
1341        intent.putExtra(ADD_CALL_MODE_KEY, true);
1342
1343        PhoneApp.getInstance().startActivity(intent);
1344    }
1345
1346    /**
1347     * Brings up the UI used to handle an incoming call.
1348     *
1349     * Originally, this brought up an IncomingCallPanel instance
1350     * (which was a subclass of Dialog) on top of whatever app
1351     * was currently running.  Now, we take you directly to the
1352     * in-call screen, whose CallCard automatically does the right
1353     * thing if there's a Call that's currently ringing.
1354     */
1355    static void showIncomingCallUi() {
1356        if (DBG) log("showIncomingCallUi()...");
1357        PhoneApp app = PhoneApp.getInstance();
1358
1359        // Before bringing up the "incoming call" UI, force any system
1360        // dialogs (like "recent tasks" or the power dialog) to close first.
1361        try {
1362            ActivityManagerNative.getDefault().closeSystemDialogs("call");
1363        } catch (RemoteException e) {
1364        }
1365
1366        // Go directly to the in-call screen.
1367        // (No need to do anything special if we're already on the in-call
1368        // screen; it'll notice the phone state change and update itself.)
1369
1370        // But first, grab a full wake lock.  We do this here, before we
1371        // even fire off the InCallScreen intent, to make sure the
1372        // ActivityManager doesn't try to pause the InCallScreen as soon
1373        // as it comes up.  (See bug 1648751.)
1374        //
1375        // And since the InCallScreen isn't visible yet (we haven't even
1376        // fired off the intent yet), we DON'T want the screen to actually
1377        // come on right now.  So *before* acquiring the wake lock we need
1378        // to call preventScreenOn(), which tells the PowerManager that
1379        // the screen should stay off even if someone's holding a full
1380        // wake lock.  (This prevents any flicker during the "incoming
1381        // call" sequence.  The corresponding preventScreenOn(false) call
1382        // will come from the InCallScreen when it's finally ready to be
1383        // displayed.)
1384        //
1385        // TODO: this is all a temporary workaround.  The real fix is to add
1386        // an Activity attribute saying "this Activity wants to wake up the
1387        // phone when it's displayed"; that way the ActivityManager could
1388        // manage the wake locks *and* arrange for the screen to come on at
1389        // the exact moment that the InCallScreen is ready to be displayed.
1390        // (See bug 1648751.)
1391        app.preventScreenOn(true);
1392        app.requestWakeState(PhoneApp.WakeState.FULL);
1393
1394        // Fire off the InCallScreen intent.
1395        app.displayCallScreen();
1396    }
1397
1398    static void turnOnSpeaker(Context context, boolean flag) {
1399        if (DBG) log("turnOnSpeaker: " + flag);
1400        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1401
1402        audioManager.setSpeakerphoneOn(flag);
1403        // record the speaker-enable value
1404        sIsSpeakerEnabled = flag;
1405        if (flag) {
1406            NotificationMgr.getDefault().notifySpeakerphone();
1407        } else {
1408            NotificationMgr.getDefault().cancelSpeakerphone();
1409        }
1410
1411        // We also need to make a fresh call to PhoneApp.updateWakeState()
1412        // any time the speaker state changes, since the screen timeout is
1413        // sometimes different depending on whether or not the speaker is
1414        // in use.
1415        PhoneApp app = PhoneApp.getInstance();
1416        app.updateWakeState();
1417    }
1418
1419    /**
1420     * Restore the speaker mode, called after a wired headset disconnect
1421     * event.
1422     */
1423    static void restoreSpeakerMode(Context context) {
1424        if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
1425
1426        // change the mode if needed.
1427        if (isSpeakerOn(context) != sIsSpeakerEnabled) {
1428            turnOnSpeaker(context, sIsSpeakerEnabled);
1429        }
1430    }
1431
1432    static boolean isSpeakerOn(Context context) {
1433        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1434        return audioManager.isSpeakerphoneOn();
1435    }
1436
1437    /**
1438     * Wrapper around Phone.setMute() that also updates the mute icon in
1439     * the status bar.
1440     *
1441     * All muting / unmuting from the in-call UI should go through this
1442     * wrapper.
1443     */
1444    static void setMute(Phone phone, boolean muted) {
1445        // make the call to mute the audio
1446        setMuteInternal(phone, muted);
1447
1448        // update the foreground connections to match.  This includes
1449        // all the connections on conference calls.
1450        for (Connection cn : phone.getForegroundCall().getConnections()) {
1451            if (sConnectionMuteTable.get(cn) == null) {
1452                if (DBG) log("problem retrieving mute value for this connection.");
1453            }
1454            sConnectionMuteTable.put(cn, Boolean.valueOf(muted));
1455        }
1456    }
1457
1458    /**
1459     * Internally used muting function.  All UI calls should use {@link setMute}
1460     */
1461    static void setMuteInternal(Phone phone, boolean muted) {
1462        if (DBG) log("setMute: " + muted);
1463        phone.setMute(muted);
1464        if (muted) {
1465            NotificationMgr.getDefault().notifyMute();
1466        } else {
1467            NotificationMgr.getDefault().cancelMute();
1468        }
1469    }
1470
1471    static boolean getMute(Phone phone) {
1472        return phone.getMute();
1473    }
1474
1475    /**
1476     * A really simple wrapper around AudioManager.setMode(),
1477     * with a bit of extra logging to help debug the exact
1478     * timing (and call stacks) for all our setMode() calls.
1479     *
1480     * Also, add additional state monitoring to determine
1481     * whether or not certain calls to change the audio mode
1482     * are ignored.
1483     */
1484    /* package */ static void setAudioMode(Context context, int mode) {
1485        if (DBG) Log.d(LOG_TAG, "PhoneUtils.setAudioMode(" + audioModeToString(mode) + ")...");
1486
1487        //decide whether or not to ignore the audio setting
1488        boolean ignore = false;
1489
1490        switch (sAudioBehaviourState) {
1491            case AUDIO_RINGING:
1492                ignore = ((mode == AudioManager.MODE_NORMAL) || (mode == AudioManager.MODE_IN_CALL));
1493                break;
1494            case AUDIO_OFFHOOK:
1495                ignore = ((mode == AudioManager.MODE_NORMAL) || (mode == AudioManager.MODE_RINGTONE));
1496                break;
1497            case AUDIO_IDLE:
1498            default:
1499                ignore = (mode == AudioManager.MODE_IN_CALL);
1500                break;
1501        }
1502
1503        if (!ignore) {
1504            AudioManager audioManager =
1505                    (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1506            // Enable stack dump only when actively debugging ("new Throwable()" is expensive!)
1507            if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump"));
1508            audioManager.setMode(mode);
1509        } else {
1510            if (DBG) Log.d(LOG_TAG, "PhoneUtils.setAudioMode(), state is " + sAudioBehaviourState +
1511                    " ignoring " + audioModeToString(mode) + " request");
1512        }
1513    }
1514    private static String audioModeToString(int mode) {
1515        switch (mode) {
1516            case AudioManager.MODE_INVALID: return "MODE_INVALID";
1517            case AudioManager.MODE_CURRENT: return "MODE_CURRENT";
1518            case AudioManager.MODE_NORMAL: return "MODE_NORMAL";
1519            case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE";
1520            case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL";
1521            default: return String.valueOf(mode);
1522        }
1523    }
1524
1525    /**
1526     * Handles the wired headset button while in-call.
1527     *
1528     * This is called from the PhoneApp, not from the InCallScreen,
1529     * since the HEADSETHOOK button means "mute or unmute the current
1530     * call" *any* time a call is active, even if the user isn't actually
1531     * on the in-call screen.
1532     *
1533     * @return true if we consumed the event.
1534     */
1535    /* package */ static boolean handleHeadsetHook(Phone phone) {
1536        if (DBG) log("handleHeadsetHook()...");
1537
1538        // If the phone is totally idle, we ignore HEADSETHOOK events
1539        // (and instead let them fall through to the media player.)
1540        if (phone.getState() == Phone.State.IDLE) {
1541            return false;
1542        }
1543
1544        // Ok, the phone is in use.
1545        // The headset button button means "Answer" if an incoming call is
1546        // ringing.  If not, it toggles the mute / unmute state.
1547        //
1548        // And in any case we *always* consume this event; this means
1549        // that the usual mediaplayer-related behavior of the headset
1550        // button will NEVER happen while the user is on a call.
1551
1552        final boolean hasRingingCall = !phone.getRingingCall().isIdle();
1553        final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
1554        final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
1555
1556        if (phone.getPhoneName().equals("CDMA")) {
1557            PhoneApp app = PhoneApp.getInstance();
1558            if (hasRingingCall) {
1559                answerCall(phone);
1560            } else {
1561                if (app.cdmaPhoneCallState.getCurrentCallState()
1562                        == CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE) {
1563                    // Send a flash command to CDMA network for putting the other
1564                    // party on hold.
1565                    // For CDMA networks which do not support this the user would just
1566                    // hear a beep from the network.
1567                    // For CDMA networks which do support it it will put the other
1568                    // party on hold.
1569                    switchHoldingAndActive(phone);
1570                }
1571
1572                // No incoming ringing call.  Toggle the mute state.
1573                if (getMute(phone)) {
1574                    if (DBG) log("handleHeadsetHook: UNmuting...");
1575                    setMute(phone, false);
1576                } else {
1577                    if (DBG) log("handleHeadsetHook: muting...");
1578                    setMute(phone, true);
1579                }
1580            }
1581        } else { // GSM
1582            if (hasRingingCall) {
1583                // If an incoming call is ringing, answer it (just like with the
1584                // CALL button):
1585                if (hasActiveCall && hasHoldingCall) {
1586                    if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!");
1587                    answerAndEndActive(phone);
1588                } else {
1589                    if (DBG) log("handleHeadsetHook: ringing ==> answer!");
1590                    answerCall(phone);  // Automatically holds the current active call,
1591                                     // if there is one
1592                }
1593            } else {
1594                // No incoming ringing call.  Toggle the mute state.
1595                if (getMute(phone)) {
1596                    if (DBG) log("handleHeadsetHook: UNmuting...");
1597                    setMute(phone, false);
1598                } else {
1599                    if (DBG) log("handleHeadsetHook: muting...");
1600                    setMute(phone, true);
1601                }
1602            }
1603        }
1604
1605        // Even if the InCallScreen is the current activity, there's no
1606        // need to force it to update, because (1) if we answered a
1607        // ringing call, the InCallScreen will imminently get a phone
1608        // state change event (causing an update), and (2) if we muted or
1609        // unmuted, the setMute() call automagically updates the status
1610        // bar, and there's no "mute" indication in the InCallScreen
1611        // itself (other than the menu item, which only ever stays
1612        // onscreen for a second anyway.)
1613
1614        return true;
1615    }
1616
1617    /**
1618     * Look for ANY connections on the phone that qualify as being
1619     * disconnected.
1620     *
1621     * @return true if we find a connection that is disconnected over
1622     * all the phone's call objects.
1623     */
1624    /* package */ static boolean hasDisconnectedConnections(Phone phone) {
1625        return hasDisconnectedConnections(phone.getForegroundCall()) ||
1626                hasDisconnectedConnections(phone.getBackgroundCall()) ||
1627                hasDisconnectedConnections(phone.getRingingCall());
1628    }
1629
1630    /**
1631     * Iterate over all connections in a call to see if there are any
1632     * that are not alive (disconnected or idle).
1633     *
1634     * @return true if we find a connection that is disconnected, and
1635     * pending removal via
1636     * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}.
1637     */
1638    private static final boolean hasDisconnectedConnections(Call call) {
1639        // look through all connections for non-active ones.
1640        for (Connection c : call.getConnections()) {
1641            if (!c.isAlive()) {
1642                return true;
1643            }
1644        }
1645        return false;
1646    }
1647
1648    //
1649    // Misc UI policy helper functions
1650    //
1651
1652    /**
1653     * @return true if we're allowed to swap calls, given the current
1654     * state of the Phone.
1655     */
1656    /* package */ static boolean okToSwapCalls(Phone phone) {
1657        if (phone.getPhoneName().equals("CDMA")) {
1658            // CDMA: "Swap" is enabled only when the phone reaches a *generic*.
1659            // state by either accepting a Call Waiting or by merging two calls
1660            PhoneApp app = PhoneApp.getInstance();
1661            return (app.cdmaPhoneCallState.getCurrentCallState()
1662                    == CdmaPhoneCallState.PhoneCallState.CONF_CALL);
1663        } else {
1664            // GSM: "Swap" is available if both lines are in use and there's no
1665            // incoming call.  (Actually we need to verify that the active
1666            // call really is in the ACTIVE state and the holding call really
1667            // is in the HOLDING state, since you *can't* actually swap calls
1668            // when the foreground call is DIALING or ALERTING.)
1669            return phone.getRingingCall().isIdle()
1670                    && (phone.getForegroundCall().getState() == Call.State.ACTIVE)
1671                    && (phone.getBackgroundCall().getState() == Call.State.HOLDING);
1672        }
1673    }
1674
1675    /**
1676     * @return true if we're allowed to merge calls, given the current
1677     * state of the Phone.
1678     */
1679    /* package */ static boolean okToMergeCalls(Phone phone) {
1680        if (phone.getPhoneName().equals("CDMA")) {
1681            // CDMA: "Merge" is enabled only when the user is in a 3Way call.
1682            PhoneApp app = PhoneApp.getInstance();
1683            return (app.cdmaPhoneCallState.getCurrentCallState()
1684                    == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
1685        } else { //GSM.
1686            // GSM: "Merge" is available if both lines are in use and there's no
1687            // incoming call, *and* the current conference isn't already
1688            // "full".
1689            return phone.getRingingCall().isIdle() && phone.canConference();
1690        }
1691    }
1692
1693    /**
1694     * @return true if the UI should let you add a new call, given the current
1695     * state of the Phone.
1696     */
1697    /* package */ static boolean okToAddCall(Phone phone) {
1698       if (phone.getPhoneName().equals("CDMA")) {
1699           // CDMA: "Add call" menu item is only enabled when the call is in
1700           // - SINGLE_ACTIVE state
1701           // - After 60 seconds of user Ignoring/Missing a Call Waiting call.
1702            PhoneApp app = PhoneApp.getInstance();
1703            return ((app.cdmaPhoneCallState.getCurrentCallState()
1704                    == CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE)
1705                    && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting()));
1706        } else {
1707            // GSM: "Add call" is available only if ALL of the following are true:
1708            // - There's no incoming ringing call
1709            // - There's < 2 lines in use
1710            // - The foreground call is ACTIVE or IDLE or DISCONNECTED.
1711            //   (We mainly need to make sure it *isn't* DIALING or ALERTING.)
1712            final boolean hasRingingCall = !phone.getRingingCall().isIdle();
1713            final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
1714            final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
1715            final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
1716            final Call.State fgCallState = phone.getForegroundCall().getState();
1717
1718            return !hasRingingCall
1719                    && !allLinesTaken
1720                    && ((fgCallState == Call.State.ACTIVE)
1721                        || (fgCallState == Call.State.IDLE)
1722                        || (fgCallState == Call.State.DISCONNECTED));
1723        }
1724    }
1725
1726    /**
1727     * Based on the input CNAP number string,
1728     * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
1729     * Otherwise, return CNAP_SPECIAL_CASE_NO.
1730     */
1731    private static int checkCnapSpecialCases(String n) {
1732        if (n.equals("PRIVATE") ||
1733                n.equals("P") ||
1734                n.equals("RES")) {
1735            if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
1736            return Connection.PRESENTATION_RESTRICTED;
1737        } else if (n.equals("UNAVAILABLE") ||
1738                n.equals("UNKNOWN") ||
1739                n.equals("UNA") ||
1740                n.equals("U")) {
1741            if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
1742            return Connection.PRESENTATION_UNKNOWN;
1743        } else {
1744            if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
1745            return CNAP_SPECIAL_CASE_NO;
1746        }
1747    }
1748
1749    //
1750    // General phone and call state debugging/testing code
1751    //
1752
1753    /* package */ static void dumpCallState(Phone phone) {
1754        Log.d(LOG_TAG, "##### dumpCallState()");
1755        Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
1756              + ", state = " + phone.getState());
1757        Log.d(LOG_TAG, "-");
1758
1759        Call fgCall = phone.getForegroundCall();
1760        Log.d(LOG_TAG, "- FG call: " + fgCall);
1761        Log.d(LOG_TAG, "-  state: " + fgCall.getState());
1762        Log.d(LOG_TAG, "-  isAlive(): " + fgCall.getState().isAlive());
1763        Log.d(LOG_TAG, "-  isRinging(): " + fgCall.getState().isRinging());
1764        Log.d(LOG_TAG, "-  isDialing(): " + fgCall.getState().isDialing());
1765        Log.d(LOG_TAG, "-  isIdle(): " + fgCall.isIdle());
1766        Log.d(LOG_TAG, "-  hasConnections: " + fgCall.hasConnections());
1767        Log.d(LOG_TAG, "-");
1768
1769        Call bgCall = phone.getBackgroundCall();
1770        Log.d(LOG_TAG, "- BG call: " + bgCall);
1771        Log.d(LOG_TAG, "-  state: " + bgCall.getState());
1772        Log.d(LOG_TAG, "-  isAlive(): " + bgCall.getState().isAlive());
1773        Log.d(LOG_TAG, "-  isRinging(): " + bgCall.getState().isRinging());
1774        Log.d(LOG_TAG, "-  isDialing(): " + bgCall.getState().isDialing());
1775        Log.d(LOG_TAG, "-  isIdle(): " + bgCall.isIdle());
1776        Log.d(LOG_TAG, "-  hasConnections: " + bgCall.hasConnections());
1777        Log.d(LOG_TAG, "-");
1778
1779        Call ringingCall = phone.getRingingCall();
1780        Log.d(LOG_TAG, "- RINGING call: " + ringingCall);
1781        Log.d(LOG_TAG, "-  state: " + ringingCall.getState());
1782        Log.d(LOG_TAG, "-  isAlive(): " + ringingCall.getState().isAlive());
1783        Log.d(LOG_TAG, "-  isRinging(): " + ringingCall.getState().isRinging());
1784        Log.d(LOG_TAG, "-  isDialing(): " + ringingCall.getState().isDialing());
1785        Log.d(LOG_TAG, "-  isIdle(): " + ringingCall.isIdle());
1786        Log.d(LOG_TAG, "-  hasConnections: " + ringingCall.hasConnections());
1787        Log.d(LOG_TAG, "-");
1788
1789        final boolean hasRingingCall = !phone.getRingingCall().isIdle();
1790        final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
1791        final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
1792        final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
1793        Log.d(LOG_TAG, "- hasRingingCall: " + hasRingingCall);
1794        Log.d(LOG_TAG, "- hasActiveCall: " + hasActiveCall);
1795        Log.d(LOG_TAG, "- hasHoldingCall: " + hasHoldingCall);
1796        Log.d(LOG_TAG, "- allLinesTaken: " + allLinesTaken);
1797
1798        // Watch out: the isRinging() call below does NOT tell us anything
1799        // about the state of the telephony layer; it merely tells us whether
1800        // the Ringer manager is currently playing the ringtone.
1801        boolean ringing = PhoneApp.getInstance().getRinger().isRinging();
1802        Log.d(LOG_TAG, "- ringing (Ringer manager state): " + ringing);
1803        Log.d(LOG_TAG, "-----");
1804    }
1805
1806    private static void log(String msg) {
1807        Log.d(LOG_TAG, msg);
1808    }
1809}
1810