ImsPhoneCallTracker.java revision f1099a9dfe0250a6b343de0646413db4034381de
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(mPhone.getContext(), 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(mPhone.getContext(), 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            //detach the disconnected connections
882            conn.getCall().detach(conn);
883            removeConnection(conn);
884        }
885
886        if (changed) {
887            if (conn.getCall() == mHandoverCall) return;
888            updatePhoneState();
889            mPhone.notifyPreciseCallStateChanged();
890        }
891    }
892
893    private int getDisconnectCauseFromReasonInfo(ImsReasonInfo reasonInfo) {
894        int cause = DisconnectCause.ERROR_UNSPECIFIED;
895
896        //int type = reasonInfo.getReasonType();
897        int code = reasonInfo.getCode();
898        switch (code) {
899            case ImsReasonInfo.CODE_SIP_BAD_ADDRESS:
900            case ImsReasonInfo.CODE_SIP_NOT_REACHABLE:
901                return DisconnectCause.NUMBER_UNREACHABLE;
902
903            case ImsReasonInfo.CODE_SIP_BUSY:
904                return DisconnectCause.BUSY;
905
906            case ImsReasonInfo.CODE_USER_TERMINATED:
907                return DisconnectCause.LOCAL;
908
909            case ImsReasonInfo.CODE_LOCAL_CALL_DECLINE:
910                return DisconnectCause.INCOMING_REJECTED;
911
912            case ImsReasonInfo.CODE_USER_TERMINATED_BY_REMOTE:
913                return DisconnectCause.NORMAL;
914
915            case ImsReasonInfo.CODE_SIP_REDIRECTED:
916            case ImsReasonInfo.CODE_SIP_BAD_REQUEST:
917            case ImsReasonInfo.CODE_SIP_FORBIDDEN:
918            case ImsReasonInfo.CODE_SIP_NOT_ACCEPTABLE:
919            case ImsReasonInfo.CODE_SIP_USER_REJECTED:
920            case ImsReasonInfo.CODE_SIP_GLOBAL_ERROR:
921                return DisconnectCause.SERVER_ERROR;
922
923            case ImsReasonInfo.CODE_SIP_SERVICE_UNAVAILABLE:
924            case ImsReasonInfo.CODE_SIP_NOT_FOUND:
925            case ImsReasonInfo.CODE_SIP_SERVER_ERROR:
926                return DisconnectCause.SERVER_UNREACHABLE;
927
928            case ImsReasonInfo.CODE_LOCAL_NETWORK_ROAMING:
929            case ImsReasonInfo.CODE_LOCAL_NETWORK_IP_CHANGED:
930            case ImsReasonInfo.CODE_LOCAL_IMS_SERVICE_DOWN:
931            case ImsReasonInfo.CODE_LOCAL_SERVICE_UNAVAILABLE:
932            case ImsReasonInfo.CODE_LOCAL_NOT_REGISTERED:
933            case ImsReasonInfo.CODE_LOCAL_NETWORK_NO_LTE_COVERAGE:
934            case ImsReasonInfo.CODE_LOCAL_NETWORK_NO_SERVICE:
935            case ImsReasonInfo.CODE_LOCAL_CALL_VCC_ON_PROGRESSING:
936                return DisconnectCause.OUT_OF_SERVICE;
937
938            case ImsReasonInfo.CODE_SIP_REQUEST_TIMEOUT:
939            case ImsReasonInfo.CODE_TIMEOUT_1XX_WAITING:
940            case ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER:
941            case ImsReasonInfo.CODE_TIMEOUT_NO_ANSWER_CALL_UPDATE:
942                return DisconnectCause.TIMED_OUT;
943
944            case ImsReasonInfo.CODE_LOCAL_LOW_BATTERY:
945            case ImsReasonInfo.CODE_LOCAL_POWER_OFF:
946                return DisconnectCause.POWER_OFF;
947
948            default:
949        }
950
951        return cause;
952    }
953
954    /**
955     * Listen to the IMS call state change
956     */
957    private ImsCall.Listener mImsCallListener = new ImsCall.Listener() {
958        @Override
959        public void onCallProgressing(ImsCall imsCall) {
960            if (DBG) log("onCallProgressing");
961
962            mPendingMO = null;
963            processCallStateChange(imsCall, ImsPhoneCall.State.ALERTING,
964                    DisconnectCause.NOT_DISCONNECTED);
965        }
966
967        @Override
968        public void onCallStarted(ImsCall imsCall) {
969            if (DBG) log("onCallStarted");
970
971            mPendingMO = null;
972            processCallStateChange(imsCall, ImsPhoneCall.State.ACTIVE,
973                    DisconnectCause.NOT_DISCONNECTED);
974        }
975
976        /**
977         * onCallStartFailed will be invoked when:
978         * case 1) Dialing fails
979         * case 2) Ringing call is disconnected by local or remote user
980         */
981        @Override
982        public void onCallStartFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
983            if (DBG) log("onCallStartFailed reasonCode=" + reasonInfo.getCode());
984
985            if (mPendingMO != null) {
986                // To initiate dialing circuit-switched call
987                if (reasonInfo.getCode() == ImsReasonInfo.CODE_LOCAL_CALL_CS_RETRY_REQUIRED
988                        && mBackgroundCall.getState() == ImsPhoneCall.State.IDLE
989                        && mRingingCall.getState() == ImsPhoneCall.State.IDLE) {
990                    mForegroundCall.detach(mPendingMO);
991                    removeConnection(mPendingMO);
992                    mPendingMO.finalize();
993                    mPendingMO = null;
994                    mPhone.initiateSilentRedial();
995                    return;
996                }
997                mPendingMO = null;
998            }
999        }
1000
1001        @Override
1002        public void onCallTerminated(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1003            if (DBG) log("onCallTerminated reasonCode=" + reasonInfo.getCode());
1004
1005            ImsPhoneCall.State oldState = mForegroundCall.getState();
1006            int cause = getDisconnectCauseFromReasonInfo(reasonInfo);
1007            ImsPhoneConnection conn = findConnection(imsCall);
1008            if (DBG) log("cause = " + cause + " conn = " + conn);
1009
1010            if (conn != null && conn.isIncoming() && conn.getConnectTime() == 0) {
1011                // Missed
1012                if (cause == DisconnectCause.NORMAL) {
1013                    cause = DisconnectCause.INCOMING_MISSED;
1014                }
1015                if (DBG) log("Incoming connection of 0 connect time detected - translated cause = "
1016                        + cause);
1017
1018            }
1019
1020            if (cause == DisconnectCause.NORMAL && conn != null && conn.getImsCall().isMerged()) {
1021                // Call was terminated while it is merged instead of a remote disconnect.
1022                cause = DisconnectCause.IMS_MERGED_SUCCESSFULLY;
1023            }
1024
1025            processCallStateChange(imsCall, ImsPhoneCall.State.DISCONNECTED, cause);
1026        }
1027
1028        @Override
1029        public void onCallHeld(ImsCall imsCall) {
1030            if (DBG) log("onCallHeld");
1031
1032            synchronized (mSyncHold) {
1033                ImsPhoneCall.State oldState = mBackgroundCall.getState();
1034                processCallStateChange(imsCall, ImsPhoneCall.State.HOLDING,
1035                        DisconnectCause.NOT_DISCONNECTED);
1036                if (oldState == ImsPhoneCall.State.ACTIVE) {
1037                    // Note: This case comes up when we have just held a call in response to a
1038                    // switchWaitingOrHoldingAndActive.  We now need to resume the background call.
1039                    // The EVENT_RESUME_BACKGROUND causes resumeWaitingOrHolding to be called.
1040                    if ((mForegroundCall.getState() == ImsPhoneCall.State.HOLDING)
1041                            || (mRingingCall.getState() == ImsPhoneCall.State.WAITING)) {
1042
1043                            sendEmptyMessage(EVENT_RESUME_BACKGROUND);
1044                    } else {
1045                        //when multiple connections belong to background call,
1046                        //only the first callback reaches here
1047                        //otherwise the oldState is already HOLDING
1048                        if (mPendingMO != null) {
1049                            sendEmptyMessage(EVENT_DIAL_PENDINGMO);
1050                        }
1051                    }
1052                }
1053            }
1054        }
1055
1056        @Override
1057        public void onCallHoldFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1058            if (DBG) log("onCallHoldFailed reasonCode=" + reasonInfo.getCode());
1059
1060            synchronized (mSyncHold) {
1061                ImsPhoneCall.State bgState = mBackgroundCall.getState();
1062                if (reasonInfo.getCode() == ImsReasonInfo.CODE_LOCAL_CALL_TERMINATED) {
1063                    // disconnected while processing hold
1064                    if (mPendingMO != null) {
1065                        sendEmptyMessage(EVENT_DIAL_PENDINGMO);
1066                    }
1067                } else if (bgState == ImsPhoneCall.State.ACTIVE) {
1068                    mForegroundCall.switchWith(mBackgroundCall);
1069
1070                    if (mPendingMO != null) {
1071                        mPendingMO.setDisconnectCause(DisconnectCause.ERROR_UNSPECIFIED);
1072                        sendEmptyMessageDelayed(EVENT_HANGUP_PENDINGMO, TIMEOUT_HANGUP_PENDINGMO);
1073                    }
1074                }
1075            }
1076        }
1077
1078        @Override
1079        public void onCallResumed(ImsCall imsCall) {
1080            if (DBG) log("onCallResumed");
1081
1082            // If we are the in midst of swapping FG and BG calls and the call we end up resuming
1083            // is not the one we expected, we likely had a resume failure and we need to swap the
1084            // FG and BG calls back.
1085            if (mSwitchingFgAndBgCalls && imsCall != mCallExpectedToResume) {
1086                mForegroundCall.switchWith(mBackgroundCall);
1087                mSwitchingFgAndBgCalls = false;
1088                mCallExpectedToResume = null;
1089            }
1090            processCallStateChange(imsCall, ImsPhoneCall.State.ACTIVE,
1091                    DisconnectCause.NOT_DISCONNECTED);
1092        }
1093
1094        @Override
1095        public void onCallResumeFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1096            // TODO : What should be done?
1097            // If we are in the midst of swapping the FG and BG calls and we got a resume fail, we
1098            // need to swap back the FG and BG calls.
1099            if (mSwitchingFgAndBgCalls && imsCall == mCallExpectedToResume) {
1100                mForegroundCall.switchWith(mBackgroundCall);
1101                mCallExpectedToResume = null;
1102                mSwitchingFgAndBgCalls = false;
1103            }
1104            mPhone.notifySuppServiceFailed(Phone.SuppService.RESUME);
1105        }
1106
1107        @Override
1108        public void onCallResumeReceived(ImsCall imsCall) {
1109            if (DBG) log("onCallResumeReceived");
1110
1111            if (mOnHoldToneStarted) {
1112                mPhone.stopOnHoldTone();
1113                mOnHoldToneStarted = false;
1114            }
1115        }
1116
1117        @Override
1118        public void onCallHoldReceived(ImsCall imsCall) {
1119            if (DBG) log("onCallHoldReceived");
1120
1121            ImsPhoneConnection conn = findConnection(imsCall);
1122            if (conn != null && conn.getState() == ImsPhoneCall.State.ACTIVE) {
1123                if (!mOnHoldToneStarted && ImsPhoneCall.isLocalTone(imsCall)) {
1124                    mPhone.startOnHoldTone();
1125                    mOnHoldToneStarted = true;
1126                }
1127            }
1128        }
1129
1130        @Override
1131        public void onCallMerged(ImsCall call) {
1132            if (DBG) log("onCallMerged");
1133
1134            mForegroundCall.merge(mBackgroundCall, mForegroundCall.getState());
1135            updatePhoneState();
1136            mPhone.notifyPreciseCallStateChanged();
1137        }
1138
1139        @Override
1140        public void onCallMergeFailed(ImsCall call, ImsReasonInfo reasonInfo) {
1141            if (DBG) log("onCallMergeFailed reasonInfo=" + reasonInfo);
1142            mPhone.notifySuppServiceFailed(Phone.SuppService.CONFERENCE);
1143        }
1144
1145        /**
1146         * Called when the state of IMS conference participant(s) has changed.
1147         *
1148         * @param call the call object that carries out the IMS call.
1149         * @param participants the participant(s) and their new state information.
1150         */
1151        @Override
1152        public void onConferenceParticipantsStateChanged(ImsCall call,
1153                List<ConferenceParticipant> participants) {
1154            if (DBG) log("onConferenceParticipantsStateChanged");
1155
1156            ImsPhoneConnection conn = findConnection(call);
1157            if (conn != null) {
1158                conn.updateConferenceParticipants(participants);
1159            }
1160        }
1161
1162        @Override
1163        public void onCallSessionTtyModeReceived(ImsCall call, int mode) {
1164            mPhone.onTtyModeReceived(mode);
1165        }
1166    };
1167
1168    /**
1169     * Listen to the IMS call state change
1170     */
1171    private ImsCall.Listener mImsUssdListener = new ImsCall.Listener() {
1172        @Override
1173        public void onCallStarted(ImsCall imsCall) {
1174            if (DBG) log("mImsUssdListener onCallStarted");
1175
1176            if (imsCall == mUssdSession) {
1177                if (mPendingUssd != null) {
1178                    AsyncResult.forMessage(mPendingUssd);
1179                    mPendingUssd.sendToTarget();
1180                    mPendingUssd = null;
1181                }
1182            }
1183        }
1184
1185        @Override
1186        public void onCallStartFailed(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1187            if (DBG) log("mImsUssdListener onCallStartFailed reasonCode=" + reasonInfo.getCode());
1188
1189            onCallTerminated(imsCall, reasonInfo);
1190        }
1191
1192        @Override
1193        public void onCallTerminated(ImsCall imsCall, ImsReasonInfo reasonInfo) {
1194            if (DBG) log("mImsUssdListener onCallTerminated reasonCode=" + reasonInfo.getCode());
1195
1196            if (imsCall == mUssdSession) {
1197                mUssdSession = null;
1198                if (mPendingUssd != null) {
1199                    CommandException ex =
1200                            new CommandException(CommandException.Error.GENERIC_FAILURE);
1201                    AsyncResult.forMessage(mPendingUssd, null, ex);
1202                    mPendingUssd.sendToTarget();
1203                    mPendingUssd = null;
1204                }
1205            }
1206            imsCall.close();
1207        }
1208
1209        @Override
1210        public void onCallUssdMessageReceived(ImsCall call,
1211                int mode, String ussdMessage) {
1212            if (DBG) log("mImsUssdListener onCallUssdMessageReceived mode=" + mode);
1213
1214            int ussdMode = -1;
1215
1216            switch(mode) {
1217                case ImsCall.USSD_MODE_REQUEST:
1218                    ussdMode = CommandsInterface.USSD_MODE_REQUEST;
1219                    break;
1220
1221                case ImsCall.USSD_MODE_NOTIFY:
1222                    ussdMode = CommandsInterface.USSD_MODE_NOTIFY;
1223                    break;
1224            }
1225
1226            mPhone.onIncomingUSSD(ussdMode, ussdMessage);
1227        }
1228    };
1229
1230    /**
1231     * Listen to the IMS service state change
1232     *
1233     */
1234    private ImsConnectionStateListener mImsConnectionStateListener =
1235        new ImsConnectionStateListener() {
1236        @Override
1237        public void onImsConnected() {
1238            if (DBG) log("onImsConnected");
1239            mPhone.setServiceState(ServiceState.STATE_IN_SERVICE);
1240        }
1241
1242        @Override
1243        public void onImsDisconnected() {
1244            if (DBG) log("onImsDisconnected");
1245            mPhone.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
1246        }
1247
1248        @Override
1249        public void onImsResumed() {
1250            if (DBG) log("onImsResumed");
1251            mPhone.setServiceState(ServiceState.STATE_IN_SERVICE);
1252        }
1253
1254        @Override
1255        public void onImsSuspended() {
1256            if (DBG) log("onImsSuspended");
1257            mPhone.setServiceState(ServiceState.STATE_OUT_OF_SERVICE);
1258        }
1259
1260        @Override
1261        public void onFeatureCapabilityChanged(int serviceClass,
1262                int[] enabledFeatures, int[] disabledFeatures) {
1263            if (serviceClass == ImsServiceClass.MMTEL) {
1264                if (enabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE] ==
1265                        ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE) {
1266                    mIsVolteEnabled = true;
1267                }
1268                if (enabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE] ==
1269                        ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE) {
1270                    mIsVtEnabled = true;
1271                }
1272                if (disabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE] ==
1273                        ImsConfig.FeatureConstants.FEATURE_TYPE_VOICE_OVER_LTE) {
1274                    mIsVolteEnabled = false;
1275                }
1276                if (disabledFeatures[ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE] ==
1277                        ImsConfig.FeatureConstants.FEATURE_TYPE_VIDEO_OVER_LTE) {
1278                    mIsVtEnabled = false;
1279                }
1280            }
1281            if (DBG) log("onFeatureCapabilityChanged, mIsVolteEnabled = " +  mIsVolteEnabled
1282                    + " mIsVtEnabled = " + mIsVtEnabled);
1283        }
1284    };
1285
1286    /* package */
1287    ImsUtInterface getUtInterface() throws ImsException {
1288        if (mImsManager == null) {
1289            throw new ImsException("no ims manager", ImsReasonInfo.CODE_UNSPECIFIED);
1290        }
1291
1292        ImsUtInterface ut = mImsManager.getSupplementaryServiceConfiguration(mServiceId);
1293        return ut;
1294    }
1295
1296    private void transferHandoverConnections(ImsPhoneCall call) {
1297        if (call.mConnections != null) {
1298            for (Connection c : call.mConnections) {
1299                c.mPreHandoverState = call.mState;
1300                log ("Connection state before handover is " + c.getStateBeforeHandover());
1301            }
1302        }
1303        if (mHandoverCall.mConnections == null ) {
1304            mHandoverCall.mConnections = call.mConnections;
1305        } else { // Multi-call SRVCC
1306            mHandoverCall.mConnections.addAll(call.mConnections);
1307        }
1308        if (mHandoverCall.mConnections != null) {
1309            if (call.getImsCall() != null) {
1310                call.getImsCall().close();
1311            }
1312            for (Connection c : mHandoverCall.mConnections) {
1313                ((ImsPhoneConnection)c).changeParent(mHandoverCall);
1314            }
1315        }
1316        if (call.getState().isAlive()) {
1317            log ("Call is alive and state is " + call.mState);
1318            mHandoverCall.mState = call.mState;
1319        }
1320        call.mConnections.clear();
1321        call.mState = ImsPhoneCall.State.IDLE;
1322    }
1323
1324    /* package */
1325    void notifySrvccState(Call.SrvccState state) {
1326        if (DBG) log("notifySrvccState state=" + state);
1327
1328        mSrvccState = state;
1329
1330        if (mSrvccState == Call.SrvccState.COMPLETED) {
1331            transferHandoverConnections(mForegroundCall);
1332            transferHandoverConnections(mBackgroundCall);
1333            transferHandoverConnections(mRingingCall);
1334            // release wake lock hold
1335            ImsPhoneConnection con = mHandoverCall.getHandoverConnection();
1336            if (con != null) {
1337                con.releaseWakeLock();
1338            }
1339        }
1340    }
1341
1342    //****** Overridden from Handler
1343
1344    @Override
1345    public void
1346    handleMessage (Message msg) {
1347        AsyncResult ar;
1348        if (DBG) log("handleMessage what=" + msg.what);
1349
1350        switch (msg.what) {
1351            case EVENT_HANGUP_PENDINGMO:
1352                if (mPendingMO != null) {
1353                    mPendingMO.onDisconnect();
1354                    removeConnection(mPendingMO);
1355                    mPendingMO = null;
1356                }
1357
1358                updatePhoneState();
1359                mPhone.notifyPreciseCallStateChanged();
1360                break;
1361            case EVENT_RESUME_BACKGROUND:
1362                try {
1363                    resumeWaitingOrHolding();
1364                } catch (CallStateException e) {
1365                    if (Phone.DEBUG_PHONE) {
1366                        loge("handleMessage EVENT_RESUME_BACKGROUND exception=" + e);
1367                    }
1368                }
1369                break;
1370            case EVENT_DIAL_PENDINGMO:
1371                dialInternal(mPendingMO, mClirMode, VideoProfile.VideoState.AUDIO_ONLY);
1372                break;
1373
1374            case EVENT_EXIT_ECM_RESPONSE_CDMA:
1375                // no matter the result, we still do the same here
1376                if (pendingCallInEcm) {
1377                    dialInternal(mPendingMO, pendingCallClirMode, pendingCallVideoState);
1378                    pendingCallInEcm = false;
1379                }
1380                mPhone.unsetOnEcbModeExitResponse(this);
1381                break;
1382        }
1383    }
1384
1385    @Override
1386    protected void log(String msg) {
1387        Rlog.d(LOG_TAG, "[ImsPhoneCallTracker] " + msg);
1388    }
1389
1390    protected void loge(String msg) {
1391        Rlog.e(LOG_TAG, "[ImsPhoneCallTracker] " + msg);
1392    }
1393
1394    @Override
1395    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1396        pw.println("ImsPhoneCallTracker extends:");
1397        super.dump(fd, pw, args);
1398        pw.println(" mVoiceCallEndedRegistrants=" + mVoiceCallEndedRegistrants);
1399        pw.println(" mVoiceCallStartedRegistrants=" + mVoiceCallStartedRegistrants);
1400        pw.println(" mRingingCall=" + mRingingCall);
1401        pw.println(" mForegroundCall=" + mForegroundCall);
1402        pw.println(" mBackgroundCall=" + mBackgroundCall);
1403        pw.println(" mHandoverCall=" + mHandoverCall);
1404        pw.println(" mPendingMO=" + mPendingMO);
1405        //pw.println(" mHangupPendingMO=" + mHangupPendingMO);
1406        pw.println(" mPhone=" + mPhone);
1407        pw.println(" mDesiredMute=" + mDesiredMute);
1408        pw.println(" mState=" + mState);
1409    }
1410
1411    @Override
1412    protected void handlePollCalls(AsyncResult ar) {
1413    }
1414
1415    /* package */
1416    ImsEcbm getEcbmInterface() throws ImsException {
1417        if (mImsManager == null) {
1418            throw new ImsException("no ims manager", ImsReasonInfo.CODE_UNSPECIFIED);
1419        }
1420
1421        ImsEcbm ecbm = mImsManager.getEcbmInterface(mServiceId);
1422        return ecbm;
1423    }
1424
1425    public boolean isInEmergencyCall() {
1426        return mIsInEmergencyCall;
1427    }
1428
1429    public boolean isVolteEnabled() {
1430        return mIsVolteEnabled;
1431    }
1432
1433    public boolean isVtEnabled() {
1434        return mIsVtEnabled;
1435    }
1436}
1437