summaryrefslogtreecommitdiffstats
path: root/src/com/android/incallui/CallList.java
blob: 9b942ed19918deec1950b23ffce5e5d04533ed7a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.incallui;

import com.google.android.collect.Lists;
import com.google.android.collect.Maps;
import com.google.android.collect.Sets;
import com.google.common.base.Preconditions;

import android.os.Handler;
import android.os.Message;

import android.telephony.MSimTelephonyManager;
import com.android.internal.telephony.MSimConstants;
import com.android.services.telephony.common.Call;
import com.android.services.telephony.common.Call.DisconnectCause;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * Maintains the list of active calls received from CallHandlerService and notifies interested
 * classes of changes to the call list as they are received from the telephony stack.
 * Primary lister of changes to this class is InCallPresenter.
 */
public class CallList {

    private static final int DISCONNECTED_CALL_SHORT_TIMEOUT_MS = 200;
    private static final int DISCONNECTED_CALL_MEDIUM_TIMEOUT_MS = 2000;
    private static final int DISCONNECTED_CALL_LONG_TIMEOUT_MS = 5000;

    private static final int EVENT_DISCONNECTED_TIMEOUT = 1;
    private static final int EVENT_NOTIFY_CHANGE = 2;

    private static CallList sInstance = new CallList();

    private final HashMap<Integer, Call> mCallMap = Maps.newHashMap();
    private final HashMap<Integer, ArrayList<String>> mCallTextReponsesMap =
            Maps.newHashMap();
    private final Set<Listener> mListeners = Sets.newArraySet();
    private final HashMap<Integer, List<CallUpdateListener>> mCallUpdateListenerMap = Maps
            .newHashMap();

    private int mSubscription = 0;
    private final ArrayList<ActiveSubChangeListener> mActiveSubChangeListeners =
            Lists.newArrayList();

    /**
     * Static singleton accessor method.
     */
    public static CallList getInstance() {
        return sInstance;
    }

    /**
     * Private constructor.  Instance should only be acquired through getInstance().
     */
    private CallList() {
    }

    /**
     * Called when a single call has changed.
     */
    public void onUpdate(Call call) {
        Log.d(this, "onUpdate - ", call);

        updateActiveSuscription();

        updateCallInMap(call);
        notifyListenersOfChange();
    }

    /**
     * Called when a single call disconnects.
     */
    public void onDisconnect(Call call) {
        Log.d(this, "onDisconnect: ", call);

        boolean updated = updateCallInMap(call);

        if (updated) {
            // notify those listening for changes on this specific change
            notifyCallUpdateListeners(call);

            // notify those listening for all disconnects
            notifyListenersOfDisconnect(call);
        }
    }

    /**
     * Called when a single call has changed.
     */
    public void onIncoming(Call call, List<String> textMessages) {
        Log.d(this, "onIncoming - " + call);

        updateActiveSuscription();

        updateCallInMap(call);
        updateCallTextMap(call, textMessages);

        for (Listener listener : mListeners) {
            listener.onIncomingCall(call);
        }
    }

    /**
     * Called when multiple calls have changed.
     */
    public void onUpdate(List<Call> callsToUpdate) {
        Log.d(this, "onUpdate(...)");

        updateActiveSuscription();

        Preconditions.checkNotNull(callsToUpdate);
        for (Call call : callsToUpdate) {
            Log.d(this, "\t" + call);

            updateCallInMap(call);
            updateCallTextMap(call, null);

            notifyCallUpdateListeners(call);
        }

        notifyListenersOfChange();
    }

    public void notifyCallUpdateListeners(Call call) {
        final List<CallUpdateListener> listeners = mCallUpdateListenerMap.get(call.getCallId());
        if (listeners != null) {
            for (CallUpdateListener listener : listeners) {
                listener.onCallStateChanged(call);
            }
        }
    }

    /**
     * Add a call update listener for a call id.
     *
     * @param callId The call id to get updates for.
     * @param listener The listener to add.
     */
    public void addCallUpdateListener(int callId, CallUpdateListener listener) {
        List<CallUpdateListener> listeners = mCallUpdateListenerMap.get(callId);
        if (listeners == null) {
            listeners = Lists.newArrayList();
            mCallUpdateListenerMap.put(callId, listeners);
        }
        listeners.add(listener);
    }

