ImsPhoneCallTracker.java revision d9aa1a75304b1c04c352198b9269f40a2a059f74
1/*
2 * Copyright (C) 2013 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.internal.telephony.imsphone;
18
19import java.io.FileDescriptor;
20import java.io.PrintWriter;
21import java.util.ArrayList;
22import java.util.List;
23
24import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.content.SharedPreferences;
30import android.os.AsyncResult;
31import android.os.Handler;
32import android.os.Message;
33import android.os.Registrant;
34import android.os.RegistrantList;
35import android.os.RemoteException;
36import android.os.SystemProperties;
37import android.provider.Settings;
38import android.preference.PreferenceManager;
39import android.telecom.ConferenceParticipant;
40import android.telecom.VideoProfile;
41import android.telephony.DisconnectCause;
42import android.telephony.PhoneNumberUtils;
43import android.telephony.Rlog;
44import android.telephony.ServiceState;
45
46import com.android.ims.ImsCall;
47import com.android.ims.ImsCallProfile;
48import com.android.ims.ImsConfig;
49import com.android.ims.ImsConnectionStateListener;
50import com.android.ims.ImsEcbm;
51import com.android.ims.ImsException;
52import com.android.ims.ImsManager;
53import com.android.ims.ImsReasonInfo;
54import com.android.ims.ImsServiceClass;
55import com.android.ims.ImsUtInterface;
56import com.android.ims.internal.IImsVideoCallProvider;
57import com.android.ims.internal.ImsVideoCallProviderWrapper;
58import com.android.internal.telephony.Call;
59import com.android.internal.telephony.CallStateException;
60import com.android.internal.telephony.CallTracker;
61import com.android.internal.telephony.CommandException;
62import com.android.internal.telephony.CommandsInterface;
63import com.android.internal.telephony.Connection;
64import com.android.internal.telephony.Phone;
65import com.android.internal.telephony.PhoneBase;
66import com.android.internal.telephony.PhoneConstants;
67import com.android.internal.telephony.TelephonyProperties;
68
69/**
70 * {@hide}
71 */
72public final class ImsPhoneCallTracker extends CallTracker {
73    static final String LOG_TAG = "ImsPhoneCallTracker";
74
75    private static final boolean DBG = true;
76
77    private boolean mIsVolteEnabled = false;
78    private boolean mIsVtEnabled = false;
79
80    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
81        @Override
82        public void onReceive(Context context, Intent intent) {
83            if (intent.getAction().equals(ImsManager.ACTION_IMS_INCOMING_CALL)) {
84                if (DBG) log("onReceive : incoming call intent");
85
86                if (mImsManager == null) return;
87
88                if (mServiceId < 0) return;
89
90                try {
91                    // Network initiated USSD will be treated by mImsUssdListener
92                    boolean isUssd = intent.getBooleanExtra(ImsManager.EXTRA_USSD, false);
93                    if (isUssd) {
94                        if (DBG) log("onReceive : USSD");
95                        mUssdSession = mImsManager.takeCall(mServiceId, intent, mImsUssdListener);
96                        if (mUssdSession != null) {
97                            mUssdSession.accept(ImsCallProfile.CALL_TYPE_VOICE);
98                        }
99                        return;
100                    }
101
102                    // Normal MT call
103                    ImsCall imsCall = mImsManager.takeCall(mServiceId, intent, mImsCallListener);
104                    ImsPhoneConnection conn = new ImsPhoneConnection(mPhone.getContext(), imsCall,
105                            ImsPhoneCallTracker.this, mRingingCall);
106                    addConnection(conn);
107
108                    IImsVideoCallProvider imsVideoCallProvider =
109                            imsCall.getCallSession().getVideoCallProvider();
110                    if (imsVideoCallProvider != null) {
111                        ImsVideoCallProviderWrapper imsVideoCallProviderWrapper =
112                                new ImsVideoCallProviderWrapper(imsVideoCallProvider);
113                        conn.setVideoProvider(imsVideoCallProviderWrapper);
114                    }
115
116                    if ((mForegroundCall.getState() != ImsPhoneCall.State.IDLE) ||
117                            (mBackgroundCall.getState() != ImsPhoneCall.State.IDLE)) {
118                        conn.update(imsCall, ImsPhoneCall.State.WAITING);
119                    }
120
121                    mPhone.notifyNewRingingConnection(conn);
122                    mPhone.notifyIncomingRing();
123
124                    updatePhoneState();
125                    mPhone.notifyPreciseCallStateChanged();
126                } catch (ImsException e) {
127                    loge("onReceive : exception " + e);
128                } catch (RemoteException e) {
129                }
130            }
131        }
132    };
133
134    //***** Constants
135
136    static final int MAX_CONNECTIONS = 7;
137    static final int MAX_CONNECTIONS_PER_CALL = 5;
138
139    private static final int EVENT_HANGUP_PENDINGMO = 18;
140    private static final int EVENT_RESUME_BACKGROUND = 19;
141    private static final int EVENT_DIAL_PENDINGMO = 20;
142
143    private static final int TIMEOUT_HANGUP_PENDINGMO = 500;
144
145    //***** Instance Variables
146    private ArrayList<ImsPhoneConnection> mConnections = new ArrayList<ImsPhoneConnection>();
147    private RegistrantList mVoiceCallEndedRegistrants = new RegistrantList();
148    private RegistrantList mVoiceCallStartedRegistrants = new RegistrantList();
149
150    ImsPhoneCall mRingingCall = new ImsPhoneCall(this);
151    ImsPhoneCall mForegroundCall = new ImsPhoneCall(this);
152    ImsPhoneCall mBackgroundCall = new ImsPhoneCall(this);
153    ImsPhoneCall mHandoverCall = new ImsPhoneCall(this);
154
155    private ImsPhoneConnection mPendingMO;
156    private int mClirMode = CommandsInterface.CLIR_DEFAULT;
157    private Object mSyncHold = new Object();
158
159    private ImsCall mUssdSession = null;
160    private Message mPendingUssd = null;
161
162    ImsPhone mPhone;
163
164    private boolean mDesiredMute = false;    // false = mute off
165    private boolean mOnHoldToneStarted = false;
166
167    PhoneConstants.State mState = PhoneConstants.State.IDLE;
168
169    private ImsManager mImsManager;
170    private int mServiceId = -1;
171
172    private Call.SrvccState mSrvccState = Call.SrvccState.NONE;
173
174    private boolean mIsInEmergencyCall = false;
175
176    private int pendingCallClirMode;
177    private int pendingCallVideoState;
178    private boolean pendingCallInEcm = false;
179    private boolean mSwitchingFgAndBgCalls = false;
180    private ImsCall mCallExpectedToResume = null;
181
182    //***** Events
183
184
185    //***** Constructors
186
187    ImsPhoneCallTracker(ImsPhone phone) {
188        this.mPhone = phone;
189
190        IntentFilter intentfilter = new IntentFilter();
191        intentfilter.addAction(ImsManager.ACTION_IMS_INCOMING_CALL);
192        mPhone.getContext().registerReceiver(mReceiver, intentfilter);
193
194        Thread t = new Thread() {
195            public void run() {
196                getImsService();
197            }
198        };
199        t.start();
200    }
201
202    private PendingIntent createIncomingCallPendingIntent() {
203        Intent intent = new Intent(ImsManager.ACTION_IMS_INCOMING_CALL);
204        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
205        return PendingIntent.getBroadcast(mPhone.getContext(), 0, intent,
206                PendingIntent.FLAG_UPDATE_CURRENT);
207    }
208
209    private void getImsService() {
210        if (DBG) log("getImsService");
211        mImsManager = ImsManager.getInstance(mPhone.getContext(), mPhone.getPhoneId());
212        try {
213            mServiceId = mImsManager.open(ImsServiceClass.MMTEL,
214                    createIncomingCallPendingIntent(),
215                    mImsConnectionStateListener);
216
217            // Get the ECBM interface and set IMSPhone's listener object for notifications
218            getEcbmInterface().setEcbmStateListener(mPhone.mImsEcbmStateListener);
219            if (mPhone.isInEcm()) {
220                // Call exit ECBM which will invoke onECBMExited
221                mPhone.exitEmergencyCallbackMode();
222            }
223            int mPreferredTtyMode = Settings.Secure.getInt(
224                mPhone.getContext().getContentResolver(),
225                Settings.Secure.PREFERRED_TTY_MODE,
226                Phone.TTY_MODE_OFF);
227           mImsManager.setUiTTYMode(mServiceId, mPreferredTtyMode, null);
228
229        } catch (ImsException e) {
230            loge("getImsService: " + e);
231            //Leave mImsManager as null, then CallStateException will be thrown when dialing
232            mImsManager = null;
233        }
234    }
235
236    public void dispose() {
237        if (DBG) log("dispose");
238        mRingingCall.dispose();
239        mBackgroundCall.dispose();
240        mForegroundCall.dispose();
241        mHandoverCall.dispose();
242
243        clearDisconnected();
244        mPhone.getContext().unregisterReceiver(mReceiver);
245    }
246
247    @Override
248    protected void finalize() {
249        log("ImsPhoneCallTracker finalized");
250    }
251
252    //***** Instance Methods
253
254    //***** Public Methods
255    @Override
256    public void registerForVoiceCallStarted(Handler h, int what, Object obj) {
257        Registrant r = new Registrant(h, what, obj);
258        mVoiceCallStartedRegistrants.add(r);
259    }
260
261    @Override
262    public void unregisterForVoiceCallStarted(Handler h) {
263        mVoiceCallStartedRegistrants.remove(h);
264    }
265
266    @Override
267    public void registerForVoiceCallEnded(Handler h, int what, Object obj) {
268        Registrant r = new Registrant(h, what, obj);
269        mVoiceCallEndedRegistrants.add(r);
270    }
271
272    @Override
273    public void unregisterForVoiceCallEnded(Handler h) {
274        mVoiceCallEndedRegistrants.remove(h);
275    }
276
277    Connection
278    dial(String dialString, int videoState) throws CallStateException {
279        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mPhone.getContext());
280        int oirMode = sp.getInt(PhoneBase.CLIR_KEY, CommandsInterface.CLIR_DEFAULT);
281        return dial(dialString, oirMode, videoState);
282    }
283
284    /**
285     * oirMode is one of the CLIR_ constants
286     */
287    synchronized Connection
288    dial(String dialString, int clirMode, int videoState) throws CallStateException {
289        boolean isPhoneInEcmMode = SystemProperties.getBoolean(
290                TelephonyProperties.PROPERTY_INECM_MODE, false);
291        boolean isEmergencyNumber = PhoneNumberUtils.isEmergencyNumber(dialString);
292
293        if (DBG) log("dial clirMode=" + clirMode);
294
295        // note that this triggers call state changed notif
296        clearDisconnected();
297
298        if (mImsManager == null) {
299            throw new CallStateException("service not available");
300        }
301
302        if (!canDial()) {
303            throw new CallStateException("cannot dial in current state");
304        }
305
306        if (isPhoneInEcmMode && isEmergencyNumber) {
307            handleEcmTimer(ImsPhone.CANCEL_ECM_TIMER);
308        }
309
310        boolean holdBeforeDial = false;
311
312        // The new call must be assigned to the foreground call.
313        // That call must be idle, so place anything that's
314        // there on hold
315        if (mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE) {
316            if (mBackgroundCall.getState() != ImsPhoneCall.State.IDLE) {
317                //we should have failed in !canDial() above before we get here
318                throw new CallStateException("cannot dial in current state");
319            }
320            // foreground call is empty for the newly dialed connection
321            holdBeforeDial = true;
322            switchWaitingOrHoldingAndActive();
323        }
324
325        ImsPhoneCall.State fgState = ImsPhoneCall.State.IDLE;
326        ImsPhoneCall.State bgState = ImsPhoneCall.State.IDLE;
327
328        mClirMode = clirMode;
329
330        synchronized (mSyncHold) {
331            if (holdBeforeDial) {
332                fgState = mForegroundCall.getState();
333                bgState = mBackgroundCall.getState();
334
335                //holding foreground call failed
336                if (fgState == ImsPhoneCall.State.ACTIVE) {
337                    throw new CallStateException("cannot dial in current state");
338                }
339
340                //holding foreground call succeeded
341                if (bgState == ImsPhoneCall.State.HOLDING) {
342                    holdBeforeDial = false;
343                }
344            }
345
346            mPendingMO = new ImsPhoneConnection(mPhone.getContext(),
347                    checkForTestEmergencyNumber(dialString), this, mForegroundCall);
348        }
349        addConnection(mPendingMO);
350
351        if (!holdBeforeDial) {
352            if ((!isPhoneInEcmMode) || (isPhoneInEcmMode && isEmergencyNumber)) {
353                dialInternal(mPendingMO, clirMode, videoState);
354            } else {
355                try {
356                    getEcbmInterface().exitEmergencyCallbackMode();
357                } catch (ImsException e) {
358                    e.printStackTrace();
359                    throw new CallStateException("service not available");
360                }
361                mPhone.setOnEcbModeExitResponse(this, EVENT_EXIT_ECM_RESPONSE_CDMA, null);
362                pendingCallClirMode = clirMode;
363                pendingCallVideoState = videoState;
364                pendingCallInEcm = true;
365            }
366        }
367
368        updatePhoneState();
369        mPhone.notifyPreciseCallStateChanged();
370
371        return mPendingMO;
372    }
373
374    private void handleEcmTimer(int action) {
375        mPhone.handleTimerInEmergencyCallbackMode(action);
376        switch (action) {
377            case ImsPhone.CANCEL_ECM_TIMER:
378                break;
379            case ImsPhone.RESTART_ECM_TIMER:
380                break;
381            default:
382                log("handleEcmTimer, unsupported action " + action);
383        }
384    }
385
386    private void dialInternal(ImsPhoneConnection conn, int clirMode, int videoState) {
387        if (conn == null) {
388            return;
389        }
390
391        if (conn.getAddress()== null || conn.getAddress().length() == 0
392                || conn.getAddress().indexOf(PhoneNumberUtils.WILD) >= 0) {
393            // Phone number is invalid
394            conn.setDisconnectCause(DisconnectCause.INVALID_NUMBER);
395            sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
396            return;
397        }
398
399        // Always unmute when initiating a new call
400        setMute(false);
401        int serviceType = PhoneNumberUtils.isEmergencyNumber(conn.getAddress()) ?
402                ImsCallProfile.SERVICE_TYPE_EMERGENCY : ImsCallProfile.SERVICE_TYPE_NORMAL;
403        int callType = ImsCallProfile.getCallTypeFromVideoState(videoState);
404        //TODO(vt): Is this sufficient?  At what point do we know the video state of the call?
405        conn.setVideoState(videoState);
406
407        try {
408            String[] callees = new String[] { conn.getAddress() };
409            ImsCallProfile profile = mImsManager.createCallProfile(mServiceId,
410                    serviceType, callType);
411            profile.setCallExtraInt(ImsCallProfile.EXTRA_OIR, clirMode);
412
413            ImsCall imsCall = mImsManager.makeCall(mServiceId, profile,
414                    callees, mImsCallListener);
415            conn.setImsCall(imsCall);
416
417            IImsVideoCallProvider imsVideoCallProvider =
418                    imsCall.getCallSession().getVideoCallProvider();
419            if (imsVideoCallProvider != null) {
420                ImsVideoCallProviderWrapper imsVideoCallProviderWrapper =
421                        new ImsVideoCallProviderWrapper(imsVideoCallProvider);
422                conn.setVideoProvider(imsVideoCallProviderWrapper);
423            }
424        } catch (ImsException e) {
425            loge("dialInternal : " + e);
426            conn.setDisconnectCause(DisconnectCause.ERROR_UNSPECIFIED);
427            sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
428        } catch (RemoteException e) {
429        }
430    }
431
432    /**
433     * Accepts a call with the specified video state.  The video state is the video state that the
434     * user has agreed upon in the InCall UI.
435     *
436     * @param videoState The video State
437     * @throws CallStateException
438     */
439    void acceptCall (int videoState) throws CallStateException {
440        if (DBG) log("acceptCall");
441
442        if (mForegroundCall.getState().isAlive()
443                && mBackgroundCall.getState().isAlive()) {
444            throw new CallStateException("cannot accept call");
445        }
446
447        if ((mRingingCall.getState() == ImsPhoneCall.State.WAITING)
448                && mForegroundCall.getState().isAlive()) {
449            setMute(false);
450            switchWaitingOrHoldingAndActive();
451        } else if (mRingingCall.getState().isRinging()) {
452            if (DBG) log("acceptCall: incoming...");
453            // Always unmute when answering a new call
454            setMute(false);
455            try {
456                ImsCall imsCall = mRingingCall.getImsCall();
457                if (imsCall != null) {
458                    imsCall.accept(ImsCallProfile.getCallTypeFromVideoState(videoState));
459                } else {
460                    throw new CallStateException("no valid ims call");
461                }
462            } catch (ImsException e) {
463                throw new CallStateException("cannot accept call");
464            }
465        } else {
466            throw new CallStateException("phone not ringing");
467        }
468    }
469
470    void
471    rejectCall () throws CallStateException {
472        if (DBG) log("rejectCall");
473
474        if (mRingingCall.getState().isRinging()) {
475            hangup(mRingingCall);
476        } else {
477            throw new CallStateException("phone not ringing");
478        }
479    }
480
481    void
482    switchWaitingOrHoldingAndActive() throws CallStateException {
483        if (DBG) log("switchWaitingOrHoldingAndActive");
484
485        if (mRingingCall.getState() == ImsPhoneCall.State.INCOMING) {
486            throw new CallStateException("cannot be in the incoming state");
487        }
488
489        if (mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE) {
490            ImsCall imsCall = mForegroundCall.getImsCall();
491            if (imsCall == null) {
492                throw new CallStateException("no ims call");
493            }
494
495            // Swap the ImsCalls pointed to by the foreground and background ImsPhoneCalls.
496            // If hold or resume later fails, we will swap them back.
497            mSwitchingFgAndBgCalls = true;
498            mCallExpectedToResume = mBackgroundCall.getImsCall();
499            mForegroundCall.switchWith(mBackgroundCall);
500
501            // Hold the foreground call; once the foreground call is held, the background call will
502            // be resumed.
503            try {
504                imsCall.hold();
505            } catch (ImsException e) {
506                mForegroundCall.switchWith(mBackgroundCall);
507                throw new CallStateException(e.getMessage());
508            }
509        } else if (mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING) {
510            resumeWaitingOrHolding();
511        }
512    }
513
514    void
515    conference() {
516        if (DBG) log("conference");
517
518        ImsCall fgImsCall = mForegroundCall.getImsCall();
519        if (fgImsCall == null) {
520            log("conference no foreground ims call");
521            return;
522        }
523
524        ImsCall bgImsCall = mBackgroundCall.getImsCall();
525        if (bgImsCall == null) {
526            log("conference no background ims call");
527            return;
528        }
529
530        try {
531            fgImsCall.merge(bgImsCall);
532        } catch (ImsException e) {
533            log("conference " + e.getMessage());
534        }
535    }
536
537    void
538    explicitCallTransfer() {
539        //TODO : implement
540    }
541
542    void
543    clearDisconnected() {
544        if (DBG) log("clearDisconnected");
545
546        internalClearDisconnected();
547
548        updatePhoneState();
549        mPhone.notifyPreciseCallStateChanged();
550    }
551
552    boolean
553    canConference() {
554        return mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE
555            && mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING
556            && !mBackgroundCall.isFull()
557            && !mForegroundCall.isFull();
558    }
559
560    boolean
561    canDial() {
562        boolean ret;
563        int serviceState = mPhone.getServiceState().getState();
564        String disableCall = SystemProperties.get(
565                TelephonyProperties.PROPERTY_DISABLE_CALL, "false");
566
567        ret = (serviceState != ServiceState.STATE_POWER_OFF)
568            && mPendingMO == null
569            && !mRingingCall.isRinging()
570            && !disableCall.equals("true")
571            && (!mForegroundCall.getState().isAlive()
572                    || !mBackgroundCall.getState().isAlive());
573
574        return ret;
575    }
576
577    boolean
578    canTransfer() {
579        return mForegroundCall.getState() == ImsPhoneCall.State.ACTIVE
580            && mBackgroundCall.getState() == ImsPhoneCall.State.HOLDING;
581    }
582
583    //***** Private Instance Methods
584
585    private void
586    internalClearDisconnected() {
587        mRingingCall.clearDisconnected();
588        mForegroundCall.clearDisconnected();
589        mBackgroundCall.clearDisconnected();
590        mHandoverCall.clearDisconnected();
591    }
592
593    private void
594    updatePhoneState() {
595        PhoneConstants.State oldState = mState;
596
597        if (mRingingCall.isRinging()) {
598            mState = PhoneConstants.State.RINGING;
599        } else if (mPendingMO != null ||
600                !(mForegroundCall.isIdle() && mBackgroundCall.isIdle())) {
601            mState = PhoneConstants.State.OFFHOOK;
602        } else {
603            mState = PhoneConstants.State.IDLE;
604        }
605
606        if (mState == PhoneConstants.State.IDLE && oldState != mState) {
607            mVoiceCallEndedRegistrants.notifyRegistrants(
608                    new AsyncResult(null, null, null));
609        } else if (oldState == PhoneConstants.State.IDLE && oldState != mState) {
610            mVoiceCallStartedRegistrants.notifyRegistrants (
611                    new AsyncResult(null, null, null));
612        }
613
614        if (DBG) log("updatePhoneState oldState=" + oldState + ", newState=" + mState);
615
616        if (mState != oldState) {
617            mPhone.notifyPhoneStateChanged();
618        }
619    }
620
621    private void
622    handleRadioNotAvailable() {
623        // handlePollCalls will clear out its
624        // call list when it gets the CommandException
625        // error result from this
626        pollCallsWhenSafe();
627    }
628
629    private void
630    dumpState() {
631        List l;
632
633        log("Phone State:" + mState);
634
635        log("Ringing call: " + mRingingCall.toString());
636
637        l = mRingingCall.getConnections();
638        for (int i = 0, s = l.size(); i < s; i++) {
639            log(l.get(i).toString());
640        }
641
642        log("Foreground call: " + mForegroundCall.toString());
643
644        l = mForegroundCall.getConnections();
645        for (int i = 0, s = l.size(); i < s; i++) {
646            log(l.get(i).toString());
647        }
648
649        log("Background call: " + mBackgroundCall.toString());
650
651        l = mBackgroundCall.getConnections();
652        for (int i = 0, s = l.size(); i < s; i++) {
653            log(l.get(i).toString());
654        }
655
656    }
657
658    //***** Called from ImsPhone
659
660    void setUiTTYMode(int uiTtyMode, Message onComplete) {
661        try {
662            mImsManager.setUiTTYMode(mServiceId, uiTtyMode, onComplete);
663        } catch (ImsException e) {
664            loge("setTTYMode : " + e);
665            mPhone.sendErrorResponse(onComplete, e);
666        }
667    }
668
669    /*package*/ void setMute(boolean mute) {
670        mDesiredMute = mute;
671        mForegroundCall.setMute(mute);
672    }
673
674    /*package*/ boolean getMute() {
675        return mDesiredMute;
676    }
677
678    /* package */ void sendDtmf(char c, Message result) {
679        if (DBG) log("sendDtmf");
680
681        ImsCall imscall = mForegroundCall.getImsCall();
682        if (imscall != null) {
683            imscall.sendDtmf(c, result);
684        }
685    }
686
687    /*package*/ void
688    startDtmf(char c) {
689        if (DBG) log("startDtmf");
690
691        ImsCall imscall = mForegroundCall.getImsCall();
692        if (imscall != null) {
693            imscall.startDtmf(c);
694        } else {
695            loge("startDtmf : no foreground call");
696        }
697    }
698
699    /*package*/ void
700    stopDtmf() {
701        if (DBG) log("stopDtmf");
702
703        ImsCall imscall = mForegroundCall.getImsCall();
704        if (imscall != null) {
705            imscall.stopDtmf();
706        } else {
707            loge("stopDtmf : no foreground call");
708        }
709    }
710
711    //***** Called from ImsPhoneConnection
712
713    /*package*/ void
714    hangup (ImsPhoneConnection conn) throws CallStateException {
715        if (DBG) log("hangup connection");
716
717        if (conn.getOwner() != this) {
718            throw new CallStateException ("ImsPhoneConnection " + conn
719                    + "does not belong to ImsPhoneCallTracker " + this);
720        }
721
722        hangup(conn.getCall());
723    }
724
725    //***** Called from ImsPhoneCall
726
727    /* package */ void
728    hangup (ImsPhoneCall call) throws CallStateException {
729        if (DBG) log("hangup call");
730
731        if (call.getConnections().size() == 0) {
732            throw new CallStateException("no connections");
733        }
734
735        ImsCall imsCall = call.getImsCall();
736        boolean rejectCall = false;
737
738        if (call == mRingingCall) {
739            if (Phone.DEBUG_PHONE) log("(ringing) hangup incoming");
740            rejectCall = true;
741        } else if (call == mForegroundCall) {
742            if (call.isDialingOrAlerting()) {
743                if (Phone.DEBUG_PHONE) {
744                    log("(foregnd) hangup dialing or alerting...");
745                }
746            } else {
747                if (Phone.DEBUG_PHONE) {
748                    log("(foregnd) hangup foreground");
749                }
750                //held call will be resumed by onCallTerminated
751            }
752        } else if (call == mBackgroundCall) {
753            if (Phone.DEBUG_PHONE) {
754                log("(backgnd) hangup waiting or background");
755            }
756        } else {
757            throw new CallStateException ("ImsPhoneCall " + call +
758                    "does not belong to ImsPhoneCallTracker " + this);
759        }
760
761        call.onHangupLocal();
762
763        try {
764            if (imsCall != null) {
765                if (rejectCall) imsCall.reject(ImsReasonInfo.CODE_USER_DECLINE);
766                else imsCall.terminate(ImsReasonInfo.CODE_USER_TERMINATED);
767            } else if (mPendingMO != null && call == mForegroundCall) {
768                // is holding a foreground call
769                mPendingMO.update(null, ImsPhoneCall.State.DISCONNECTED);
770                mPendingMO.onDisconnect();
771                removeConnection(mPendingMO);
772                mPendingMO = null;
773                updatePhoneState();
774                removeMessages(EVENT_DIAL_PENDINGMO);
775            }
776        } catch (ImsException e) {
777            throw new CallStateException(e.getMessage());
778        }
779
780        mPhone.notifyPreciseCallStateChanged();
781    }
782
783    /* package */
784    void resumeWaitingOrHolding() throws CallStateException {
785        if (DBG) log("resumeWaitingOrHolding");
786
787        try {
788            if (mForegroundCall.getState().isAlive()) {
789                //resume foreground call after holding background call
790                //they were switched before holding
791                ImsCall imsCall = mForegroundCall.getImsCall();
792                if (imsCall != null) imsCall.resume();
793            } else if (mRingingCall.getState() == ImsPhoneCall.State.WAITING) {
794                //accept waiting call after holding background call
795                ImsCall imsCall = mRingingCall.getImsCall();
796                if (imsCall != null) imsCall.accept(ImsCallProfile.CALL_TYPE_VOICE);
797            } else {
798                //Just resume background call.
799                //To distinguish resuming call with swapping calls
800                //we do not switch calls.here
801                //ImsPhoneConnection.update will chnage the parent when completed
802                ImsCall imsCall = mBackgroundCall.getImsCall();
803                if (imsCall != null) imsCall.resume();
804            }
805        } catch (ImsException e) {
806            throw new CallStateException(e.getMessage());
807        }
808    }
809
810    /* package */
811    void sendUSSD (String ussdString, Message response) {
812        if (DBG) log("sendUSSD");
813
814        try {
815            if (mUssdSession != null) {
816                mUssdSession.sendUssd(ussdString);
817                AsyncResult.forMessage(response, null, null);
818                response.sendToTarget();
819                return;
820            }
821
822            String[] callees = new String[] { ussdString };
823            ImsCallProfile profile = mImsManager.createCallProfile(mServiceId,
824                    ImsCallProfile.SERVICE_TYPE_NORMAL, ImsCallProfile.CALL_TYPE_VOICE);
825            profile.setCallExtraInt(ImsCallProfile.EXTRA_DIALSTRING,
826                    ImsCallProfile.DIALSTRING_USSD);
827
828            mUssdSession = mImsManager.makeCall(mServiceId, profile,
829                    callees, mImsUssdListener);
830        } catch (ImsException e) {
831            loge("sendUSSD : " + e);
832            mPhone.sendErrorResponse(response, e);
833        }
834    }
835
836    /* package */
837    void cancelUSSD() {
838        if (mUssdSession == null) return;
839
840        try {
841            mUssdSession.terminate(ImsReasonInfo.CODE_USER_TERMINATED);
842        } catch (ImsException e) {
843        }
844
845    }
846
847    private synchronized ImsPhoneConnection findConnection(ImsCall imsCall) {
848        for (ImsPhoneConnection conn : mConnections) {
849            if (conn.getImsCall() == imsCall) {
850                return conn;
851            }
852        }
853        return null;
854    }
855
856    private synchronized void removeConnection(ImsPhoneConnection conn) {
857        mConnections.remove(conn);
858    }
859
860    private synchronized void addConnection(ImsPhoneConnection conn) {
861        mConnections.add(conn);
862    }
863
864    private void processCallStateChange(ImsCall imsCall, ImsPhoneCall.State state, int cause) {
865        if (DBG) log("processCallStateChange " + imsCall + " state=" + state + " cause=" + cause);
866
867        if (imsCall == null) return;
868
869        boolean changed = false;
870        ImsPhoneConnection conn = findConnection(imsCall);
871
872        if (conn == null) {
873            // TODO : what should be done?
874            return;
875        }
876
877        changed = conn.update(imsCall, state);
878
879        if (state == ImsPhoneCall.State.DISCONNECTED) {
880            changed = conn.onDisconnect(cause) || changed;
881            removeConnection(conn);
882        }
883
884        if (changed) {
885            if (conn.getCall() == mHandoverCall) return;
886            updatePhoneState();
887            mPhone.notifyPreciseCallStateChanged();
888        }
889    }
890
891    private int getDisconnectCauseFromReasonInfo(ImsReasonInfo reasonInfo) {
892        int cause = DisconnectCause.ERROR_UNSPECIFIED;
893
894        //int type = reasonInfo.getReasonType();
895        int code = reasonInfo.getCode();
896        switch (code) {
897            case ImsReasonInfo.CODE_SIP_BAD_ADDRESS:
898            case ImsReasonInfo.CODE_SIP_NOT_REACHABLE:
899                return DisconnectCause.NUMBER_UNREACHABLE;
900
901            case ImsReasonInfo.CODE_SIP_BUSY:
902                return DisconnectCause.BUSY;
903
904            case ImsReasonInfo.CODE_USER_TERMINATED:
905                return DisconnectCause.LOCAL;
906
907            case ImsReasonInfo.CODE_LOCAL_CALL_DECLINE:
908                return DisconnectCause.INCOMING_REJECTED;
909
910            case ImsReasonInfo.CODE_USER_TERMINATED_BY_REMOTE:
911                return DisconnectCause.NORMAL;
912
913            case ImsReasonInfo.CODE_SIP_REDIRECTED:
914            case ImsReasonInfo.CODE_SIP_BAD_REQUEST:
915            case ImsReasonInfo.CODE_SIP_FORBIDDEN:
916            case ImsReasonInfo.CODE_SIP_NOT_ACCEPTABLE:
917            case ImsReasonInfo.CODE_SIP_USER_REJECTED:
918            case ImsReasonInfo.CODE_SIP_GLOBAL_ERROR:
919                return DisconnectCause.SERVER_ERROR;
920
921            case ImsReasonInfo.CODE_SIP_SERVICE_UNAVAILABLE:
922            case ImsReasonInfo.CODE_SIP_NOT_FOUND:
923            case ImsReasonInfo.CODE_SIP_SERVER_ERROR:
924                return DisconnectCause.SERVER_UNREACHABLE;
925
926            case ImsReasonInfo.CODE_LOCAL_NETWORK_ROAMING:
927            case ImsReasonInfo.CODE_LOCAL_NETWORK_IP_CHANGED:
928            case ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN:
929            case ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE:
930            case ImsReasonInfo.CODE_LOCAL_NOT_REGISTERED:
931            case ImsReasonInfo.CODE_LOCAL_NETWORK_NO_LTE_COVERAGE:
932            case ImsReasonInfo.CODE_LOCAL_NETWORK_NO_SERVICE:
933            case ImsReasonInfo.CODE_LOCAL_CALL_VCC_ON_PROGRESSING:
934                return DisconnectCause.OUT_OF_SERVICE;
935
936            case ImsReasonInfo.CODE_SIP_REQUEST_TIMEOUT:
937            case ImsReasonInfo.CODE_TIMEOUT_1XX_WAITING:
938            case ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER:
939            case ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER_CALL_UPDATE:
940                return DisconnectCause.TIMED_OUT;
941
942            case ImsReasonInfo.CODE_LOCAL_LOW_BATTERY:
943            case ImsReasonInfo.CODE_LOCAL_POWER_OFF:
944                return DisconnectCause.POWER_OFF;
945
946            default:
947        }
948
949        return cause;
950    }
951
952    /**
953     * Listen to the IMS call state change
954     */
955    private ImsCall.Listener mImsCallListener = new ImsCall.Listener() {
956        @Override
957        public void onCallProgressing(ImsCall imsCall) {
958            if (DBG) log("onCallProgressing");
959
960            mPendingMO = null;
961            processCallStateChange(imsCall, ImsPhoneCall.State.ALERTING,
962                    DisconnectCause.NOT_DISCONNECTED);
963        }
964
965        @Override
966        public void onCallStarted(ImsCall imsCall) {
967            if (DBG) log("onCallStarted");
968
969            mPendingMO = null;
970            processCallStateChange(imsCall, ImsPhoneCall.State.ACTIVE,
971                    DisconnectCause.NOT_DISCONNECTED);
972        }
973
974        /**
975         * onCallStartFailed will be invoked when:
976         * case 1) Dialing fails
977         * case 2) Ringing call is disconnected by local or remote user
978         */
979        @Override
980        public void onCallStartFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
981            if (DBG) log("onCallStartFailed reasonCode=" + reasonInfo.getCode());
982
983            if (mPendingMO != null) {
984                // To initiate dialing circuit-switched call
985                if (reasonInfo.getCode() == ImsReasonInfo.CODE_LOCAL_CALL_CS_RETRY_REQUIRED
986                        && mBackgroundCall.getState() == ImsPhoneCall.State.IDLE
987                        && mRingingCall.getState() == ImsPhoneCall.State.IDLE) {
988                    mForegroundCall.detach(mPendingMO);
989                    removeConnection(mPendingMO);
990                    mPendingMO.finalize();
991                    mPendingMO = null;
992                    mPhone.initiateSilentRedial();
993                    return;
994                }
995                mPendingMO = null;
996            }
997        }
998
999        @Override
1000        public void onCallTerminated(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1001            if (DBG) log("onCallTerminated reasonCode=" + reasonInfo.getCode());
1002
1003            ImsPhoneCall.State oldState = mForegroundCall.getState();
1004            int cause = getDisconnectCauseFromReasonInfo(reasonInfo);
1005            ImsPhoneConnection conn = findConnection(imsCall);
1006            if (DBG) log("cause = " + cause + " conn = " + conn);
1007
1008            if (conn != null && conn.isIncoming() && conn.getConnectTime() == 0) {
1009                // Missed
1010                if (cause == DisconnectCause.NORMAL) {
1011                    cause = DisconnectCause.INCOMING_MISSED;
1012                }
1013                if (DBG) log("Incoming connection of 0 connect time detected - translated cause = "
1014                        + cause);
1015
1016            }
1017
1018            if (cause == DisconnectCause.NORMAL && conn != null && conn.getImsCall().isMerged()) {
1019                // Call was terminated while it is merged instead of a remote disconnect.
1020                cause = DisconnectCause.IMS_MERGED_SUCCESSFULLY;
1021            }
1022
1023            processCallStateChange(imsCall, ImsPhoneCall.State.DISCONNECTED, cause);
1024        }
1025
1026        @Override
1027        public void onCallHeld(ImsCall imsCall) {
1028            if (DBG) log("onCallHeld");
1029
1030            synchronized (mSyncHold) {
1031                ImsPhoneCall.State oldState = mBackgroundCall.getState();
1032                processCallStateChange(imsCall, ImsPhoneCall.State.HOLDING,
1033                        DisconnectCause.NOT_DISCONNECTED);
1034                if (oldState == ImsPhoneCall.State.ACTIVE) {
1035                    // Note: This case comes up when we have just held a call in response to a
1036                    // switchWaitingOrHoldingAndActive.  We now need to resume the background call.
1037                    // The EVENT_RESUME_BACKGROUND causes resumeWaitingOrHolding to be called.
1038                    if ((mForegroundCall.getState() == ImsPhoneCall.State.HOLDING)
1039                            || (mRingingCall.getState() == ImsPhoneCall.State.WAITING)) {
1040
1041                            sendEmptyMessage(EVENT_RESUME_BACKGROUND);
1042                    } else {
1043                        //when multiple connections belong to background call,
1044                        //only the first callback reaches here
1045                        //otherwise the oldState is already HOLDING
1046                        if (mPendingMO != null) {
1047                            sendEmptyMessage(EVENT_DIAL_PENDINGMO);
1048                        }
1049                    }
1050                }
1051            }
1052        }
1053
1054        @Override
1055        public void onCallHoldFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1056            if (DBG) log("onCallHoldFailed reasonCode=" + reasonInfo.getCode());
1057
1058            synchronized (mSyncHold) {
1059                ImsPhoneCall.State bgState = mBackgroundCall.getState();
1060                if (reasonInfo.getCode() == ImsReasonInfo.CODE_LOCAL_CALL_TERMINATED) {
1061                    // disconnected while processing hold
1062                    if (mPendingMO != null) {
1063                        sendEmptyMessage(EVENT_DIAL_PENDINGMO);
1064                    }
1065                } else if (bgState == ImsPhoneCall.State.ACTIVE) {
1066                    mForegroundCall.switchWith(mBackgroundCall);
1067
1068                    if (mPendingMO != null) {
1069                        mPendingMO.setDisconnectCause(DisconnectCause.ERROR_UNSPECIFIED);
1070                        sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
1071                    }
1072                }
1073            }
1074        }
1075
1076        @Override
1077        public void onCallResumed(ImsCall imsCall) {
1078            if (DBG) log("onCallResumed");
1079
1080            // If we are the in midst of swapping FG and BG calls and the call we end up resuming
1081            // is not the one we expected, we likely had a resume failure and we need to swap the
1082            // FG and BG calls back.
1083            if (mSwitchingFgAndBgCalls && imsCall != mCallExpectedToResume) {
1084                mForegroundCall.switchWith(mBackgroundCall);
1085                mSwitchingFgAndBgCalls = false;
1086                mCallExpectedToResume = null;
1087            }
1088            processCallStateChange(imsCall, ImsPhoneCall.State.ACTIVE,
1089                    DisconnectCause.NOT_DISCONNECTED);
1090        }
1091
1092        @Override
1093        public void onCallResumeFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1094            // TODO : What should be done?
1095            // If we are in the midst of swapping the FG and BG calls and we got a resume fail, we
1096            // need to swap back the FG and BG calls.
1097            if (mSwitchingFgAndBgCalls && imsCall == mCallExpectedToResume) {
1098                mForegroundCall.switchWith(mBackgroundCall);
1099                mCallExpectedToResume = null;
1100                mSwitchingFgAndBgCalls = false;
1101            }
1102            mPhone.notifySuppServiceFailed(Phone.SuppService.RESUME);
1103        }
1104
1105        @Override
1106        public void onCallResumeReceived(ImsCall imsCall) {
1107            if (DBG) log("onCallResumeReceived");
1108
1109            if (mOnHoldToneStarted) {
1110                mPhone.stopOnHoldTone();
1111                mOnHoldToneStarted = false;
1112            }
1113        }
1114
1115        @Override
1116        public void onCallHoldReceived(ImsCall imsCall) {
1117            if (DBG) log("onCallHoldReceived");
1118
1119            ImsPhoneConnection conn = findConnection(imsCall);
1120            if (conn != null && conn.getState() == ImsPhoneCall.State.ACTIVE) {
1121                if (!mOnHoldToneStarted && ImsPhoneCall.isLocalTone(imsCall)) {
1122                    mPhone.startOnHoldTone();
1123                    mOnHoldToneStarted = true;
1124                }
1125            }
1126        }
1127
1128        @Override
1129        public void onCallMerged(ImsCall call) {
1130            if (DBG) log("onCallMerged");
1131
1132            mForegroundCall.merge(mBackgroundCall, mForegroundCall.getState());
1133            updatePhoneState();
1134            mPhone.notifyPreciseCallStateChanged();
1135        }
1136
1137        @Override
1138        public void onCallMergeFailed(ImsCall call, ImsReasonInfo reasonInfo) {
1139            if (DBG) log("onCallMergeFailed reasonInfo=" + reasonInfo);
1140            mPhone.notifySuppServiceFailed(Phone.SuppService.CONFERENCE);
1141        }
1142
1143        /**
1144         * Called when the state of IMS conference participant(s) has changed.
1145         *
1146         * @param call the call object that carries out the IMS call.
1147         * @param participants the participant(s) and their new state information.
1148         */
1149        @Override
1150        public void onConferenceParticipantsStateChanged(ImsCall call,
1151                List<ConferenceParticipant> participants) {
1152            if (DBG) log("onConferenceParticipantsStateChanged");
1153
1154            ImsPhoneConnection conn = findConnection(call);
1155            if (conn != null) {
1156                conn.updateConferenceParticipants(participants);
1157            }
1158        }
1159    };
1160
1161    /**
1162     * Listen to the IMS call state change
1163     */
1164    private ImsCall.Listener mImsUssdListener = new ImsCall.Listener() {
1165        @Override
1166        public void onCallStarted(ImsCall imsCall) {
1167            if (DBG) log("mImsUssdListener onCallStarted");
1168
1169            if (imsCall == mUssdSession) {
1170                if (mPendingUssd != null) {
1171                    AsyncResult.forMessage(mPendingUssd);
1172                    mPendingUssd.sendToTarget();
1173                    mPendingUssd = null;
1174                }
1175            }
1176        }
1177
1178        @Override
1179        public void onCallStartFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1180            if (DBG) log("mImsUssdListener onCallStartFailed reasonCode=" + reasonInfo.getCode());
1181
1182            onCallTerminated(imsCall, reasonInfo);
1183        }
1184
1185        @Override
1186        public void onCallTerminated(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1187            if (DBG) log("mImsUssdListener onCallTerminated reasonCode=" + reasonInfo.getCode());
1188
1189            if (imsCall == mUssdSession) {
1190                mUssdSession = null;
1191                if (mPendingUssd != null) {
1192                    CommandException ex =
1193                            new CommandException(CommandException.Error.GENERIC_FAILURE);
1194                    AsyncResult.forMessage(mPendingUssd, null, ex);
1195                    mPendingUssd.sendToTarget();
1196                    mPendingUssd = null;
1197                }
1198            }
1199            imsCall.close();
1200        }
1201
1202        @Override
1203        public void onCallUssdMessageReceived(ImsCall call,
1204                int mode, String ussdMessage) {
1205            if (DBG) log("mImsUssdListener onCallUssdMessageReceived mode=" + mode);
1206
1207            int ussdMode = -1;
1208
1209            switch(mode) {
1210                case ImsCall.USSD_MODE_REQUEST:
1211                    ussdMode = CommandsInterface.USSD_MODE_REQUEST;
1212                    break;
1213
1214                case ImsCall.USSD_MODE_NOTIFY:
1215                    ussdMode = CommandsInterface.USSD_MODE_NOTIFY;
1216                    break;
1217            }
1218
1219            mPhone.onIncomingUSSD(ussdMode, ussdMessage);
1220        }
1221    };
1222
1223    /**
1224     * Listen to the IMS service state change
1225     *
1226     */
1227    private ImsConnectionStateListener mImsConnectionStateListener =
1228        new ImsConnectionStateListener() {
1229        @Override
1230        public void onImsConnected() {
1231            if (DBG) log("onImsConnected");
1232            mPhone.setServiceState(ServiceState.STATE_IN_SERVICE);
1233        }
1234
1235        @Override
1236        public void onImsDisconnected() {
1237            if (DBG) log("onImsDisconnected");
1238            mPhone.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
1239        }
1240
1241        @Override
1242        public void onImsResumed() {
1243            if (DBG) log("onImsResumed");
1244            mPhone.setServiceState(ServiceState.STATE_IN_SERVICE);
1245        }
1246
1247        @Override
1248        public void onImsSuspended() {
1249            if (DBG) log("onImsSuspended");
1250            mPhone.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
1251        }
1252
1253        @Override
1254        public void onFeatureCapabilityChanged(int serviceClass,
1255                int[] enabledFeatures, int[] disabledFeatures) {
1256            if (serviceClass == ImsServiceClass.MMTEL) {
1257                if (enabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE] ==
1258                        ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE) {
1259                    mIsVolteEnabled = true;
1260                }
1261                if (enabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE] ==
1262                        ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE) {
1263                    mIsVtEnabled = true;
1264                }
1265                if (disabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE] ==
1266                        ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE) {
1267                    mIsVolteEnabled = false;
1268                }
1269                if (disabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE] ==
1270                        ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE) {
1271                    mIsVtEnabled = false;
1272                }
1273            }
1274            if (DBG) log("onFeatureCapabilityChanged, mIsVolteEnabled = " +  mIsVolteEnabled
1275                    + " mIsVtEnabled = " + mIsVtEnabled);
1276        }
1277    };
1278
1279    /* package */
1280    ImsUtInterface getUtInterface() throws ImsException {
1281        if (mImsManager == null) {
1282            throw new ImsException("no ims manager", ImsReasonInfo.CODE_UNSPECIFIED);
1283        }
1284
1285        ImsUtInterface ut = mImsManager.getSupplementaryServiceConfiguration(mServiceId);
1286        return ut;
1287    }
1288
1289    /* package */
1290    void notifySrvccState(Call.SrvccState state) {
1291        if (DBG) log("notifySrvccState state=" + state);
1292
1293        mSrvccState = state;
1294
1295        if (mSrvccState == Call.SrvccState.COMPLETED) {
1296            if (mForegroundCall.getConnections().size() > 0) {
1297                mHandoverCall.switchWith(mForegroundCall);
1298            } else if (mBackgroundCall.getConnections().size() > 0) {
1299                mHandoverCall.switchWith(mBackgroundCall);
1300            }
1301
1302            // release wake lock hold
1303            ImsPhoneConnection con = mHandoverCall.getHandoverConnection();
1304            if (con != null) {
1305                con.releaseWakeLock();
1306            }
1307        }
1308    }
1309
1310    //****** Overridden from Handler
1311
1312    @Override
1313    public void
1314    handleMessage (Message msg) {
1315        AsyncResult ar;
1316        if (DBG) log("handleMessage what=" + msg.what);
1317
1318        switch (msg.what) {
1319            case EVENT_HANGUP_PENDINGMO:
1320                if (mPendingMO != null) {
1321                    mPendingMO.onDisconnect();
1322                    removeConnection(mPendingMO);
1323                    mPendingMO = null;
1324                }
1325
1326                updatePhoneState();
1327                mPhone.notifyPreciseCallStateChanged();
1328                break;
1329            case EVENT_RESUME_BACKGROUND:
1330                try {
1331                    resumeWaitingOrHolding();
1332                } catch (CallStateException e) {
1333                    if (Phone.DEBUG_PHONE) {
1334                        loge("handleMessage EVENT_RESUME_BACKGROUND exception=" + e);
1335                    }
1336                }
1337                break;
1338            case EVENT_DIAL_PENDINGMO:
1339                dialInternal(mPendingMO, mClirMode, VideoProfile.VideoState.AUDIO_ONLY);
1340                break;
1341
1342            case EVENT_EXIT_ECM_RESPONSE_CDMA:
1343                // no matter the result, we still do the same here
1344                if (pendingCallInEcm) {
1345                    dialInternal(mPendingMO, pendingCallClirMode, pendingCallVideoState);
1346                    pendingCallInEcm = false;
1347                }
1348                mPhone.unsetOnEcbModeExitResponse(this);
1349                break;
1350        }
1351    }
1352
1353    @Override
1354    protected void log(String msg) {
1355        Rlog.d(LOG_TAG, "[ImsPhoneCallTracker] " + msg);
1356    }
1357
1358    protected void loge(String msg) {
1359        Rlog.e(LOG_TAG, "[ImsPhoneCallTracker] " + msg);
1360    }
1361
1362    @Override
1363    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1364        pw.println("ImsPhoneCallTracker extends:");
1365        super.dump(fd, pw, args);
1366        pw.println(" mVoiceCallEndedRegistrants=" + mVoiceCallEndedRegistrants);
1367        pw.println(" mVoiceCallStartedRegistrants=" + mVoiceCallStartedRegistrants);
1368        pw.println(" mRingingCall=" + mRingingCall);
1369        pw.println(" mForegroundCall=" + mForegroundCall);
1370        pw.println(" mBackgroundCall=" + mBackgroundCall);
1371        pw.println(" mHandoverCall=" + mHandoverCall);
1372        pw.println(" mPendingMO=" + mPendingMO);
1373        //pw.println(" mHangupPendingMO=" + mHangupPendingMO);
1374        pw.println(" mPhone=" + mPhone);
1375        pw.println(" mDesiredMute=" + mDesiredMute);
1376        pw.println(" mState=" + mState);
1377    }
1378
1379    @Override
1380    protected void handlePollCalls(AsyncResult ar) {
1381    }
1382
1383    /* package */
1384    ImsEcbm getEcbmInterface() throws ImsException {
1385        if (mImsManager == null) {
1386            throw new ImsException("no ims manager", ImsReasonInfo.CODE_UNSPECIFIED);
1387        }
1388
1389        ImsEcbm ecbm = mImsManager.getEcbmInterface(mServiceId);
1390        return ecbm;
1391    }
1392
1393    public boolean isInEmergencyCall() {
1394        return mIsInEmergencyCall;
1395    }
1396
1397    public boolean isVolteEnabled() {
1398        return mIsVolteEnabled;
1399    }
1400
1401    public boolean isVtEnabled() {
1402        return mIsVtEnabled;
1403    }
1404}
1405