PhoneUtils.java revision 1ca2b2b333a7c22b728d648d3592ee064762dd00
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.AlertDialog;
20import android.app.Dialog;
21import android.app.ProgressDialog;
22import android.content.ComponentName;
23import android.content.ContentResolver;
24import android.content.Context;
25import android.content.DialogInterface;
26import android.content.Intent;
27import android.content.ServiceConnection;
28import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageManager;
30import android.graphics.drawable.Drawable;
31import android.media.AudioManager;
32import android.net.Uri;
33import android.net.sip.SipManager;
34import android.os.AsyncResult;
35import android.os.Handler;
36import android.os.IBinder;
37import android.os.Message;
38import android.os.RemoteException;
39import android.os.SystemProperties;
40import android.telephony.PhoneNumberUtils;
41import android.text.TextUtils;
42import android.util.Log;
43import android.view.KeyEvent;
44import android.view.LayoutInflater;
45import android.view.View;
46import android.view.WindowManager;
47import android.widget.EditText;
48import android.widget.Toast;
49
50import com.android.internal.telephony.Call;
51import com.android.internal.telephony.CallStateException;
52import com.android.internal.telephony.CallerInfo;
53import com.android.internal.telephony.CallerInfoAsyncQuery;
54import com.android.internal.telephony.Connection;
55import com.android.internal.telephony.IExtendedNetworkService;
56import com.android.internal.telephony.MmiCode;
57import com.android.internal.telephony.Phone;
58import com.android.internal.telephony.TelephonyProperties;
59import com.android.internal.telephony.cdma.CdmaConnection;
60import com.android.internal.telephony.CallManager;
61import com.android.internal.telephony.sip.SipPhone;
62
63import java.util.ArrayList;
64import java.util.Hashtable;
65import java.util.Iterator;
66import java.util.List;
67
68/**
69 * Misc utilities for the Phone app.
70 */
71public class PhoneUtils {
72    private static final String LOG_TAG = "PhoneUtils";
73    private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 2);
74
75    /** Control stack trace for Audio Mode settings */
76    private static final boolean DBG_SETAUDIOMODE_STACK = false;
77
78    /** Identifier for the "Add Call" intent extra. */
79    static final String ADD_CALL_MODE_KEY = "add_call_mode";
80
81    // Return codes from placeCall()
82    static final int CALL_STATUS_DIALED = 0;  // The number was successfully dialed
83    static final int CALL_STATUS_DIALED_MMI = 1;  // The specified number was an MMI code
84    static final int CALL_STATUS_FAILED = 2;  // The call failed
85
86    // State of the Phone's audio modes
87    // Each state can move to the other states, but within the state only certain
88    //  transitions for AudioManager.setMode() are allowed.
89    static final int AUDIO_IDLE = 0;  /** audio behaviour at phone idle */
90    static final int AUDIO_RINGING = 1;  /** audio behaviour while ringing */
91    static final int AUDIO_OFFHOOK = 2;  /** audio behaviour while in call. */
92
93    /** Speaker state, persisting between wired headset connection events */
94    private static boolean sIsSpeakerEnabled = false;
95
96    /** Hash table to store mute (Boolean) values based upon the connection.*/
97    private static Hashtable<Connection, Boolean> sConnectionMuteTable =
98        new Hashtable<Connection, Boolean>();
99
100    /** Static handler for the connection/mute tracking */
101    private static ConnectionHandler mConnectionHandler;
102
103    /** Phone state changed event*/
104    private static final int PHONE_STATE_CHANGED = -1;
105
106    /** Define for not a special CNAP string */
107    private static final int CNAP_SPECIAL_CASE_NO = -1;
108
109    // Extended network service interface instance
110    private static IExtendedNetworkService mNwService = null;
111    // used to cancel MMI command after 15 seconds timeout for NWService requirement
112    private static Message mMmiTimeoutCbMsg = null;
113
114    /** Noise suppression status as selected by user */
115    private static boolean sIsNoiseSuppressionEnabled = true;
116
117    /**
118     * Handler that tracks the connections and updates the value of the
119     * Mute settings for each connection as needed.
120     */
121    private static class ConnectionHandler extends Handler {
122        @Override
123        public void handleMessage(Message msg) {
124            AsyncResult ar = (AsyncResult) msg.obj;
125            switch (msg.what) {
126                case PHONE_STATE_CHANGED:
127                    if (DBG) log("ConnectionHandler: updating mute state for each connection");
128
129                    CallManager cm = (CallManager) ar.userObj;
130
131                    // update the foreground connections, if there are new connections.
132                    // Have to get all foreground calls instead of the active one
133                    // because there may two foreground calls co-exist in shore period
134                    // (a racing condition based on which phone changes firstly)
135                    // Otherwise the connection may get deleted.
136                    List<Connection> fgConnections = new ArrayList<Connection>();
137                    for (Call fgCall : cm.getForegroundCalls()) {
138                        if (!fgCall.isIdle()) {
139                            fgConnections.addAll(fgCall.getConnections());
140                        }
141                    }
142                    for (Connection cn : fgConnections) {
143                        if (sConnectionMuteTable.get(cn) == null) {
144                            sConnectionMuteTable.put(cn, Boolean.FALSE);
145                        }
146                    }
147
148                    // mute is connection based operation, we need loop over
149                    // all background calls instead of the first one to update
150                    // the background connections, if there are new connections.
151                    List<Connection> bgConnections = new ArrayList<Connection>();
152                    for (Call bgCall : cm.getBackgroundCalls()) {
153                        if (!bgCall.isIdle()) {
154                            bgConnections.addAll(bgCall.getConnections());
155                        }
156                    }
157                    for (Connection cn : bgConnections) {
158                        if (sConnectionMuteTable.get(cn) == null) {
159                          sConnectionMuteTable.put(cn, Boolean.FALSE);
160                        }
161                    }
162
163                    // Check to see if there are any lingering connections here
164                    // (disconnected connections), use old-school iterators to avoid
165                    // concurrent modification exceptions.
166                    Connection cn;
167                    for (Iterator<Connection> cnlist = sConnectionMuteTable.keySet().iterator();
168                            cnlist.hasNext();) {
169                        cn = cnlist.next();
170                        if (!fgConnections.contains(cn) && !bgConnections.contains(cn)) {
171                            if (DBG) log("connection '" + cn + "' not accounted for, removing.");
172                            cnlist.remove();
173                        }
174                    }
175
176                    // Restore the mute state of the foreground call if we're not IDLE,
177                    // otherwise just clear the mute state. This is really saying that
178                    // as long as there is one or more connections, we should update
179                    // the mute state with the earliest connection on the foreground
180                    // call, and that with no connections, we should be back to a
181                    // non-mute state.
182                    if (cm.getState() != Phone.State.IDLE) {
183                        restoreMuteState();
184                    } else {
185                        setMuteInternal(cm.getFgPhone(), false);
186                    }
187
188                    break;
189            }
190        }
191    }
192
193
194    private static ServiceConnection ExtendedNetworkServiceConnection = new ServiceConnection() {
195        public void onServiceConnected(ComponentName name, IBinder iBinder) {
196            if (DBG) log("Extended NW onServiceConnected");
197            mNwService = IExtendedNetworkService.Stub.asInterface(iBinder);
198        }
199
200        public void onServiceDisconnected(ComponentName arg0) {
201            if (DBG) log("Extended NW onServiceDisconnected");
202            mNwService = null;
203        }
204    };
205
206    /**
207     * Register the ConnectionHandler with the phone, to receive connection events
208     */
209    public static void initializeConnectionHandler(CallManager cm) {
210        if (mConnectionHandler == null) {
211            mConnectionHandler = new ConnectionHandler();
212        }
213
214        // pass over cm as user.obj
215        cm.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, cm);
216        // Extended NW service
217        Intent intent = new Intent("com.android.ussd.IExtendedNetworkService");
218        cm.getDefaultPhone().getContext().bindService(intent,
219                ExtendedNetworkServiceConnection, Context.BIND_AUTO_CREATE);
220        if (DBG) log("Extended NW bindService IExtendedNetworkService");
221
222    }
223
224    /** This class is never instantiated. */
225    private PhoneUtils() {
226    }
227
228    /**
229     * Answer the currently-ringing call.
230     *
231     * @return true if we answered the call, or false if there wasn't
232     *         actually a ringing incoming call, or some other error occurred.
233     *
234     * @see answerAndEndHolding()
235     * @see answerAndEndActive()
236     */
237    static boolean answerCall(Call ringing) {
238        if (DBG) log("answerCall()...");
239        final PhoneApp app = PhoneApp.getInstance();
240
241        // If the ringer is currently ringing and/or vibrating, stop it
242        // right now (before actually answering the call.)
243        app.getRinger().stopRing();
244
245        boolean answered = false;
246        Phone phone = ringing.getPhone();
247        boolean phoneIsCdma = (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA);
248        BluetoothHandsfree bthf = null;
249
250        if (phoneIsCdma) {
251            // Stop any signalInfo tone being played when a Call waiting gets answered
252            if (ringing.getState() == Call.State.WAITING) {
253                final CallNotifier notifier = app.notifier;
254                notifier.stopSignalInfoTone();
255            }
256        }
257
258        if (ringing != null && ringing.isRinging()) {
259            if (DBG) log("answerCall: call state = " + ringing.getState());
260            try {
261                if (phoneIsCdma) {
262                    if (app.cdmaPhoneCallState.getCurrentCallState()
263                            == CdmaPhoneCallState.PhoneCallState.IDLE) {
264                        // This is the FIRST incoming call being answered.
265                        // Set the Phone Call State to SINGLE_ACTIVE
266                        app.cdmaPhoneCallState.setCurrentCallState(
267                                CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
268                    } else {
269                        // This is the CALL WAITING call being answered.
270                        // Set the Phone Call State to CONF_CALL
271                        app.cdmaPhoneCallState.setCurrentCallState(
272                                CdmaPhoneCallState.PhoneCallState.CONF_CALL);
273                        // Enable "Add Call" option after answering a Call Waiting as the user
274                        // should be allowed to add another call in case one of the parties
275                        // drops off
276                        app.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(true);
277
278                        // If a BluetoothHandsfree is valid we need to set the second call state
279                        // so that the Bluetooth client can update the Call state correctly when
280                        // a call waiting is answered from the Phone.
281                        bthf = app.getBluetoothHandsfree();
282                        if (bthf != null) {
283                            bthf.cdmaSetSecondCallState(true);
284                        }
285                    }
286                }
287
288                //if (DBG) log("sPhone.acceptCall");
289                app.mCM.acceptCall(ringing);
290                answered = true;
291
292                // Always reset to "unmuted" for a freshly-answered call
293                setMute(false);
294
295                setAudioMode();
296
297                // Check is phone in any dock, and turn on speaker accordingly
298                activateSpeakerIfDocked(phone);
299            } catch (CallStateException ex) {
300                Log.w(LOG_TAG, "answerCall: caught " + ex, ex);
301
302                if (phoneIsCdma) {
303                    // restore the cdmaPhoneCallState and bthf.cdmaSetSecondCallState:
304                    app.cdmaPhoneCallState.setCurrentCallState(
305                            app.cdmaPhoneCallState.getPreviousCallState());
306                    if (bthf != null) {
307                        bthf.cdmaSetSecondCallState(false);
308                    }
309                }
310            }
311        }
312        return answered;
313    }
314
315    /**
316     * Smart "hang up" helper method which hangs up exactly one connection,
317     * based on the current Phone state, as follows:
318     * <ul>
319     * <li>If there's a ringing call, hang that up.
320     * <li>Else if there's a foreground call, hang that up.
321     * <li>Else if there's a background call, hang that up.
322     * <li>Otherwise do nothing.
323     * </ul>
324     * @return true if we successfully hung up, or false
325     *              if there were no active calls at all.
326     */
327    static boolean hangup(CallManager cm) {
328        boolean hungup = false;
329        Call ringing = cm.getFirstActiveRingingCall();
330        Call fg = cm.getActiveFgCall();
331        Call bg = cm.getFirstActiveBgCall();
332
333        if (!ringing.isIdle()) {
334            if (DBG) log("HANGUP ringing call");
335            hungup = hangupRingingCall(ringing);
336        } else if (!fg.isIdle()) {
337            if (DBG) log("HANGUP foreground call");
338            hungup = hangup(fg);
339        } else if (!bg.isIdle()) {
340            if (DBG) log("HANGUP background call");
341            hungup = hangup(bg);
342        }
343
344        if (DBG) log("hungup=" + hungup);
345
346        return hungup;
347    }
348
349    static boolean hangupRingingCall(Call ringing) {
350        if (DBG) log("hangup ringing call");
351        int phoneType = ringing.getPhone().getPhoneType();
352        Call.State state = ringing.getState();
353
354        if (state == Call.State.INCOMING) {
355            // Regular incoming call (with no other active calls)
356            if (DBG) log("- regular incoming call: hangup()");
357            return hangup(ringing);
358        } else if (state == Call.State.WAITING) {
359            // Call-waiting: there's an incoming call, but another call is
360            // already active.
361            // TODO: It would be better for the telephony layer to provide
362            // a "hangupWaitingCall()" API that works on all devices,
363            // rather than us having to check the phone type here and do
364            // the notifier.sendCdmaCallWaitingReject() hack for CDMA phones.
365            if (phoneType == Phone.PHONE_TYPE_CDMA) {
366                // CDMA: Ringing call and Call waiting hangup is handled differently.
367                // For Call waiting we DO NOT call the conventional hangup(call) function
368                // as in CDMA we just want to hangup the Call waiting connection.
369                if (DBG) log("- CDMA-specific call-waiting hangup");
370                final CallNotifier notifier = PhoneApp.getInstance().notifier;
371                notifier.sendCdmaCallWaitingReject();
372                return true;
373            } else {
374                // Otherwise, the regular hangup() API works for
375                // call-waiting calls too.
376                if (DBG) log("- call-waiting call: hangup()");
377                return hangup(ringing);
378            }
379        } else {
380            // Unexpected state: the ringing call isn't INCOMING or
381            // WAITING, so there's no reason to have called
382            // hangupRingingCall() in the first place.
383            // (Presumably the incoming call went away at the exact moment
384            // we got here, so just do nothing.)
385            Log.w(LOG_TAG, "hangupRingingCall: no INCOMING or WAITING call");
386            return false;
387        }
388    }
389
390    static boolean hangupActiveCall(Call foreground) {
391        if (DBG) log("hangup active call");
392        return hangup(foreground);
393    }
394
395    static boolean hangupHoldingCall(Call background) {
396        if (DBG) log("hangup holding call");
397        return hangup(background);
398    }
399
400    /**
401     * Used in CDMA phones to end the complete Call session
402     * @param phone the Phone object.
403     * @return true if *any* call was successfully hung up
404     */
405    static boolean hangupRingingAndActive(Phone phone) {
406        boolean hungUpRingingCall = false;
407        boolean hungUpFgCall = false;
408        Call ringingCall = phone.getRingingCall();
409        Call fgCall = phone.getForegroundCall();
410
411        // Hang up any Ringing Call
412        if (!ringingCall.isIdle()) {
413            if (DBG) log("endCallInternal: Hang up Ringing Call");
414            hungUpRingingCall = hangupRingingCall(ringingCall);
415        }
416
417        // Hang up any Active Call
418        if (!fgCall.isIdle()) {
419            if (DBG) log("endCallInternal: Hang up Foreground Call");
420            hungUpFgCall = hangupActiveCall(fgCall);
421        }
422
423        return hungUpRingingCall || hungUpFgCall;
424    }
425
426    /**
427     * Trivial wrapper around Call.hangup(), except that we return a
428     * boolean success code rather than throwing CallStateException on
429     * failure.
430     *
431     * @return true if the call was successfully hung up, or false
432     *         if the call wasn't actually active.
433     */
434    static boolean hangup(Call call) {
435        try {
436            CallManager cm = PhoneApp.getInstance().mCM;
437
438            if (call.getState() == Call.State.ACTIVE && cm.hasActiveBgCall()) {
439                // handle foreground call hangup while there is background call
440                cm.hangupForegroundResumeBackground(cm.getFirstActiveBgCall());
441            } else {
442                call.hangup();
443            }
444            return true;
445        } catch (CallStateException ex) {
446            Log.e(LOG_TAG, "Call hangup: caught " + ex, ex);
447        }
448
449        return false;
450    }
451
452    /**
453     * Trivial wrapper around Connection.hangup(), except that we silently
454     * do nothing (rather than throwing CallStateException) if the
455     * connection wasn't actually active.
456     */
457    static void hangup(Connection c) {
458        try {
459            if (c != null) {
460                c.hangup();
461            }
462        } catch (CallStateException ex) {
463            Log.w(LOG_TAG, "Connection hangup: caught " + ex, ex);
464        }
465    }
466
467    static boolean answerAndEndHolding(CallManager cm, Call ringing) {
468        if (DBG) log("end holding & answer waiting: 1");
469        if (!hangupHoldingCall(cm.getFirstActiveBgCall())) {
470            Log.e(LOG_TAG, "end holding failed!");
471            return false;
472        }
473
474        if (DBG) log("end holding & answer waiting: 2");
475        return answerCall(ringing);
476
477    }
478
479    static boolean answerAndEndActive(CallManager cm, Call ringing) {
480        if (DBG) log("answerAndEndActive()...");
481
482        // Unlike the answerCall() method, we *don't* need to stop the
483        // ringer or change audio modes here since the user is already
484        // in-call, which means that the audio mode is already set
485        // correctly, and that we wouldn't have started the ringer in the
486        // first place.
487
488        // hanging up the active call also accepts the waiting call
489        // while active call and waiting call are from the same phone
490        // i.e. both from GSM phone
491        if ( !hangupActiveCall(cm.getActiveFgCall())) {
492            Log.w(LOG_TAG, "end active call failed!");
493            return false;
494        }
495
496        // since hangupActiveCall() also accepts the ringing call
497        // check if the ringing call was already answered or not
498        // only answer it when the call still is ringing
499        if (ringing.isRinging()) {
500            return answerCall(ringing);
501        }
502
503        return true;
504    }
505
506    /**
507     * For a CDMA phone, advance the call state upon making a new
508     * outgoing call.
509     *
510     * <pre>
511     *   IDLE -> SINGLE_ACTIVE
512     * or
513     *   SINGLE_ACTIVE -> THRWAY_ACTIVE
514     * </pre>
515     * @param app The phone instance.
516     */
517    private static void updateCdmaCallStateOnNewOutgoingCall(PhoneApp app) {
518        if (app.cdmaPhoneCallState.getCurrentCallState() ==
519            CdmaPhoneCallState.PhoneCallState.IDLE) {
520            // This is the first outgoing call. Set the Phone Call State to ACTIVE
521            app.cdmaPhoneCallState.setCurrentCallState(
522                CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
523        } else {
524            // This is the second outgoing call. Set the Phone Call State to 3WAY
525            app.cdmaPhoneCallState.setCurrentCallState(
526                CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
527        }
528    }
529
530    /**
531     * Dial the number using the phone passed in.
532     *
533     * If the connection is establised, this method issues a sync call
534     * that may block to query the caller info.
535     * TODO: Change the logic to use the async query.
536     *
537     * @param context To perform the CallerInfo query.
538     * @param phone the Phone object.
539     * @param number to be dialed as requested by the user. This is
540     * NOT the phone number to connect to. It is used only to build the
541     * call card and to update the call log. See above for restrictions.
542     * @param contactRef that triggered the call. Typically a 'tel:'
543     * uri but can also be a 'content://contacts' one.
544     * @param isEmergencyCall indicates that whether or not this is an
545     * emergency call
546     * @param gatewayUri Is the address used to setup the connection, null
547     * if not using a gateway
548     *
549     * @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED
550     */
551    public static int placeCall(Context context, Phone phone,
552            String number, Uri contactRef, boolean isEmergencyCall,
553            Uri gatewayUri) {
554        if (DBG) log("placeCall '" + number + "' GW:'" + gatewayUri + "'");
555        final PhoneApp app = PhoneApp.getInstance();
556
557        boolean useGateway = false;
558        if (null != gatewayUri &&
559            !isEmergencyCall &&
560            PhoneUtils.isRoutableViaGateway(number)) {  // Filter out MMI, OTA and other codes.
561            useGateway = true;
562        }
563
564        int status = CALL_STATUS_DIALED;
565        Connection connection;
566        String numberToDial;
567        if (useGateway) {
568            // TODO: 'tel' should be a constant defined in framework base
569            // somewhere (it is in webkit.)
570            if (null == gatewayUri || !Constants.SCHEME_TEL.equals(gatewayUri.getScheme())) {
571                Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri);
572                return CALL_STATUS_FAILED;
573            }
574
575            // We can use getSchemeSpecificPart because we don't allow #
576            // in the gateway numbers (treated a fragment delim.) However
577            // if we allow more complex gateway numbers sequence (with
578            // passwords or whatnot) that use #, this may break.
579            // TODO: Need to support MMI codes.
580            numberToDial = gatewayUri.getSchemeSpecificPart();
581        } else {
582            numberToDial = number;
583        }
584
585        try {
586            connection = app.mCM.dial(phone, numberToDial);
587        } catch (CallStateException ex) {
588            // CallStateException means a new outgoing call is not currently
589            // possible: either no more call slots exist, or there's another
590            // call already in the process of dialing or ringing.
591            Log.w(LOG_TAG, "Exception from app.mCM.dial()", ex);
592            return CALL_STATUS_FAILED;
593
594            // Note that it's possible for CallManager.dial() to return
595            // null *without* throwing an exception; that indicates that
596            // we dialed an MMI (see below).
597        }
598
599        int phoneType = phone.getPhoneType();
600
601        // On GSM phones, null is returned for MMI codes
602        if (null == connection) {
603            if (phoneType == Phone.PHONE_TYPE_GSM && gatewayUri == null) {
604                if (DBG) log("dialed MMI code: " + number);
605                status = CALL_STATUS_DIALED_MMI;
606                // Set dialed MMI command to service
607                if (mNwService != null) {
608                    try {
609                        mNwService.setMmiString(number);
610                        if (DBG) log("Extended NW bindService setUssdString (" + number + ")");
611                    } catch (RemoteException e) {
612                        mNwService = null;
613                    }
614                }
615            } else {
616                status = CALL_STATUS_FAILED;
617            }
618        } else {
619            if (phoneType == Phone.PHONE_TYPE_CDMA) {
620                updateCdmaCallStateOnNewOutgoingCall(app);
621            }
622
623            // Clean up the number to be displayed.
624            if (phoneType == Phone.PHONE_TYPE_CDMA) {
625                number = CdmaConnection.formatDialString(number);
626            }
627            number = PhoneNumberUtils.extractNetworkPortion(number);
628            number = PhoneNumberUtils.convertKeypadLettersToDigits(number);
629            number = PhoneNumberUtils.formatNumber(number);
630
631            if (gatewayUri == null) {
632                // phone.dial() succeeded: we're now in a normal phone call.
633                // attach the URI to the CallerInfo Object if it is there,
634                // otherwise just attach the Uri Reference.
635                // if the uri does not have a "content" scheme, then we treat
636                // it as if it does NOT have a unique reference.
637                String content = context.getContentResolver().SCHEME_CONTENT;
638                if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
639                    Object userDataObject = connection.getUserData();
640                    if (userDataObject == null) {
641                        connection.setUserData(contactRef);
642                    } else {
643                        // TODO: This branch is dead code, we have
644                        // just created the connection which has
645                        // no user data (null) by default.
646                        if (userDataObject instanceof CallerInfo) {
647                        ((CallerInfo) userDataObject).contactRefUri = contactRef;
648                        } else {
649                        ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
650                            contactRef;
651                        }
652                    }
653                }
654            } else {
655                // Get the caller info synchronously because we need the final
656                // CallerInfo object to update the dialed number with the one
657                // requested by the user (and not the provider's gateway number).
658                CallerInfo info = null;
659                String content = phone.getContext().getContentResolver().SCHEME_CONTENT;
660                if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
661                    info = CallerInfo.getCallerInfo(context, contactRef);
662                }
663
664                // Fallback, lookup contact using the phone number if the
665                // contact's URI scheme was not content:// or if is was but
666                // the lookup failed.
667                if (null == info) {
668                    info = CallerInfo.getCallerInfo(context, number);
669                }
670                info.phoneNumber = number;
671                connection.setUserData(info);
672            }
673            setAudioMode();
674
675            if (DBG) log("about to activate speaker");
676            // Check is phone in any dock, and turn on speaker accordingly
677            activateSpeakerIfDocked(phone);
678        }
679
680        return status;
681    }
682
683    /**
684     * Wrapper function to control when to send an empty Flash command to the network.
685     * Mainly needed for CDMA networks, such as scenarios when we need to send a blank flash
686     * to the network prior to placing a 3-way call for it to be successful.
687     */
688    static void sendEmptyFlash(Phone phone) {
689        if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) {
690            Call fgCall = phone.getForegroundCall();
691            if (fgCall.getState() == Call.State.ACTIVE) {
692                // Send the empty flash
693                if (DBG) Log.d(LOG_TAG, "onReceive: (CDMA) sending empty flash to network");
694                switchHoldingAndActive(phone.getBackgroundCall());
695            }
696        }
697    }
698
699    /**
700     * @param heldCall is the background call want to be swapped
701     */
702    static void switchHoldingAndActive(Call heldCall) {
703        try {
704            if (DBG) log("switchHoldingAndActive");
705            CallManager cm = PhoneApp.getInstance().mCM;
706            if (heldCall.isIdle()) {
707                // no heldCall, so it is to hold active call
708                cm.switchHoldingAndActive(cm.getFgPhone().getBackgroundCall());
709            } else {
710                // has particular heldCall, so to switch
711                cm.switchHoldingAndActive(heldCall);
712            }
713            setAudioMode(cm);
714        } catch (CallStateException ex) {
715            Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex);
716        }
717    }
718
719    /**
720     * Restore the mute setting from the earliest connection of the
721     * foreground call.
722     */
723    static Boolean restoreMuteState() {
724        Phone phone = PhoneApp.getInstance().mCM.getFgPhone();
725
726        //get the earliest connection
727        Connection c = phone.getForegroundCall().getEarliestConnection();
728
729        // only do this if connection is not null.
730        if (c != null) {
731
732            int phoneType = phone.getPhoneType();
733
734            // retrieve the mute value.
735            Boolean shouldMute = null;
736
737            // In CDMA, mute is not maintained per Connection. Single mute apply for
738            // a call where  call can have multiple connections such as
739            // Three way and Call Waiting.  Therefore retrieving Mute state for
740            // latest connection can apply for all connection in that call
741            if (phoneType == Phone.PHONE_TYPE_CDMA) {
742                shouldMute = sConnectionMuteTable.get(
743                        phone.getForegroundCall().getLatestConnection());
744            } else if ((phoneType == Phone.PHONE_TYPE_GSM)
745                    || (phoneType == Phone.PHONE_TYPE_SIP)) {
746                shouldMute = sConnectionMuteTable.get(c);
747            }
748            if (shouldMute == null) {
749                if (DBG) log("problem retrieving mute value for this connection.");
750                shouldMute = Boolean.FALSE;
751            }
752
753            // set the mute value and return the result.
754            setMute (shouldMute.booleanValue());
755            return shouldMute;
756        }
757        return Boolean.valueOf(getMute());
758    }
759
760    static void mergeCalls() {
761        mergeCalls(PhoneApp.getInstance().mCM);
762    }
763
764    static void mergeCalls(CallManager cm) {
765        int phoneType = cm.getFgPhone().getPhoneType();
766        if (phoneType == Phone.PHONE_TYPE_CDMA) {
767            if (DBG) log("mergeCalls");
768            PhoneApp app = PhoneApp.getInstance();
769            if (app.cdmaPhoneCallState.getCurrentCallState()
770                    == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
771                // Set the Phone Call State to conference
772                app.cdmaPhoneCallState.setCurrentCallState(
773                        CdmaPhoneCallState.PhoneCallState.CONF_CALL);
774
775                // Send flash cmd
776                // TODO: Need to change the call from switchHoldingAndActive to
777                // something meaningful as we are not actually trying to swap calls but
778                // instead are merging two calls by sending a Flash command.
779                switchHoldingAndActive(cm.getFirstActiveBgCall());
780            }
781        } else {
782            try {
783                if (DBG) log("mergeCalls");
784                cm.conference(cm.getFirstActiveBgCall());
785            } catch (CallStateException ex) {
786                Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex);
787            }
788        }
789    }
790
791    static void separateCall(Connection c) {
792        try {
793            if (DBG) log("separateCall: " + c.getAddress());
794            c.separate();
795        } catch (CallStateException ex) {
796            Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
797        }
798    }
799
800    /**
801     * Handle the MMIInitiate message and put up an alert that lets
802     * the user cancel the operation, if applicable.
803     *
804     * @param context context to get strings.
805     * @param mmiCode the MmiCode object being started.
806     * @param buttonCallbackMessage message to post when button is clicked.
807     * @param previousAlert a previous alert used in this activity.
808     * @return the dialog handle
809     */
810    static Dialog displayMMIInitiate(Context context,
811                                          MmiCode mmiCode,
812                                          Message buttonCallbackMessage,
813                                          Dialog previousAlert) {
814        if (DBG) log("displayMMIInitiate: " + mmiCode);
815        if (previousAlert != null) {
816            previousAlert.dismiss();
817        }
818
819        // The UI paradigm we are using now requests that all dialogs have
820        // user interaction, and that any other messages to the user should
821        // be by way of Toasts.
822        //
823        // In adhering to this request, all MMI initiating "OK" dialogs
824        // (non-cancelable MMIs) that end up being closed when the MMI
825        // completes (thereby showing a completion dialog) are being
826        // replaced with Toasts.
827        //
828        // As a side effect, moving to Toasts for the non-cancelable MMIs
829        // also means that buttonCallbackMessage (which was tied into "OK")
830        // is no longer invokable for these dialogs.  This is not a problem
831        // since the only callback messages we supported were for cancelable
832        // MMIs anyway.
833        //
834        // A cancelable MMI is really just a USSD request. The term
835        // "cancelable" here means that we can cancel the request when the
836        // system prompts us for a response, NOT while the network is
837        // processing the MMI request.  Any request to cancel a USSD while
838        // the network is NOT ready for a response may be ignored.
839        //
840        // With this in mind, we replace the cancelable alert dialog with
841        // a progress dialog, displayed until we receive a request from
842        // the the network.  For more information, please see the comments
843        // in the displayMMIComplete() method below.
844        //
845        // Anything that is NOT a USSD request is a normal MMI request,
846        // which will bring up a toast (desribed above).
847        // Optional code for Extended USSD running prompt
848        if (mNwService != null) {
849            if (DBG) log("running USSD code, displaying indeterminate progress.");
850            // create the indeterminate progress dialog and display it.
851            ProgressDialog pd = new ProgressDialog(context);
852            CharSequence textmsg = "";
853            try {
854                textmsg = mNwService.getMmiRunningText();
855
856            } catch (RemoteException e) {
857                mNwService = null;
858                textmsg = context.getText(R.string.ussdRunning);
859            }
860            if (DBG) log("Extended NW displayMMIInitiate (" + textmsg+ ")");
861            pd.setMessage(textmsg);
862            pd.setCancelable(false);
863            pd.setIndeterminate(true);
864            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
865            pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
866            pd.show();
867            // trigger a 15 seconds timeout to clear this progress dialog
868            mMmiTimeoutCbMsg = buttonCallbackMessage;
869            try {
870                mMmiTimeoutCbMsg.getTarget().sendMessageDelayed(buttonCallbackMessage, 15000);
871            } catch(NullPointerException e) {
872                mMmiTimeoutCbMsg = null;
873            }
874            return pd;
875        }
876
877        boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
878
879        if (!isCancelable) {
880            if (DBG) log("not a USSD code, displaying status toast.");
881            CharSequence text = context.getText(R.string.mmiStarted);
882            Toast.makeText(context, text, Toast.LENGTH_SHORT)
883                .show();
884            return null;
885        } else {
886            if (DBG) log("running USSD code, displaying indeterminate progress.");
887
888            // create the indeterminate progress dialog and display it.
889            ProgressDialog pd = new ProgressDialog(context);
890            pd.setMessage(context.getText(R.string.ussdRunning));
891            pd.setCancelable(false);
892            pd.setIndeterminate(true);
893            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
894
895            pd.show();
896
897            return pd;
898        }
899
900    }
901
902    /**
903     * Handle the MMIComplete message and fire off an intent to display
904     * the message.
905     *
906     * @param context context to get strings.
907     * @param mmiCode MMI result.
908     * @param previousAlert a previous alert used in this activity.
909     */
910    static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
911            Message dismissCallbackMessage,
912            AlertDialog previousAlert) {
913        final PhoneApp app = PhoneApp.getInstance();
914        CharSequence text;
915        int title = 0;  // title for the progress dialog, if needed.
916        MmiCode.State state = mmiCode.getState();
917
918        if (DBG) log("displayMMIComplete: state=" + state);
919        // Clear timeout trigger message
920        if(mMmiTimeoutCbMsg != null) {
921            try{
922                mMmiTimeoutCbMsg.getTarget().removeMessages(mMmiTimeoutCbMsg.what);
923                if (DBG) log("Extended NW displayMMIComplete removeMsg");
924            } catch (NullPointerException e) {
925            }
926            mMmiTimeoutCbMsg = null;
927        }
928
929
930        switch (state) {
931            case PENDING:
932                // USSD code asking for feedback from user.
933                text = mmiCode.getMessage();
934                if (DBG) log("- using text from PENDING MMI message: '" + text + "'");
935                break;
936            case CANCELLED:
937                text = context.getText(R.string.mmiCancelled);
938                break;
939            case COMPLETE:
940                if (app.getPUKEntryActivity() != null) {
941                    // if an attempt to unPUK the device was made, we specify
942                    // the title and the message here.
943                    title = com.android.internal.R.string.PinMmi;
944                    text = context.getText(R.string.puk_unlocked);
945                    break;
946                }
947                // All other conditions for the COMPLETE mmi state will cause
948                // the case to fall through to message logic in common with
949                // the FAILED case.
950
951            case FAILED:
952                text = mmiCode.getMessage();
953                if (DBG) log("- using text from MMI message: '" + text + "'");
954                break;
955            default:
956                throw new IllegalStateException("Unexpected MmiCode state: " + state);
957        }
958
959        if (previousAlert != null) {
960            previousAlert.dismiss();
961        }
962
963        // Check to see if a UI exists for the PUK activation.  If it does
964        // exist, then it indicates that we're trying to unblock the PUK.
965        if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
966            if (DBG) log("displaying PUK unblocking progress dialog.");
967
968            // create the progress dialog, make sure the flags and type are
969            // set correctly.
970            ProgressDialog pd = new ProgressDialog(app);
971            pd.setTitle(title);
972            pd.setMessage(text);
973            pd.setCancelable(false);
974            pd.setIndeterminate(true);
975            pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
976            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
977
978            // display the dialog
979            pd.show();
980
981            // indicate to the Phone app that the progress dialog has
982            // been assigned for the PUK unlock / SIM READY process.
983            app.setPukEntryProgressDialog(pd);
984
985        } else {
986            // In case of failure to unlock, we'll need to reset the
987            // PUK unlock activity, so that the user may try again.
988            if (app.getPUKEntryActivity() != null) {
989                app.setPukEntryActivity(null);
990            }
991
992            // A USSD in a pending state means that it is still
993            // interacting with the user.
994            if (state != MmiCode.State.PENDING) {
995                if (DBG) log("MMI code has finished running.");
996
997                // Replace response message with Extended Mmi wording
998                if (mNwService != null) {
999                    try {
1000                        text = mNwService.getUserMessage(text);
1001                    } catch (RemoteException e) {
1002                        mNwService = null;
1003                    }
1004                    if (DBG) log("Extended NW displayMMIInitiate (" + text + ")");
1005                    if (text == null || text.length() == 0)
1006                        return;
1007                }
1008
1009                // displaying system alert dialog on the screen instead of
1010                // using another activity to display the message.  This
1011                // places the message at the forefront of the UI.
1012                AlertDialog newDialog = new AlertDialog.Builder(context)
1013                        .setMessage(text)
1014                        .setPositiveButton(R.string.ok, null)
1015                        .setCancelable(true)
1016                        .create();
1017
1018                newDialog.getWindow().setType(
1019                        WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
1020                newDialog.getWindow().addFlags(
1021                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1022
1023                newDialog.show();
1024            } else {
1025                if (DBG) log("USSD code has requested user input. Constructing input dialog.");
1026
1027                // USSD MMI code that is interacting with the user.  The
1028                // basic set of steps is this:
1029                //   1. User enters a USSD request
1030                //   2. We recognize the request and displayMMIInitiate
1031                //      (above) creates a progress dialog.
1032                //   3. Request returns and we get a PENDING or COMPLETE
1033                //      message.
1034                //   4. These MMI messages are caught in the PhoneApp
1035                //      (onMMIComplete) and the InCallScreen
1036                //      (mHandler.handleMessage) which bring up this dialog
1037                //      and closes the original progress dialog,
1038                //      respectively.
1039                //   5. If the message is anything other than PENDING,
1040                //      we are done, and the alert dialog (directly above)
1041                //      displays the outcome.
1042                //   6. If the network is requesting more information from
1043                //      the user, the MMI will be in a PENDING state, and
1044                //      we display this dialog with the message.
1045                //   7. User input, or cancel requests result in a return
1046                //      to step 1.  Keep in mind that this is the only
1047                //      time that a USSD should be canceled.
1048
1049                // inflate the layout with the scrolling text area for the dialog.
1050                LayoutInflater inflater = (LayoutInflater) context.getSystemService(
1051                        Context.LAYOUT_INFLATER_SERVICE);
1052                View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
1053
1054                // get the input field.
1055                final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
1056
1057                // specify the dialog's click listener, with SEND and CANCEL logic.
1058                final DialogInterface.OnClickListener mUSSDDialogListener =
1059                    new DialogInterface.OnClickListener() {
1060                        public void onClick(DialogInterface dialog, int whichButton) {
1061                            switch (whichButton) {
1062                                case DialogInterface.BUTTON_POSITIVE:
1063                                    phone.sendUssdResponse(inputText.getText().toString());
1064                                    break;
1065                                case DialogInterface.BUTTON_NEGATIVE:
1066                                    if (mmiCode.isCancelable()) {
1067                                        mmiCode.cancel();
1068                                    }
1069                                    break;
1070                            }
1071                        }
1072                    };
1073
1074                // build the dialog
1075                final AlertDialog newDialog = new AlertDialog.Builder(context)
1076                        .setMessage(text)
1077                        .setView(dialogView)
1078                        .setPositiveButton(R.string.send_button, mUSSDDialogListener)
1079                        .setNegativeButton(R.string.cancel, mUSSDDialogListener)
1080                        .setCancelable(false)
1081                        .create();
1082
1083                // attach the key listener to the dialog's input field and make
1084                // sure focus is set.
1085                final View.OnKeyListener mUSSDDialogInputListener =
1086                    new View.OnKeyListener() {
1087                        public boolean onKey(View v, int keyCode, KeyEvent event) {
1088                            switch (keyCode) {
1089                                case KeyEvent.KEYCODE_CALL:
1090                                case KeyEvent.KEYCODE_ENTER:
1091                                    if(event.getAction() == KeyEvent.ACTION_DOWN) {
1092                                        phone.sendUssdResponse(inputText.getText().toString());
1093                                        newDialog.dismiss();
1094                                    }
1095                                    return true;
1096                            }
1097                            return false;
1098                        }
1099                    };
1100                inputText.setOnKeyListener(mUSSDDialogInputListener);
1101                inputText.requestFocus();
1102
1103                // set the window properties of the dialog
1104                newDialog.getWindow().setType(
1105                        WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
1106                newDialog.getWindow().addFlags(
1107                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1108
1109                // now show the dialog!
1110                newDialog.show();
1111            }
1112        }
1113    }
1114
1115    /**
1116     * Cancels the current pending MMI operation, if applicable.
1117     * @return true if we canceled an MMI operation, or false
1118     *         if the current pending MMI wasn't cancelable
1119     *         or if there was no current pending MMI at all.
1120     *
1121     * @see displayMMIInitiate
1122     */
1123    static boolean cancelMmiCode(Phone phone) {
1124        List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
1125        int count = pendingMmis.size();
1126        if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
1127
1128        boolean canceled = false;
1129        if (count > 0) {
1130            // assume that we only have one pending MMI operation active at a time.
1131            // I don't think it's possible to enter multiple MMI codes concurrently
1132            // in the phone UI, because during the MMI operation, an Alert panel
1133            // is displayed, which prevents more MMI code from being entered.
1134            MmiCode mmiCode = pendingMmis.get(0);
1135            if (mmiCode.isCancelable()) {
1136                mmiCode.cancel();
1137                canceled = true;
1138            }
1139        }
1140
1141        //clear timeout message and pre-set MMI command
1142        if (mNwService != null) {
1143            try {
1144                mNwService.clearMmiString();
1145            } catch (RemoteException e) {
1146                mNwService = null;
1147            }
1148        }
1149        if (mMmiTimeoutCbMsg != null) {
1150            mMmiTimeoutCbMsg = null;
1151        }
1152        return canceled;
1153    }
1154
1155    public static class VoiceMailNumberMissingException extends Exception {
1156        VoiceMailNumberMissingException() {
1157            super();
1158        }
1159
1160        VoiceMailNumberMissingException(String msg) {
1161            super(msg);
1162        }
1163    }
1164
1165    /**
1166     * Gets the phone number to be called from an intent.  Requires a Context
1167     * to access the contacts database, and a Phone to access the voicemail
1168     * number.
1169     *
1170     * <p>If <code>phone</code> is <code>null</code>, the function will return
1171     * <code>null</code> for <code>voicemail:</code> URIs;
1172     * if <code>context</code> is <code>null</code>, the function will return
1173     * <code>null</code> for person/phone URIs.</p>
1174     *
1175     * <p>If the intent contains a <code>sip:</code> URI, the returned
1176     * "number" is actually the SIP address.
1177     *
1178     * @param context a context to use (or
1179     * @param intent the intent
1180     *
1181     * @throws VoiceMailNumberMissingException if <code>intent</code> contains
1182     *         a <code>voicemail:</code> URI, but <code>phone</code> does not
1183     *         have a voicemail number set.
1184     *
1185     * @return the phone number (or SIP address) that would be called by the intent,
1186     *         or <code>null</code> if the number cannot be found.
1187     */
1188    static String getNumberFromIntent(Context context, Intent intent)
1189            throws VoiceMailNumberMissingException {
1190        Uri uri = intent.getData();
1191        String scheme = uri.getScheme();
1192
1193        // The sip: scheme is simple: just treat the rest of the URI as a
1194        // SIP address.
1195        if (Constants.SCHEME_SIP.equals(scheme)) {
1196            return uri.getSchemeSpecificPart();
1197        }
1198
1199        // Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle
1200        // the other cases (i.e. tel: and voicemail: and contact: URIs.)
1201
1202        final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
1203
1204        // Check for a voicemail-dialing request.  If the voicemail number is
1205        // empty, throw a VoiceMailNumberMissingException.
1206        if (Constants.SCHEME_VOICEMAIL.equals(scheme) &&
1207                (number == null || TextUtils.isEmpty(number)))
1208            throw new VoiceMailNumberMissingException();
1209
1210        return number;
1211    }
1212
1213    /**
1214     * Returns the caller-id info corresponding to the specified Connection.
1215     * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
1216     * extract a phone number from the specified Connection, and feed that
1217     * number into CallerInfo.getCallerInfo().)
1218     *
1219     * The returned CallerInfo may be null in certain error cases, like if the
1220     * specified Connection was null, or if we weren't able to get a valid
1221     * phone number from the Connection.
1222     *
1223     * Finally, if the getCallerInfo() call did succeed, we save the resulting
1224     * CallerInfo object in the "userData" field of the Connection.
1225     *
1226     * NOTE: This API should be avoided, with preference given to the
1227     * asynchronous startGetCallerInfo API.
1228     */
1229    static CallerInfo getCallerInfo(Context context, Connection c) {
1230        CallerInfo info = null;
1231
1232        if (c != null) {
1233            //See if there is a URI attached.  If there is, this means
1234            //that there is no CallerInfo queried yet, so we'll need to
1235            //replace the URI with a full CallerInfo object.
1236            Object userDataObject = c.getUserData();
1237            if (userDataObject instanceof Uri) {
1238                info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
1239                if (info != null) {
1240                    c.setUserData(info);
1241                }
1242            } else {
1243                if (userDataObject instanceof CallerInfoToken) {
1244                    //temporary result, while query is running
1245                    info = ((CallerInfoToken) userDataObject).currentInfo;
1246                } else {
1247                    //final query result
1248                    info = (CallerInfo) userDataObject;
1249                }
1250                if (info == null) {
1251                    // No URI, or Existing CallerInfo, so we'll have to make do with
1252                    // querying a new CallerInfo using the connection's phone number.
1253                    String number = c.getAddress();
1254
1255                    if (DBG) log("getCallerInfo: number = " + number);
1256
1257                    if (!TextUtils.isEmpty(number)) {
1258                        info = CallerInfo.getCallerInfo(context, number);
1259                        if (info != null) {
1260                            c.setUserData(info);
1261                        }
1262                    }
1263                }
1264            }
1265        }
1266        return info;
1267    }
1268
1269    /**
1270     * Class returned by the startGetCallerInfo call to package a temporary
1271     * CallerInfo Object, to be superceded by the CallerInfo Object passed
1272     * into the listener when the query with token mAsyncQueryToken is complete.
1273     */
1274    public static class CallerInfoToken {
1275        /**indicates that there will no longer be updates to this request.*/
1276        public boolean isFinal;
1277
1278        public CallerInfo currentInfo;
1279        public CallerInfoAsyncQuery asyncQuery;
1280    }
1281
1282    /**
1283     * Start a CallerInfo Query based on the earliest connection in the call.
1284     */
1285    static CallerInfoToken startGetCallerInfo(Context context, Call call,
1286            CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1287        Connection conn = null;
1288        int phoneType = call.getPhone().getPhoneType();
1289        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1290            conn = call.getLatestConnection();
1291        } else if ((phoneType == Phone.PHONE_TYPE_GSM)
1292                || (phoneType == Phone.PHONE_TYPE_SIP)) {
1293            conn = call.getEarliestConnection();
1294        } else {
1295            throw new IllegalStateException("Unexpected phone type: " + phoneType);
1296        }
1297
1298        return startGetCallerInfo(context, conn, listener, cookie);
1299    }
1300
1301    /**
1302     * place a temporary callerinfo object in the hands of the caller and notify
1303     * caller when the actual query is done.
1304     */
1305    static CallerInfoToken startGetCallerInfo(Context context, Connection c,
1306            CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1307        CallerInfoToken cit;
1308
1309        if (c == null) {
1310            //TODO: perhaps throw an exception here.
1311            cit = new CallerInfoToken();
1312            cit.asyncQuery = null;
1313            return cit;
1314        }
1315
1316        Object userDataObject = c.getUserData();
1317
1318        // There are now 3 states for the Connection's userData object:
1319        //
1320        //   (1) Uri - query has not been executed yet
1321        //
1322        //   (2) CallerInfoToken - query is executing, but has not completed.
1323        //
1324        //   (3) CallerInfo - query has executed.
1325        //
1326        // In each case we have slightly different behaviour:
1327        //   1. If the query has not been executed yet (Uri or null), we start
1328        //      query execution asynchronously, and note it by attaching a
1329        //      CallerInfoToken as the userData.
1330        //   2. If the query is executing (CallerInfoToken), we've essentially
1331        //      reached a state where we've received multiple requests for the
1332        //      same callerInfo.  That means that once the query is complete,
1333        //      we'll need to execute the additional listener requested.
1334        //   3. If the query has already been executed (CallerInfo), we just
1335        //      return the CallerInfo object as expected.
1336        //   4. Regarding isFinal - there are cases where the CallerInfo object
1337        //      will not be attached, like when the number is empty (caller id
1338        //      blocking).  This flag is used to indicate that the
1339        //      CallerInfoToken object is going to be permanent since no
1340        //      query results will be returned.  In the case where a query
1341        //      has been completed, this flag is used to indicate to the caller
1342        //      that the data will not be updated since it is valid.
1343        //
1344        //      Note: For the case where a number is NOT retrievable, we leave
1345        //      the CallerInfo as null in the CallerInfoToken.  This is
1346        //      something of a departure from the original code, since the old
1347        //      code manufactured a CallerInfo object regardless of the query
1348        //      outcome.  From now on, we will append an empty CallerInfo
1349        //      object, to mirror previous behaviour, and to avoid Null Pointer
1350        //      Exceptions.
1351
1352        if (userDataObject instanceof Uri) {
1353            // State (1): query has not been executed yet
1354
1355            //create a dummy callerinfo, populate with what we know from URI.
1356            cit = new CallerInfoToken();
1357            cit.currentInfo = new CallerInfo();
1358            cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1359                    (Uri) userDataObject, sCallerInfoQueryListener, c);
1360            cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1361            cit.isFinal = false;
1362
1363            c.setUserData(cit);
1364
1365            if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
1366
1367        } else if (userDataObject == null) {
1368            // No URI, or Existing CallerInfo, so we'll have to make do with
1369            // querying a new CallerInfo using the connection's phone number.
1370            String number = c.getAddress();
1371
1372            if (DBG) {
1373                log("###### PhoneUtils.startGetCallerInfo: new query for phone number #####");
1374                log("- number (address): " + number);
1375                log("- c: " + c);
1376                log("- phone: " + c.getCall().getPhone());
1377                int phoneType = c.getCall().getPhone().getPhoneType();
1378                log("- phoneType: " + phoneType);
1379                switch (phoneType) {
1380                    case Phone.PHONE_TYPE_NONE: log("  ==> PHONE_TYPE_NONE"); break;
1381                    case Phone.PHONE_TYPE_GSM: log("  ==> PHONE_TYPE_GSM"); break;
1382                    case Phone.PHONE_TYPE_CDMA: log("  ==> PHONE_TYPE_CDMA"); break;
1383                    case Phone.PHONE_TYPE_SIP: log("  ==> PHONE_TYPE_SIP"); break;
1384                    default: log("  ==> Unknown phone type"); break;
1385                }
1386            }
1387
1388            cit = new CallerInfoToken();
1389            cit.currentInfo = new CallerInfo();
1390
1391            // Store CNAP information retrieved from the Connection (we want to do this
1392            // here regardless of whether the number is empty or not).
1393            cit.currentInfo.cnapName =  c.getCnapName();
1394            cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
1395                                                             // by ContactInfo later
1396            cit.currentInfo.numberPresentation = c.getNumberPresentation();
1397            cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1398
1399            if (DBG) {
1400                log("startGetCallerInfo: number = " + number);
1401                log("startGetCallerInfo: CNAP Info from FW(1): name="
1402                    + cit.currentInfo.cnapName
1403                    + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1404            }
1405
1406            // handling case where number is null (caller id hidden) as well.
1407            if (!TextUtils.isEmpty(number)) {
1408                // Check for special CNAP cases and modify the CallerInfo accordingly
1409                // to be sure we keep the right information to display/log later
1410                number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
1411                        cit.currentInfo.numberPresentation);
1412
1413                cit.currentInfo.phoneNumber = number;
1414                // For scenarios where we may receive a valid number from the network but a
1415                // restricted/unavailable presentation, we do not want to perform a contact query
1416                // (see note on isFinal above). So we set isFinal to true here as well.
1417                if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) {
1418                    cit.isFinal = true;
1419                } else {
1420                    if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
1421                    cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1422                            number, sCallerInfoQueryListener, c);
1423                    cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1424                    cit.isFinal = false;
1425                }
1426            } else {
1427                // This is the case where we are querying on a number that
1428                // is null or empty, like a caller whose caller id is
1429                // blocked or empty (CLIR).  The previous behaviour was to
1430                // throw a null CallerInfo object back to the user, but
1431                // this departure is somewhat cleaner.
1432                if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
1433                cit.isFinal = true; // please see note on isFinal, above.
1434            }
1435
1436            c.setUserData(cit);
1437
1438            if (DBG) log("startGetCallerInfo: query based on number: " + number);
1439
1440        } else if (userDataObject instanceof CallerInfoToken) {
1441            // State (2): query is executing, but has not completed.
1442
1443            // just tack on this listener to the queue.
1444            cit = (CallerInfoToken) userDataObject;
1445
1446            // handling case where number is null (caller id hidden) as well.
1447            if (cit.asyncQuery != null) {
1448                cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1449
1450                if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
1451                        listener.getClass().toString());
1452            } else {
1453                // handling case where number/name gets updated later on by the network
1454                String updatedNumber = c.getAddress();
1455                if (DBG) log("startGetCallerInfo: updatedNumber initially = " + updatedNumber);
1456                if (!TextUtils.isEmpty(updatedNumber)) {
1457                    // Store CNAP information retrieved from the Connection
1458                    cit.currentInfo.cnapName =  c.getCnapName();
1459                    // This can still get overwritten by ContactInfo
1460                    cit.currentInfo.name = cit.currentInfo.cnapName;
1461                    cit.currentInfo.numberPresentation = c.getNumberPresentation();
1462                    cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1463
1464                    updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
1465                            updatedNumber, cit.currentInfo.numberPresentation);
1466
1467                    cit.currentInfo.phoneNumber = updatedNumber;
1468                    if (DBG) log("startGetCallerInfo: updatedNumber=" + updatedNumber);
1469                    if (DBG) log("startGetCallerInfo: CNAP Info from FW(2): name="
1470                            + cit.currentInfo.cnapName
1471                            + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1472                    // For scenarios where we may receive a valid number from the network but a
1473                    // restricted/unavailable presentation, we do not want to perform a contact query
1474                    // (see note on isFinal above). So we set isFinal to true here as well.
1475                    if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) {
1476                        cit.isFinal = true;
1477                    } else {
1478                        cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1479                                updatedNumber, sCallerInfoQueryListener, c);
1480                        cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1481                        cit.isFinal = false;
1482                    }
1483                } else {
1484                    if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
1485                    if (cit.currentInfo == null) {
1486                        cit.currentInfo = new CallerInfo();
1487                    }
1488                    // Store CNAP information retrieved from the Connection
1489                    cit.currentInfo.cnapName = c.getCnapName();  // This can still get
1490                                                                 // overwritten by ContactInfo
1491                    cit.currentInfo.name = cit.currentInfo.cnapName;
1492                    cit.currentInfo.numberPresentation = c.getNumberPresentation();
1493                    cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1494
1495                    if (DBG) log("startGetCallerInfo: CNAP Info from FW(3): name="
1496                            + cit.currentInfo.cnapName
1497                            + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1498                    cit.isFinal = true; // please see note on isFinal, above.
1499                }
1500            }
1501        } else {
1502            // State (3): query is complete.
1503
1504            // The connection's userDataObject is a full-fledged
1505            // CallerInfo instance.  Wrap it in a CallerInfoToken and
1506            // return it to the user.
1507
1508            cit = new CallerInfoToken();
1509            cit.currentInfo = (CallerInfo) userDataObject;
1510            cit.asyncQuery = null;
1511            cit.isFinal = true;
1512            // since the query is already done, call the listener.
1513            if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
1514            if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
1515        }
1516        return cit;
1517    }
1518
1519    /**
1520     * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
1521     * we use with all our CallerInfoAsyncQuery.startQuery() requests.
1522     */
1523    private static final int QUERY_TOKEN = -1;
1524    static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
1525        new CallerInfoAsyncQuery.OnQueryCompleteListener () {
1526            /**
1527             * When the query completes, we stash the resulting CallerInfo
1528             * object away in the Connection's "userData" (where it will
1529             * later be retrieved by the in-call UI.)
1530             */
1531            public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
1532                if (DBG) log("query complete, updating connection.userdata");
1533                Connection conn = (Connection) cookie;
1534
1535                // Added a check if CallerInfo is coming from ContactInfo or from Connection.
1536                // If no ContactInfo, then we want to use CNAP information coming from network
1537                if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
1538                if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
1539                    // If the number presentation has not been set by
1540                    // the ContactInfo, use the one from the
1541                    // connection.
1542
1543                    // TODO: Need a new util method to merge the info
1544                    // from the Connection in a CallerInfo object.
1545                    // Here 'ci' is a new CallerInfo instance read
1546                    // from the DB. It has lost all the connection
1547                    // info preset before the query (see PhoneUtils
1548                    // line 1334). We should have a method to merge
1549                    // back into this new instance the info from the
1550                    // connection object not set by the DB. If the
1551                    // Connection already has a CallerInfo instance in
1552                    // userData, then we could use this instance to
1553                    // fill 'ci' in. The same routine could be used in
1554                    // PhoneUtils.
1555                    if (0 == ci.numberPresentation) {
1556                        ci.numberPresentation = conn.getNumberPresentation();
1557                    }
1558                } else {
1559                    // No matching contact was found for this number.
1560                    // Return a new CallerInfo based solely on the CNAP
1561                    // information from the network.
1562
1563                    CallerInfo newCi = getCallerInfo(null, conn);
1564
1565                    // ...but copy over the (few) things we care about
1566                    // from the original CallerInfo object:
1567                    if (newCi != null) {
1568                        newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1569                        newCi.geoDescription = ci.geoDescription; // To get geo description string
1570                        ci = newCi;
1571                    }
1572                }
1573
1574                if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
1575                conn.setUserData(ci);
1576            }
1577        };
1578
1579
1580    /**
1581     * Returns a single "name" for the specified given a CallerInfo object.
1582     * If the name is null, return defaultString as the default value, usually
1583     * context.getString(R.string.unknown).
1584     */
1585    static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1586        if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1587
1588        String compactName = null;
1589        if (ci != null) {
1590            if (TextUtils.isEmpty(ci.name)) {
1591                // Perform any modifications for special CNAP cases to
1592                // the phone number being displayed, if applicable.
1593                compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
1594                                                        ci.numberPresentation);
1595            } else {
1596                // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
1597                compactName = ci.name;
1598            }
1599        }
1600
1601        if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1602            // If we're still null/empty here, then check if we have a presentation
1603            // string that takes precedence that we could return, otherwise display
1604            // "unknown" string.
1605            if (ci != null && ci.numberPresentation == Connection.PRESENTATION_RESTRICTED) {
1606                compactName = context.getString(R.string.private_num);
1607            } else if (ci != null && ci.numberPresentation == Connection.PRESENTATION_PAYPHONE) {
1608                compactName = context.getString(R.string.payphone);
1609            } else {
1610                compactName = context.getString(R.string.unknown);
1611            }
1612        }
1613        if (DBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1614        return compactName;
1615    }
1616
1617    /**
1618     * Returns true if the specified Call is a "conference call", meaning
1619     * that it owns more than one Connection object.  This information is
1620     * used to trigger certain UI changes that appear when a conference
1621     * call is active (like displaying the label "Conference call", and
1622     * enabling the "Manage conference" UI.)
1623     *
1624     * Watch out: This method simply checks the number of Connections,
1625     * *not* their states.  So if a Call has (for example) one ACTIVE
1626     * connection and one DISCONNECTED connection, this method will return
1627     * true (which is unintuitive, since the Call isn't *really* a
1628     * conference call any more.)
1629     *
1630     * @return true if the specified call has more than one connection (in any state.)
1631     */
1632    static boolean isConferenceCall(Call call) {
1633        // CDMA phones don't have the same concept of "conference call" as
1634        // GSM phones do; there's no special "conference call" state of
1635        // the UI or a "manage conference" function.  (Instead, when
1636        // you're in a 3-way call, all we can do is display the "generic"
1637        // state of the UI.)  So as far as the in-call UI is concerned,
1638        // Conference corresponds to generic display.
1639        final PhoneApp app = PhoneApp.getInstance();
1640        int phoneType = call.getPhone().getPhoneType();
1641        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1642            CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState();
1643            if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL)
1644                    || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
1645                    && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) {
1646                return true;
1647            }
1648        } else {
1649            List<Connection> connections = call.getConnections();
1650            if (connections != null && connections.size() > 1) {
1651                return true;
1652            }
1653        }
1654        return false;
1655
1656        // TODO: We may still want to change the semantics of this method
1657        // to say that a given call is only really a conference call if
1658        // the number of ACTIVE connections, not the total number of
1659        // connections, is greater than one.  (See warning comment in the
1660        // javadoc above.)
1661        // Here's an implementation of that:
1662        //        if (connections == null) {
1663        //            return false;
1664        //        }
1665        //        int numActiveConnections = 0;
1666        //        for (Connection conn : connections) {
1667        //            if (DBG) log("  - CONN: " + conn + ", state = " + conn.getState());
1668        //            if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
1669        //            if (numActiveConnections > 1) {
1670        //                return true;
1671        //            }
1672        //        }
1673        //        return false;
1674    }
1675
1676    /**
1677     * Launch the Dialer to start a new call.
1678     * This is just a wrapper around the ACTION_DIAL intent.
1679     */
1680    static void startNewCall(final CallManager cm) {
1681        final PhoneApp app = PhoneApp.getInstance();
1682
1683        // Sanity-check that this is OK given the current state of the phone.
1684        if (!okToAddCall(cm)) {
1685            Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
1686            dumpCallManager();
1687            return;
1688        }
1689
1690        // if applicable, mute the call while we're showing the add call UI.
1691        if (cm.hasActiveFgCall()) {
1692            setMuteInternal(cm.getActiveFgCall().getPhone(), true);
1693            // Inform the phone app that this mute state was NOT done
1694            // voluntarily by the User.
1695            app.setRestoreMuteOnInCallResume(true);
1696        }
1697
1698        Intent intent = new Intent(Intent.ACTION_DIAL);
1699        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1700
1701        // when we request the dialer come up, we also want to inform
1702        // it that we're going through the "add call" option from the
1703        // InCallScreen / PhoneUtils.
1704        intent.putExtra(ADD_CALL_MODE_KEY, true);
1705
1706        app.startActivity(intent);
1707    }
1708
1709    static void turnOnSpeaker(Context context, boolean flag, boolean store) {
1710        if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")...");
1711        final PhoneApp app = PhoneApp.getInstance();
1712
1713        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1714        audioManager.setSpeakerphoneOn(flag);
1715
1716        // record the speaker-enable value
1717        if (store) {
1718            sIsSpeakerEnabled = flag;
1719        }
1720
1721        // Update the status bar icon
1722        app.notificationMgr.updateSpeakerNotification(flag);
1723
1724        // We also need to make a fresh call to PhoneApp.updateWakeState()
1725        // any time the speaker state changes, since the screen timeout is
1726        // sometimes different depending on whether or not the speaker is
1727        // in use.
1728        app.updateWakeState();
1729
1730        // Update the Proximity sensor based on speaker state
1731        app.updateProximitySensorMode(app.mCM.getState());
1732
1733        app.mCM.setEchoSuppressionEnabled(flag);
1734    }
1735
1736    /**
1737     * Restore the speaker mode, called after a wired headset disconnect
1738     * event.
1739     */
1740    static void restoreSpeakerMode(Context context) {
1741        if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
1742
1743        // change the mode if needed.
1744        if (isSpeakerOn(context) != sIsSpeakerEnabled) {
1745            turnOnSpeaker(context, sIsSpeakerEnabled, false);
1746        }
1747    }
1748
1749    static boolean isSpeakerOn(Context context) {
1750        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1751        return audioManager.isSpeakerphoneOn();
1752    }
1753
1754
1755    static void turnOnNoiseSuppression(Context context, boolean flag, boolean store) {
1756        if (DBG) log("turnOnNoiseSuppression: " + flag);
1757        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1758
1759        if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
1760            return;
1761        }
1762
1763        if (flag) {
1764            audioManager.setParameters("noise_suppression=auto");
1765        } else {
1766            audioManager.setParameters("noise_suppression=off");
1767        }
1768
1769        // record the speaker-enable value
1770        if (store) {
1771            sIsNoiseSuppressionEnabled = flag;
1772        }
1773
1774        // TODO: implement and manage ICON
1775
1776    }
1777
1778    static void restoreNoiseSuppression(Context context) {
1779        if (DBG) log("restoreNoiseSuppression, restoring to: " + sIsNoiseSuppressionEnabled);
1780
1781        if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
1782            return;
1783        }
1784
1785        // change the mode if needed.
1786        if (isNoiseSuppressionOn(context) != sIsNoiseSuppressionEnabled) {
1787            turnOnNoiseSuppression(context, sIsNoiseSuppressionEnabled, false);
1788        }
1789    }
1790
1791    static boolean isNoiseSuppressionOn(Context context) {
1792
1793        if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
1794            return false;
1795        }
1796
1797        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1798        String noiseSuppression = audioManager.getParameters("noise_suppression");
1799        if (DBG) log("isNoiseSuppressionOn: " + noiseSuppression);
1800        if (noiseSuppression.contains("off")) {
1801            return false;
1802        } else {
1803            return true;
1804        }
1805    }
1806
1807    /**
1808     *
1809     * Mute / umute the foreground phone, which has the current foreground call
1810     *
1811     * All muting / unmuting from the in-call UI should go through this
1812     * wrapper.
1813     *
1814     * Wrapper around Phone.setMute() and setMicrophoneMute().
1815     * It also updates the connectionMuteTable and mute icon in the status bar.
1816     *
1817     */
1818    static void setMute(boolean muted) {
1819        CallManager cm = PhoneApp.getInstance().mCM;
1820
1821        // make the call to mute the audio
1822        setMuteInternal(cm.getFgPhone(), muted);
1823
1824
1825        // update the foreground connections to match.  This includes
1826        // all the connections on conference calls.
1827        for (Connection cn : cm.getActiveFgCall().getConnections()) {
1828            if (sConnectionMuteTable.get(cn) == null) {
1829                if (DBG) log("problem retrieving mute value for this connection.");
1830            }
1831            sConnectionMuteTable.put(cn, Boolean.valueOf(muted));
1832        }
1833    }
1834
1835    /**
1836     * Internally used muting function.
1837     */
1838    private static void setMuteInternal(Phone phone, boolean muted) {
1839        if (DBG) log("setMuteInternal: " + muted);
1840        final PhoneApp app = PhoneApp.getInstance();
1841        Context context = phone.getContext();
1842        boolean routeToAudioManager =
1843            context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager);
1844        if (routeToAudioManager) {
1845            AudioManager audioManager =
1846                (AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE);
1847            if (DBG) log("setMicrophoneMute: " + muted);
1848            audioManager.setMicrophoneMute(muted);
1849        } else {
1850            phone.setMute(muted);
1851        }
1852        app.notificationMgr.updateMuteNotification();
1853    }
1854
1855    /**
1856     * Get the mute state of foreground phone, which has the current
1857     * foreground call
1858     */
1859    static boolean getMute() {
1860        final PhoneApp app = PhoneApp.getInstance();
1861
1862        boolean routeToAudioManager =
1863            app.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager);
1864        if (routeToAudioManager) {
1865            AudioManager audioManager =
1866                (AudioManager) app.getSystemService(Context.AUDIO_SERVICE);
1867            return audioManager.isMicrophoneMute();
1868        } else {
1869            return app.mCM.getMute();
1870        }
1871    }
1872
1873    /* package */ static void setAudioMode() {
1874        setAudioMode(PhoneApp.getInstance().mCM);
1875    }
1876
1877    /**
1878     * Sets the audio mode per current phone state.
1879     */
1880    /* package */ static void setAudioMode(CallManager cm) {
1881        if (DBG) Log.d(LOG_TAG, "setAudioMode()..." + cm.getState());
1882
1883        Context context = PhoneApp.getInstance();
1884        AudioManager audioManager = (AudioManager)
1885                context.getSystemService(Context.AUDIO_SERVICE);
1886        int modeBefore = audioManager.getMode();
1887        cm.setAudioMode();
1888        int modeAfter = audioManager.getMode();
1889
1890        if (modeBefore != modeAfter) {
1891            // Enable stack dump only when actively debugging ("new Throwable()" is expensive!)
1892            if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump"));
1893        } else {
1894            if (DBG) Log.d(LOG_TAG, "setAudioMode() no change: "
1895                    + audioModeToString(modeBefore));
1896        }
1897    }
1898    private static String audioModeToString(int mode) {
1899        switch (mode) {
1900            case AudioManager.MODE_INVALID: return "MODE_INVALID";
1901            case AudioManager.MODE_CURRENT: return "MODE_CURRENT";
1902            case AudioManager.MODE_NORMAL: return "MODE_NORMAL";
1903            case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE";
1904            case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL";
1905            default: return String.valueOf(mode);
1906        }
1907    }
1908
1909    /**
1910     * Handles the wired headset button while in-call.
1911     *
1912     * This is called from the PhoneApp, not from the InCallScreen,
1913     * since the HEADSETHOOK button means "mute or unmute the current
1914     * call" *any* time a call is active, even if the user isn't actually
1915     * on the in-call screen.
1916     *
1917     * @return true if we consumed the event.
1918     */
1919    /* package */ static boolean handleHeadsetHook(Phone phone, KeyEvent event) {
1920        if (DBG) log("handleHeadsetHook()..." + event.getAction() + " " + event.getRepeatCount());
1921        final PhoneApp app = PhoneApp.getInstance();
1922
1923        // If the phone is totally idle, we ignore HEADSETHOOK events
1924        // (and instead let them fall through to the media player.)
1925        if (phone.getState() == Phone.State.IDLE) {
1926            return false;
1927        }
1928
1929        // Ok, the phone is in use.
1930        // The headset button button means "Answer" if an incoming call is
1931        // ringing.  If not, it toggles the mute / unmute state.
1932        //
1933        // And in any case we *always* consume this event; this means
1934        // that the usual mediaplayer-related behavior of the headset
1935        // button will NEVER happen while the user is on a call.
1936
1937        final boolean hasRingingCall = !phone.getRingingCall().isIdle();
1938        final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
1939        final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
1940
1941        if (hasRingingCall &&
1942            event.getRepeatCount() == 0 &&
1943            event.getAction() == KeyEvent.ACTION_UP) {
1944            // If an incoming call is ringing, answer it (just like with the
1945            // CALL button):
1946            int phoneType = phone.getPhoneType();
1947            if (phoneType == Phone.PHONE_TYPE_CDMA) {
1948                answerCall(phone.getRingingCall());
1949            } else if ((phoneType == Phone.PHONE_TYPE_GSM)
1950                    || (phoneType == Phone.PHONE_TYPE_SIP)) {
1951                if (hasActiveCall && hasHoldingCall) {
1952                    if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!");
1953                    answerAndEndActive(app.mCM, phone.getRingingCall());
1954                } else {
1955                    if (DBG) log("handleHeadsetHook: ringing ==> answer!");
1956                    // answerCall() will automatically hold the current
1957                    // active call, if there is one.
1958                    answerCall(phone.getRingingCall());
1959                }
1960            } else {
1961                throw new IllegalStateException("Unexpected phone type: " + phoneType);
1962            }
1963        } else {
1964            // No incoming ringing call.
1965            if (event.isLongPress()) {
1966                if (DBG) log("handleHeadsetHook: longpress -> hangup");
1967                hangup(app.mCM);
1968            }
1969            else if (event.getAction() == KeyEvent.ACTION_UP &&
1970                     event.getRepeatCount() == 0) {
1971                Connection c = phone.getForegroundCall().getLatestConnection();
1972                // If it is NOT an emg #, toggle the mute state. Otherwise, ignore the hook.
1973                if (c != null && !PhoneNumberUtils.isLocalEmergencyNumber(c.getAddress(),
1974                                                                          PhoneApp.getInstance())) {
1975                    if (getMute()) {
1976                        if (DBG) log("handleHeadsetHook: UNmuting...");
1977                        setMute(false);
1978                    } else {
1979                        if (DBG) log("handleHeadsetHook: muting...");
1980                        setMute(true);
1981                    }
1982                }
1983            }
1984        }
1985
1986        // Even if the InCallScreen is the current activity, there's no
1987        // need to force it to update, because (1) if we answered a
1988        // ringing call, the InCallScreen will imminently get a phone
1989        // state change event (causing an update), and (2) if we muted or
1990        // unmuted, the setMute() call automagically updates the status
1991        // bar, and there's no "mute" indication in the InCallScreen
1992        // itself (other than the menu item, which only ever stays
1993        // onscreen for a second anyway.)
1994        // TODO: (2) isn't entirely true anymore. Once we return our result
1995        // to the PhoneApp, we ask InCallScreen to update its control widgets
1996        // in case we changed mute or speaker state and phones with touch-
1997        // screen [toggle] buttons need to update themselves.
1998
1999        return true;
2000    }
2001
2002    /**
2003     * Look for ANY connections on the phone that qualify as being
2004     * disconnected.
2005     *
2006     * @return true if we find a connection that is disconnected over
2007     * all the phone's call objects.
2008     */
2009    /* package */ static boolean hasDisconnectedConnections(Phone phone) {
2010        return hasDisconnectedConnections(phone.getForegroundCall()) ||
2011                hasDisconnectedConnections(phone.getBackgroundCall()) ||
2012                hasDisconnectedConnections(phone.getRingingCall());
2013    }
2014
2015    /**
2016     * Iterate over all connections in a call to see if there are any
2017     * that are not alive (disconnected or idle).
2018     *
2019     * @return true if we find a connection that is disconnected, and
2020     * pending removal via
2021     * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}.
2022     */
2023    private static final boolean hasDisconnectedConnections(Call call) {
2024        // look through all connections for non-active ones.
2025        for (Connection c : call.getConnections()) {
2026            if (!c.isAlive()) {
2027                return true;
2028            }
2029        }
2030        return false;
2031    }
2032
2033    //
2034    // Misc UI policy helper functions
2035    //
2036
2037    /**
2038     * @return true if we're allowed to swap calls, given the current
2039     * state of the Phone.
2040     */
2041    /* package */ static boolean okToSwapCalls(CallManager cm) {
2042        int phoneType = cm.getDefaultPhone().getPhoneType();
2043        if (phoneType == Phone.PHONE_TYPE_CDMA) {
2044            // CDMA: "Swap" is enabled only when the phone reaches a *generic*.
2045            // state by either accepting a Call Waiting or by merging two calls
2046            PhoneApp app = PhoneApp.getInstance();
2047            return (app.cdmaPhoneCallState.getCurrentCallState()
2048                    == CdmaPhoneCallState.PhoneCallState.CONF_CALL);
2049        } else if ((phoneType == Phone.PHONE_TYPE_GSM)
2050                || (phoneType == Phone.PHONE_TYPE_SIP)) {
2051            // GSM: "Swap" is available if both lines are in use and there's no
2052            // incoming call.  (Actually we need to verify that the active
2053            // call really is in the ACTIVE state and the holding call really
2054            // is in the HOLDING state, since you *can't* actually swap calls
2055            // when the foreground call is DIALING or ALERTING.)
2056            return !cm.hasActiveRingingCall()
2057                    && (cm.getActiveFgCall().getState() == Call.State.ACTIVE)
2058                    && (cm.getFirstActiveBgCall().getState() == Call.State.HOLDING);
2059        } else {
2060            throw new IllegalStateException("Unexpected phone type: " + phoneType);
2061        }
2062    }
2063
2064    /**
2065     * @return true if we're allowed to merge calls, given the current
2066     * state of the Phone.
2067     */
2068    /* package */ static boolean okToMergeCalls(CallManager cm) {
2069        int phoneType = cm.getFgPhone().getPhoneType();
2070        if (phoneType == Phone.PHONE_TYPE_CDMA) {
2071            // CDMA: "Merge" is enabled only when the user is in a 3Way call.
2072            PhoneApp app = PhoneApp.getInstance();
2073            return ((app.cdmaPhoneCallState.getCurrentCallState()
2074                    == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
2075                    && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing());
2076        } else {
2077            // GSM: "Merge" is available if both lines are in use and there's no
2078            // incoming call, *and* the current conference isn't already
2079            // "full".
2080            // TODO: shall move all okToMerge logic to CallManager
2081            return !cm.hasActiveRingingCall() && cm.hasActiveFgCall()
2082                    && cm.hasActiveBgCall()
2083                    && cm.canConference(cm.getFirstActiveBgCall());
2084        }
2085    }
2086
2087    /**
2088     * @return true if the UI should let you add a new call, given the current
2089     * state of the Phone.
2090     */
2091    /* package */ static boolean okToAddCall(CallManager cm) {
2092        Phone phone = cm.getActiveFgCall().getPhone();
2093
2094        // "Add call" is never allowed in emergency callback mode (ECM).
2095        if (isPhoneInEcm(phone)) {
2096            return false;
2097        }
2098
2099        int phoneType = phone.getPhoneType();
2100        final Call.State fgCallState = cm.getActiveFgCall().getState();
2101        if (phoneType == Phone.PHONE_TYPE_CDMA) {
2102           // CDMA: "Add call" button is only enabled when:
2103           // - ForegroundCall is in ACTIVE state
2104           // - After 30 seconds of user Ignoring/Missing a Call Waiting call.
2105            PhoneApp app = PhoneApp.getInstance();
2106            return ((fgCallState == Call.State.ACTIVE)
2107                    && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting()));
2108        } else if ((phoneType == Phone.PHONE_TYPE_GSM)
2109                || (phoneType == Phone.PHONE_TYPE_SIP)) {
2110            // GSM: "Add call" is available only if ALL of the following are true:
2111            // - There's no incoming ringing call
2112            // - There's < 2 lines in use
2113            // - The foreground call is ACTIVE or IDLE or DISCONNECTED.
2114            //   (We mainly need to make sure it *isn't* DIALING or ALERTING.)
2115            final boolean hasRingingCall = cm.hasActiveRingingCall();
2116            final boolean hasActiveCall = cm.hasActiveFgCall();
2117            final boolean hasHoldingCall = cm.hasActiveBgCall();
2118            final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2119
2120            return !hasRingingCall
2121                    && !allLinesTaken
2122                    && ((fgCallState == Call.State.ACTIVE)
2123                        || (fgCallState == Call.State.IDLE)
2124                        || (fgCallState == Call.State.DISCONNECTED));
2125        } else {
2126            throw new IllegalStateException("Unexpected phone type: " + phoneType);
2127        }
2128    }
2129
2130    /**
2131     * Based on the input CNAP number string,
2132     * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
2133     * Otherwise, return CNAP_SPECIAL_CASE_NO.
2134     */
2135    private static int checkCnapSpecialCases(String n) {
2136        if (n.equals("PRIVATE") ||
2137                n.equals("P") ||
2138                n.equals("RES")) {
2139            if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
2140            return Connection.PRESENTATION_RESTRICTED;
2141        } else if (n.equals("UNAVAILABLE") ||
2142                n.equals("UNKNOWN") ||
2143                n.equals("UNA") ||
2144                n.equals("U")) {
2145            if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
2146            return Connection.PRESENTATION_UNKNOWN;
2147        } else {
2148            if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
2149            return CNAP_SPECIAL_CASE_NO;
2150        }
2151    }
2152
2153    /**
2154     * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
2155     * from the network to indicate different number presentations, convert them to
2156     * expected number and presentation values within the CallerInfo object.
2157     * @param number number we use to verify if we are in a corner case
2158     * @param presentation presentation value used to verify if we are in a corner case
2159     * @return the new String that should be used for the phone number
2160     */
2161    /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
2162            String number, int presentation) {
2163        // Obviously we return number if ci == null, but still return number if
2164        // number == null, because in these cases the correct string will still be
2165        // displayed/logged after this function returns based on the presentation value.
2166        if (ci == null || number == null) return number;
2167
2168        if (DBG) log("modifyForSpecialCnapCases: initially, number=" + number
2169                + ", presentation=" + presentation + " ci " + ci);
2170
2171        // "ABSENT NUMBER" is a possible value we could get from the network as the
2172        // phone number, so if this happens, change it to "Unknown" in the CallerInfo
2173        // and fix the presentation to be the same.
2174        if (number.equals(context.getString(R.string.absent_num))
2175                && presentation == Connection.PRESENTATION_ALLOWED) {
2176            number = context.getString(R.string.unknown);
2177            ci.numberPresentation = Connection.PRESENTATION_UNKNOWN;
2178        }
2179
2180        // Check for other special "corner cases" for CNAP and fix them similarly. Corner
2181        // cases only apply if we received an allowed presentation from the network, so check
2182        // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
2183        // match the presentation passed in for verification (meaning we changed it previously
2184        // because it's a corner case and we're being called from a different entry point).
2185        if (ci.numberPresentation == Connection.PRESENTATION_ALLOWED
2186                || (ci.numberPresentation != presentation
2187                        && presentation == Connection.PRESENTATION_ALLOWED)) {
2188            int cnapSpecialCase = checkCnapSpecialCases(number);
2189            if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
2190                // For all special strings, change number & numberPresentation.
2191                if (cnapSpecialCase == Connection.PRESENTATION_RESTRICTED) {
2192                    number = context.getString(R.string.private_num);
2193                } else if (cnapSpecialCase == Connection.PRESENTATION_UNKNOWN) {
2194                    number = context.getString(R.string.unknown);
2195                }
2196                if (DBG) log("SpecialCnap: number=" + number
2197                        + "; presentation now=" + cnapSpecialCase);
2198                ci.numberPresentation = cnapSpecialCase;
2199            }
2200        }
2201        if (DBG) log("modifyForSpecialCnapCases: returning number string=" + number);
2202        return number;
2203    }
2204
2205    //
2206    // Support for 3rd party phone service providers.
2207    //
2208
2209    /**
2210     * Check if all the provider's info is present in the intent.
2211     * @param intent Expected to have the provider's extra.
2212     * @return true if the intent has all the extras to build the
2213     * in-call screen's provider info overlay.
2214     */
2215    /* package */ static boolean hasPhoneProviderExtras(Intent intent) {
2216        if (null == intent) {
2217            return false;
2218        }
2219        final String name = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
2220        final String gatewayUri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI);
2221
2222        return !TextUtils.isEmpty(name) && !TextUtils.isEmpty(gatewayUri);
2223    }
2224
2225    /**
2226     * Copy all the expected extras set when a 3rd party provider is
2227     * used from the source intent to the destination one.  Checks all
2228     * the required extras are present, if any is missing, none will
2229     * be copied.
2230     * @param src Intent which may contain the provider's extras.
2231     * @param dst Intent where a copy of the extras will be added if applicable.
2232     */
2233    /* package */ static void checkAndCopyPhoneProviderExtras(Intent src, Intent dst) {
2234        if (!hasPhoneProviderExtras(src)) {
2235            Log.d(LOG_TAG, "checkAndCopyPhoneProviderExtras: some or all extras are missing.");
2236            return;
2237        }
2238
2239        dst.putExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE,
2240                     src.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE));
2241        dst.putExtra(InCallScreen.EXTRA_GATEWAY_URI,
2242                     src.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI));
2243    }
2244
2245    /**
2246     * Get the provider's label from the intent.
2247     * @param context to lookup the provider's package name.
2248     * @param intent with an extra set to the provider's package name.
2249     * @return The provider's application label. null if an error
2250     * occurred during the lookup of the package name or the label.
2251     */
2252    /* package */ static CharSequence getProviderLabel(Context context, Intent intent) {
2253        String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
2254        PackageManager pm = context.getPackageManager();
2255
2256        try {
2257            ApplicationInfo info = pm.getApplicationInfo(packageName, 0);
2258
2259            return pm.getApplicationLabel(info);
2260        } catch (PackageManager.NameNotFoundException e) {
2261            return null;
2262        }
2263    }
2264
2265    /**
2266     * Get the provider's icon.
2267     * @param context to lookup the provider's icon.
2268     * @param intent with an extra set to the provider's package name.
2269     * @return The provider's application icon. null if an error occured during the icon lookup.
2270     */
2271    /* package */ static Drawable getProviderIcon(Context context, Intent intent) {
2272        String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
2273        PackageManager pm = context.getPackageManager();
2274
2275        try {
2276            return pm.getApplicationIcon(packageName);
2277        } catch (PackageManager.NameNotFoundException e) {
2278            return null;
2279        }
2280    }
2281
2282    /**
2283     * Return the gateway uri from the intent.
2284     * @param intent With the gateway uri extra.
2285     * @return The gateway URI or null if not found.
2286     */
2287    /* package */ static Uri getProviderGatewayUri(Intent intent) {
2288        String uri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI);
2289        return TextUtils.isEmpty(uri) ? null : Uri.parse(uri);
2290    }
2291
2292    /**
2293     * Return a formatted version of the uri's scheme specific
2294     * part. E.g for 'tel:12345678', return '1-234-5678'.
2295     * @param uri A 'tel:' URI with the gateway phone number.
2296     * @return the provider's address (from the gateway uri) formatted
2297     * for user display. null if uri was null or its scheme was not 'tel:'.
2298     */
2299    /* package */ static String formatProviderUri(Uri uri) {
2300        if (null != uri) {
2301            if (Constants.SCHEME_TEL.equals(uri.getScheme())) {
2302                return PhoneNumberUtils.formatNumber(uri.getSchemeSpecificPart());
2303            } else {
2304                return uri.toString();
2305            }
2306        }
2307        return null;
2308    }
2309
2310    /**
2311     * Check if a phone number can be route through a 3rd party
2312     * gateway. The number must be a global phone number in numerical
2313     * form (1-800-666-SEXY won't work).
2314     *
2315     * MMI codes and the like cannot be used as a dial number for the
2316     * gateway either.
2317     *
2318     * @param number To be dialed via a 3rd party gateway.
2319     * @return true If the number can be routed through the 3rd party network.
2320     */
2321    /* package */ static boolean isRoutableViaGateway(String number) {
2322        if (TextUtils.isEmpty(number)) {
2323            return false;
2324        }
2325        number = PhoneNumberUtils.stripSeparators(number);
2326        if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
2327            return false;
2328        }
2329        number = PhoneNumberUtils.extractNetworkPortion(number);
2330        return PhoneNumberUtils.isGlobalPhoneNumber(number);
2331    }
2332
2333   /**
2334    * This function is called when phone answers or places a call.
2335    * Check if the phone is in a car dock or desk dock.
2336    * If yes, turn on the speaker, when no wired or BT headsets are connected.
2337    * Otherwise do nothing.
2338    */
2339    private static void activateSpeakerIfDocked(Phone phone) {
2340        if (DBG) log("activateSpeakerIfDocked()...");
2341
2342        if (PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_DESK ||
2343                PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_CAR) {
2344            if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker.");
2345            PhoneApp app = PhoneApp.getInstance();
2346            BluetoothHandsfree bthf = app.getBluetoothHandsfree();
2347
2348            if (!app.isHeadsetPlugged() && !(bthf != null && bthf.isAudioOn())) {
2349                turnOnSpeaker(phone.getContext(), true, true);
2350            }
2351        }
2352    }
2353
2354
2355    /**
2356     * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
2357     */
2358    /* package */ static boolean isPhoneInEcm(Phone phone) {
2359        if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
2360            // For phones that support ECM, return true iff PROPERTY_INECM_MODE == "true".
2361            // TODO: There ought to be a better API for this than just
2362            // exposing a system property all the way up to the app layer,
2363            // probably a method like "inEcm()" provided by the telephony
2364            // layer.
2365            String ecmMode =
2366                    SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
2367            if (ecmMode != null) {
2368                return ecmMode.equals("true");
2369            }
2370        }
2371        return false;
2372    }
2373
2374    /**
2375     * Returns the most appropriate Phone object to handle a call
2376     * to the specified number.
2377     *
2378     * @param cm the CallManager.
2379     * @param scheme the scheme from the data URI that the number originally came from.
2380     * @param number the phone number, or SIP address.
2381     */
2382    public static Phone pickPhoneBasedOnNumber(CallManager cm,
2383            String scheme, String number, String primarySipUri) {
2384        if (DBG) log("pickPhoneBasedOnNumber: scheme " + scheme
2385                + ", number " + number + ", sipUri " + primarySipUri);
2386
2387        if (primarySipUri != null) {
2388            Phone phone = getSipPhoneFromUri(cm, primarySipUri);
2389            if (phone != null) return phone;
2390        }
2391        return cm.getDefaultPhone();
2392    }
2393
2394    public static Phone getSipPhoneFromUri(CallManager cm, String target) {
2395        for (Phone phone : cm.getAllPhones()) {
2396            if (phone.getPhoneType() == Phone.PHONE_TYPE_SIP) {
2397                String sipUri = ((SipPhone) phone).getSipUri();
2398                if (target.equals(sipUri)) {
2399                    if (DBG) log("- pickPhoneBasedOnNumber:" +
2400                            "found SipPhone! obj = " + phone + ", "
2401                            + phone.getClass());
2402                    return phone;
2403                }
2404            }
2405        }
2406        return null;
2407    }
2408
2409    public static boolean isRealIncomingCall(Call.State state) {
2410        return (state == Call.State.INCOMING && !PhoneApp.getInstance().mCM.hasActiveFgCall());
2411
2412    }
2413
2414    private static boolean sVoipSupported = false;
2415    static {
2416        PhoneApp app = PhoneApp.getInstance();
2417        sVoipSupported = SipManager.isVoipSupported(app)
2418                && app.getResources().getBoolean(com.android.internal.R.bool.config_built_in_sip_phone)
2419                && app.getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
2420    }
2421
2422    /**
2423     * @return true if this device supports voice calls using the built-in SIP stack.
2424     */
2425    static boolean isVoipSupported() {
2426        return sVoipSupported;
2427    }
2428
2429    //
2430    // General phone and call state debugging/testing code
2431    //
2432
2433    /* package */ static void dumpCallState(Phone phone) {
2434        PhoneApp app = PhoneApp.getInstance();
2435        Log.d(LOG_TAG, "dumpCallState():");
2436        Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
2437              + ", state = " + phone.getState());
2438
2439        StringBuilder b = new StringBuilder(128);
2440
2441        Call call = phone.getForegroundCall();
2442        b.setLength(0);
2443        b.append("  - FG call: ").append(call.getState());
2444        b.append(" isAlive ").append(call.getState().isAlive());
2445        b.append(" isRinging ").append(call.getState().isRinging());
2446        b.append(" isDialing ").append(call.getState().isDialing());
2447        b.append(" isIdle ").append(call.isIdle());
2448        b.append(" hasConnections ").append(call.hasConnections());
2449        Log.d(LOG_TAG, b.toString());
2450
2451        call = phone.getBackgroundCall();
2452        b.setLength(0);
2453        b.append("  - BG call: ").append(call.getState());
2454        b.append(" isAlive ").append(call.getState().isAlive());
2455        b.append(" isRinging ").append(call.getState().isRinging());
2456        b.append(" isDialing ").append(call.getState().isDialing());
2457        b.append(" isIdle ").append(call.isIdle());
2458        b.append(" hasConnections ").append(call.hasConnections());
2459        Log.d(LOG_TAG, b.toString());
2460
2461        call = phone.getRingingCall();
2462        b.setLength(0);
2463        b.append("  - RINGING call: ").append(call.getState());
2464        b.append(" isAlive ").append(call.getState().isAlive());
2465        b.append(" isRinging ").append(call.getState().isRinging());
2466        b.append(" isDialing ").append(call.getState().isDialing());
2467        b.append(" isIdle ").append(call.isIdle());
2468        b.append(" hasConnections ").append(call.hasConnections());
2469        Log.d(LOG_TAG, b.toString());
2470
2471
2472        final boolean hasRingingCall = !phone.getRingingCall().isIdle();
2473        final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
2474        final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
2475        final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2476        b.setLength(0);
2477        b.append("  - hasRingingCall ").append(hasRingingCall);
2478        b.append(" hasActiveCall ").append(hasActiveCall);
2479        b.append(" hasHoldingCall ").append(hasHoldingCall);
2480        b.append(" allLinesTaken ").append(allLinesTaken);
2481        Log.d(LOG_TAG, b.toString());
2482
2483        // On CDMA phones, dump out the CdmaPhoneCallState too:
2484        if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) {
2485            if (app.cdmaPhoneCallState != null) {
2486                Log.d(LOG_TAG, "  - CDMA call state: "
2487                      + app.cdmaPhoneCallState.getCurrentCallState());
2488            } else {
2489                Log.d(LOG_TAG, "  - CDMA device, but null cdmaPhoneCallState!");
2490            }
2491        }
2492
2493        // Watch out: the isRinging() call below does NOT tell us anything
2494        // about the state of the telephony layer; it merely tells us whether
2495        // the Ringer manager is currently playing the ringtone.
2496        boolean ringing = app.getRinger().isRinging();
2497        Log.d(LOG_TAG, "  - Ringer state: " + ringing);
2498    }
2499
2500    private static void log(String msg) {
2501        Log.d(LOG_TAG, msg);
2502    }
2503
2504    static void dumpCallManager() {
2505        Call call;
2506        CallManager cm = PhoneApp.getInstance().mCM;
2507        StringBuilder b = new StringBuilder(128);
2508
2509
2510
2511        Log.d(LOG_TAG, "############### dumpCallManager() ##############");
2512        // TODO: Don't log "cm" itself, since CallManager.toString()
2513        // already spews out almost all this same information.
2514        // We should fix CallManager.toString() to be more minimal, and
2515        // use an explicit dumpState() method for the verbose dump.
2516        // Log.d(LOG_TAG, "CallManager: " + cm
2517        //         + ", state = " + cm.getState());
2518        Log.d(LOG_TAG, "CallManager: state = " + cm.getState());
2519        b.setLength(0);
2520        call = cm.getActiveFgCall();
2521        b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO ");
2522        b.append(call);
2523        b.append( "  State: ").append(cm.getActiveFgCallState());
2524        b.append( "  Conn: ").append(cm.getFgCallConnections());
2525        Log.d(LOG_TAG, b.toString());
2526        b.setLength(0);
2527        call = cm.getFirstActiveBgCall();
2528        b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO ");
2529        b.append(call);
2530        b.append( "  State: ").append(cm.getFirstActiveBgCall().getState());
2531        b.append( "  Conn: ").append(cm.getBgCallConnections());
2532        Log.d(LOG_TAG, b.toString());
2533        b.setLength(0);
2534        call = cm.getFirstActiveRingingCall();
2535        b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO ");
2536        b.append(call);
2537        b.append( "  State: ").append(cm.getFirstActiveRingingCall().getState());
2538        Log.d(LOG_TAG, b.toString());
2539
2540
2541
2542        for (Phone phone : CallManager.getInstance().getAllPhones()) {
2543            if (phone != null) {
2544                Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName()
2545                        + ", state = " + phone.getState());
2546                b.setLength(0);
2547                call = phone.getForegroundCall();
2548                b.append(" - FG call: ").append(call);
2549                b.append( "  State: ").append(call.getState());
2550                b.append( "  Conn: ").append(call.hasConnections());
2551                Log.d(LOG_TAG, b.toString());
2552                b.setLength(0);
2553                call = phone.getBackgroundCall();
2554                b.append(" - BG call: ").append(call);
2555                b.append( "  State: ").append(call.getState());
2556                b.append( "  Conn: ").append(call.hasConnections());
2557                Log.d(LOG_TAG, b.toString());b.setLength(0);
2558                call = phone.getRingingCall();
2559                b.append(" - RINGING call: ").append(call);
2560                b.append( "  State: ").append(call.getState());
2561                b.append( "  Conn: ").append(call.hasConnections());
2562                Log.d(LOG_TAG, b.toString());
2563            }
2564        }
2565
2566        Log.d(LOG_TAG, "############## END dumpCallManager() ###############");
2567    }
2568}
2569