    /**
     * Remove a call update listener for a call id.
     *
     * @param callId The call id to remove the listener for.
     * @param listener The listener to remove.
     */
    public void removeCallUpdateListener(int callId, CallUpdateListener listener) {
        List<CallUpdateListener> listeners = mCallUpdateListenerMap.get(callId);
        if (listeners != null) {
            listeners.remove(listener);
        }
    }

    public void addListener(Listener listener) {
        Preconditions.checkNotNull(listener);

        mListeners.add(listener);

        // Let the listener know about the active calls immediately.
        listener.onCallListChange(this);
    }

    public void removeListener(Listener listener) {
        Preconditions.checkNotNull(listener);
        mListeners.remove(listener);
    }

    /**
     * TODO: Change so that this function is not needed. Instead of assuming there is an active
     * call, the code should rely on the status of a specific Call and allow the presenters to
     * update the Call object when the active call changes.
     */
    public Call getIncomingOrActive() {
        Call retval = getIncomingCall();
        if (retval == null) {
            retval = getActiveCall();
        }
        return retval;
    }

    public Call getOutgoingCall() {
        Call call = getFirstCallWithState(Call.State.DIALING);
        if (call == null) {
            call = getFirstCallWithState(Call.State.REDIALING);
        }
        return call;
    }

    public Call getActiveCall() {
        return getFirstCallWithState(Call.State.ACTIVE);
    }

    public Call getBackgroundCall() {
        return getFirstCallWithState(Call.State.ONHOLD);
    }

    public Call getDisconnectedCall() {
        return getFirstCallWithState(Call.State.DISCONNECTED);
    }

    public Call getDisconnectingCall() {
        return getFirstCallWithState(Call.State.DISCONNECTING);
    }

    public Call getSecondBackgroundCall() {
        return getCallWithState(Call.State.ONHOLD, 1);
    }

    public Call getActiveOrBackgroundCall() {
        Call call = getActiveCall();
        if (call == null) {
            call = getBackgroundCall();
        }
        return call;
    }

    public Call getIncomingCall() {
        Call call = getFirstCallWithState(Call.State.INCOMING);
        if (call == null) {
            call = getFirstCallWithState(Call.State.CALL_WAITING);
        }

        return call;
    }

    public Call getFirstCall() {
        Call result = getIncomingCall();
        if (result == null) {
            result = getOutgoingCall();
        }
        if (result == null) {
            result = getFirstCallWithState(Call.State.ACTIVE);
        }
        if (result == null) {
            result = getDisconnectingCall();
        }
        if (result == null) {
            result = getDisconnectedCall();
        }
        return result;
    }

    public Call getCall(int callId) {
        return mCallMap.get(callId);
    }

    public boolean existsLiveCall() {
        for (Call call : mCallMap.values()) {
            if (!isCallDead(call)) {
                return true;
            }
        }
        return false;
    }

    public ArrayList<String> getTextResponses(int callId) {
        return mCallTextReponsesMap.get(callId);
    }

    /**
     * Returns first call found in the call map with the specified state.
     */
    public Call getFirstCallWithState(int state) {
        return getCallWithState(state, 0);
    }

    /**
     * Returns the [position]th call found in the call map with the specified state.
     * TODO: Improve this logic to sort by call time.
     */
    public Call getCallWithState(int state, int positionToFind) {
        if (MSimTelephonyManager.getDefault().getMultiSimConfiguration()
                == MSimTelephonyManager.MultiSimVariants.DSDA) {
            return getCallWithState(state, positionToFind, getActiveSubscription());
        }

        Call retval = null;
        int position = 0;
        for (Call call : mCallMap.values()) {
            if (call.getState() == state) {
                if (position >= positionToFind) {
                    retval = call;
                    break;
                } else {
                    position++;
                }
            }
        }

        return retval;
    }

    /**
     * This is called when the service disconnects, either expectedly or unexpectedly.
     * For the expected case, it's because we have no calls left.  For the unexpected case,
     * it is likely a crash of phone and we need to clean up our calls manually.  Without phone,
     * there can be no active calls, so this is relatively safe thing to do.
     */
    public void clearOnDisconnect() {
        for (Call call : mCallMap.values()) {
            final int state = call.getState();
            if (state != Call.State.IDLE &&
                    state != Call.State.INVALID &&
                    state != Call.State.DISCONNECTED) {

                call.setState(Call.State.DISCONNECTED);
                call.setDisconnectCause(DisconnectCause.UNKNOWN);
                updateCallInMap(call);
            }
        }
        notifyListenersOfChange();
    }

