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