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