    /**
     * Sends a generic notification to all listeners that something has changed.
     * It is up to the listeners to call back to determine what changed.
     */
    private void notifyListenersOfChange() {
        for (Listener listener : mListeners) {
            listener.onCallListChange(this);
        }
    }

    private void notifyListenersOfDisconnect(Call call) {
        for (Listener listener : mListeners) {
            listener.onDisconnect(call);
        }
    }

    /**
     * Updates the call entry in the local map.
     * @return false if no call previously existed and no call was added, otherwise true.
     */
    private boolean updateCallInMap(Call call) {
        Preconditions.checkNotNull(call);

        boolean updated = false;

        final Integer id = new Integer(call.getCallId());

        if (call.getState() == Call.State.DISCONNECTED) {
            // update existing (but do not add!!) disconnected calls
            if (mCallMap.containsKey(id)) {
                final Call.DisconnectCause disconnCause = call.getDisconnectCause();
                Log.d(this, "disconnect cause: " + disconnCause);
                if (disconnCause == Call.DisconnectCause.SRVCC_CALL_DROP) {
                    Log.d(this, "SRVCC call so silently removing call entry");
                    //silently remove the call entry
                    call.setState(Call.State.IDLE);
                    mCallMap.remove(id);
                    updated = false;
                } else {

                    // For disconnected calls, we want to keep them alive for a few seconds
                    // so that the UI has a chance to display anything it needs when a
                    // call is disconnected.

                    // Set up a timer to destroy the call after X seconds.
                    final Message msg = mHandler.obtainMessage(EVENT_DISCONNECTED_TIMEOUT, call);
                    mHandler.sendMessageDelayed(msg, getDelayForDisconnect(call));

                    mCallMap.put(id, call);
                    updated = true;
               }
            }
        } else if (!isCallDead(call)) {
            mCallMap.put(id, call);
            updated = true;
        } else if (mCallMap.containsKey(id)) {
            mCallMap.remove(id);
            updated = true;
        }

        return updated;
    }

    private int getDelayForDisconnect(Call call) {
        Preconditions.checkState(call.getState() == Call.State.DISCONNECTED);


        final Call.DisconnectCause cause = call.getDisconnectCause();
        final int delay;
        switch (cause) {
            case LOCAL:
                delay = DISCONNECTED_CALL_SHORT_TIMEOUT_MS;
                break;
            case NORMAL:
            case UNKNOWN:
                delay = DISCONNECTED_CALL_MEDIUM_TIMEOUT_MS;
                break;
            case INCOMING_REJECTED:
            case INCOMING_MISSED:
                // no delay for missed/rejected incoming calls
                delay = 0;
                break;
            default:
                delay = DISCONNECTED_CALL_LONG_TIMEOUT_MS;
                break;
        }

        return delay;
    }

    private void updateCallTextMap(Call call, List<String> textResponses) {
        Preconditions.checkNotNull(call);

        final Integer id = new Integer(call.getCallId());

        if (!isCallDead(call)) {
            if (textResponses != null) {
                mCallTextReponsesMap.put(id, (ArrayList<String>) textResponses);
            }
        } else if (mCallMap.containsKey(id)) {
            mCallTextReponsesMap.remove(id);
        }
    }

    private boolean isCallDead(Call call) {
        final int state = call.getState();
        return Call.State.IDLE == state || Call.State.INVALID == state;
    }

    /**
     * Sets up a call for deletion and notifies listeners of change.
     */
    private void finishDisconnectedCall(Call call) {
        call.setState(Call.State.IDLE);
        updateCallInMap(call);
        notifyListenersOfChange();
    }

    /**
     * Handles the timeout for destroying disconnected calls.
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EVENT_DISCONNECTED_TIMEOUT:
                    Log.d(this, "EVENT_DISCONNECTED_TIMEOUT ", msg.obj);
                    finishDisconnectedCall((Call) msg.obj);
                    break;
                case EVENT_NOTIFY_CHANGE:
                    Log.d(this, "EVENT_NOTIFY_CHANGE: ");
                    notifyListenersOfChange();
                    for (ActiveSubChangeListener listener : mActiveSubChangeListeners) {
                        listener.onActiveSubChanged(getActiveSubscription());
                    }
                    break;
                default:
                    Log.wtf(this, "Message not expected: " + msg.what);
                    break;
            }
        }
    };

    /**
     * Listener interface for any class that wants to be notified of changes
     * to the call list.
     */
    public interface Listener {
        /**
         * Called when a new incoming call comes in.
         * This is the only method that gets called for incoming calls. Listeners
         * that want to perform an action on incoming call should respond in this method
         * because {@link #onCallListChange} does not automatically get called for
         * incoming calls.
         */
        public void onIncomingCall(Call call);

        /**
         * Called anytime there are changes to the call list.  The change can be switching call
         * states, updating information, etc. This method will NOT be called for new incoming
         * calls and for calls that switch to disconnected state. Listeners must add actions
         * to those method implementations if they want to deal with those actions.
         */
        public void onCallListChange(CallList callList);

        /**
         * Called when a call switches to the disconnected state.  This is the only method
         * that will get called upon disconnection.
         */
        public void onDisconnect(Call call);
    }

    public interface CallUpdateListener {
        // TODO: refactor and limit arg to be call state.  Caller info is not needed.
        public void onCallStateChanged(Call call);
    }

    /**
     * Called when active subscription changes.
     */
    public void onActiveSubChanged(int activeSub) {
        Log.d(this, "onActiveSubChanged  = " + activeSub);
        if (existsLiveCall(activeSub)) {
            setActiveSubscription(activeSub);
        }
    }

    public int getActiveSubscription() {
        return mSubscription;
    }

    /**
     * Called to update the latest active subscription id, and also it
     * notifies the registred clients about subscription change information.
     */
    public void setActiveSubscription(int subscription) {
        if (subscription != mSubscription) {
            Log.i(this, "setActiveSubscription, old = " + mSubscription + " new = " + subscription);
            mSubscription = subscription;
            final Message msg = mHandler.obtainMessage(EVENT_NOTIFY_CHANGE, null);
            mHandler.sendMessage(msg);
        }
    }

    /**
     * Returns true, if any voice call in ACTIVE on the provided subscription.
     */
    public boolean existsLiveCall(int subscription) {
        for (Call call : mCallMap.values()) {
            if (!isCallDead(call) && (call.getSubscription() == subscription)) {
                return true;
            }
        }
        return false;
    }

    /**
     * This method checks whether any other subscription currently has active voice
     * call other than current active subscription, if yes it makes that other
     * subscription as active subscription i.e user visible subscription.
     */
    public boolean switchToOtherActiveSubscription() {
        int activeSub = getActiveSubscription();
        boolean subSwitched = false;

        for (int i = 0; i < MSimTelephonyManager.getDefault().getPhoneCount(); i++) {
            if ((i != activeSub) && existsLiveCall(i)) {
                Log.i(this, "switchToOtherActiveSubscription, sub = " + i);
                subSwitched = true;
                setActiveSubscription(i);
                break;
            }
        }
        return subSwitched;
    }

    /**
     * Method to check if there is any live call in a sub other than the one supplied.
     * @param currentSub  The subscription to exclude while checking for active calls.
     */
    public boolean isAnyOtherSubActive(int currentSub) {
        boolean result = false;
        for (int i = 0; i < MSimTelephonyManager.getDefault().getPhoneCount(); i++) {
            if ((i != currentSub) && existsLiveCall(i)) {
                Log.d(this, "Live call found on another sub = " + i);
                result = true;
                break;
            }
        }
        return result;
    }

    /**
     * Its a utility, gets the current active subscription from TeleService and
     * updates the mSubscription member variable.
     */
    public void updateActiveSuscription() {
        if (!MSimTelephonyManager.getDefault().isMultiSimEnabled()) {
            return;
        }
        setActiveSubscription(CallCommandClient.getInstance().getActiveSubscription());
    }

    /**
     * Returns the [position]th call which belongs to provided subscription and
     * found in the call map with the specified state.
     */
    public Call getCallWithState(int state, int positionToFind, int subscription) {
        Call retval = null;
        int position = 0;
        for (Call call : mCallMap.values()) {
            if ((call.getState() == state) && (call.getSubscription() == subscription)) {
                if (position >= positionToFind) {
                    retval = call;
                    break;
                } else {
                    position++;
                }
            }
        }
        return retval;
    }

    public void addActiveSubChangeListener(ActiveSubChangeListener listener) {
        Preconditions.checkNotNull(listener);
        mActiveSubChangeListeners.add(listener);
    }

    public void removeActiveSubChangeListener(ActiveSubChangeListener listener) {
        Preconditions.checkNotNull(listener);
        mActiveSubChangeListeners.remove(listener);
    }

    public interface ActiveSubChangeListener {
        public void onActiveSubChanged(int subscription);
    }
}