blob: a5ba31c50a531d3b92df0feff9ce15d845c43ef7 [file] [log] [blame]
Eric Erfanianccca3152017-02-22 16:32:36 -08001/*
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.incallui;
18
19import android.content.Context;
20import android.content.Intent;
21import android.graphics.Point;
22import android.os.Bundle;
23import android.os.Handler;
24import android.support.annotation.NonNull;
25import android.support.annotation.Nullable;
26import android.support.annotation.VisibleForTesting;
27import android.telecom.Call.Details;
28import android.telecom.DisconnectCause;
29import android.telecom.PhoneAccount;
30import android.telecom.PhoneAccountHandle;
31import android.telecom.TelecomManager;
32import android.telecom.VideoProfile;
33import android.telephony.PhoneStateListener;
34import android.telephony.TelephonyManager;
35import android.view.Window;
36import android.view.WindowManager;
Eric Erfanianccca3152017-02-22 16:32:36 -080037import com.android.contacts.common.compat.CallCompat;
38import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler;
39import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler.OnCheckBlockedListener;
40import com.android.dialer.blocking.FilteredNumbersUtil;
41import com.android.dialer.common.LogUtil;
Eric Erfaniand8046e52017-04-06 09:41:50 -070042import com.android.dialer.enrichedcall.EnrichedCallComponent;
Eric Erfanian10b34a52017-05-04 08:23:17 -070043import com.android.dialer.location.GeoUtil;
Eric Erfanian8369df02017-05-03 10:27:13 -070044import com.android.dialer.logging.InteractionEvent;
Eric Erfanianccca3152017-02-22 16:32:36 -080045import com.android.dialer.logging.Logger;
Eric Erfaniand5e47f62017-03-15 14:41:07 -070046import com.android.dialer.postcall.PostCall;
Eric Erfanianccca3152017-02-22 16:32:36 -080047import com.android.dialer.telecom.TelecomUtil;
48import com.android.dialer.util.TouchPointManager;
49import com.android.incallui.InCallOrientationEventListener.ScreenOrientation;
50import com.android.incallui.answerproximitysensor.PseudoScreenState;
51import com.android.incallui.call.CallList;
52import com.android.incallui.call.DialerCall;
Eric Erfanianccca3152017-02-22 16:32:36 -080053import com.android.incallui.call.ExternalCallList;
Eric Erfanianccca3152017-02-22 16:32:36 -080054import com.android.incallui.call.TelecomAdapter;
Eric Erfanianccca3152017-02-22 16:32:36 -080055import com.android.incallui.latencyreport.LatencyReport;
56import com.android.incallui.legacyblocking.BlockedNumberContentObserver;
57import com.android.incallui.spam.SpamCallListListener;
58import com.android.incallui.util.TelecomCallUtil;
59import com.android.incallui.videosurface.bindings.VideoSurfaceBindings;
60import com.android.incallui.videosurface.protocol.VideoSurfaceTexture;
Eric Erfanian90508232017-03-24 09:31:16 -070061import com.android.incallui.videotech.utils.VideoUtils;
Eric Erfanianccca3152017-02-22 16:32:36 -080062import java.util.Collections;
63import java.util.List;
64import java.util.Objects;
65import java.util.Set;
66import java.util.concurrent.ConcurrentHashMap;
67import java.util.concurrent.CopyOnWriteArrayList;
68import java.util.concurrent.atomic.AtomicBoolean;
69
70/**
71 * Takes updates from the CallList and notifies the InCallActivity (UI) of the changes. Responsible
72 * for starting the activity for a new call and finishing the activity when all calls are
73 * disconnected. Creates and manages the in-call state and provides a listener pattern for the
74 * presenters that want to listen in on the in-call state changes. TODO: This class has become more
75 * of a state machine at this point. Consider renaming.
76 */
Eric Erfaniand5e47f62017-03-15 14:41:07 -070077public class InCallPresenter implements CallList.Listener {
Eric Erfanianccca3152017-02-22 16:32:36 -080078
79 private static final String EXTRA_FIRST_TIME_SHOWN =
80 "com.android.incallui.intent.extra.FIRST_TIME_SHOWN";
81
82 private static final long BLOCK_QUERY_TIMEOUT_MS = 1000;
83
84 private static final Bundle EMPTY_EXTRAS = new Bundle();
85
86 private static InCallPresenter sInCallPresenter;
87
88 /**
89 * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is load factor before
90 * resizing, 1 means we only expect a single thread to access the map so make only a single shard
91 */
92 private final Set<InCallStateListener> mListeners =
93 Collections.newSetFromMap(new ConcurrentHashMap<InCallStateListener, Boolean>(8, 0.9f, 1));
94
95 private final List<IncomingCallListener> mIncomingCallListeners = new CopyOnWriteArrayList<>();
96 private final Set<InCallDetailsListener> mDetailsListeners =
97 Collections.newSetFromMap(new ConcurrentHashMap<InCallDetailsListener, Boolean>(8, 0.9f, 1));
98 private final Set<CanAddCallListener> mCanAddCallListeners =
99 Collections.newSetFromMap(new ConcurrentHashMap<CanAddCallListener, Boolean>(8, 0.9f, 1));
100 private final Set<InCallUiListener> mInCallUiListeners =
101 Collections.newSetFromMap(new ConcurrentHashMap<InCallUiListener, Boolean>(8, 0.9f, 1));
102 private final Set<InCallOrientationListener> mOrientationListeners =
103 Collections.newSetFromMap(
104 new ConcurrentHashMap<InCallOrientationListener, Boolean>(8, 0.9f, 1));
105 private final Set<InCallEventListener> mInCallEventListeners =
106 Collections.newSetFromMap(new ConcurrentHashMap<InCallEventListener, Boolean>(8, 0.9f, 1));
107
108 private StatusBarNotifier mStatusBarNotifier;
109 private ExternalCallNotifier mExternalCallNotifier;
110 private ContactInfoCache mContactInfoCache;
111 private Context mContext;
112 private final OnCheckBlockedListener mOnCheckBlockedListener =
113 new OnCheckBlockedListener() {
114 @Override
115 public void onCheckComplete(final Integer id) {
116 if (id != null && id != FilteredNumberAsyncQueryHandler.INVALID_ID) {
117 // Silence the ringer now to prevent ringing and vibration before the call is
118 // terminated when Telecom attempts to add it.
119 TelecomUtil.silenceRinger(mContext);
120 }
121 }
122 };
123 private CallList mCallList;
124 private ExternalCallList mExternalCallList;
125 private InCallActivity mInCallActivity;
126 private ManageConferenceActivity mManageConferenceActivity;
127 private final android.telecom.Call.Callback mCallCallback =
128 new android.telecom.Call.Callback() {
129 @Override
130 public void onPostDialWait(
131 android.telecom.Call telecomCall, String remainingPostDialSequence) {
132 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
133 if (call == null) {
134 Log.w(this, "DialerCall not found in call list: " + telecomCall);
135 return;
136 }
137 onPostDialCharWait(call.getId(), remainingPostDialSequence);
138 }
139
140 @Override
141 public void onDetailsChanged(
142 android.telecom.Call telecomCall, android.telecom.Call.Details details) {
143 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
144 if (call == null) {
145 Log.w(this, "DialerCall not found in call list: " + telecomCall);
146 return;
147 }
148
149 if (details.hasProperty(Details.PROPERTY_IS_EXTERNAL_CALL)
150 && !mExternalCallList.isCallTracked(telecomCall)) {
151
152 // A regular call became an external call so swap call lists.
153 Log.i(this, "Call became external: " + telecomCall);
154 mCallList.onInternalCallMadeExternal(mContext, telecomCall);
155 mExternalCallList.onCallAdded(telecomCall);
156 return;
157 }
158
159 for (InCallDetailsListener listener : mDetailsListeners) {
160 listener.onDetailsChanged(call, details);
161 }
162 }
163
164 @Override
165 public void onConferenceableCallsChanged(
166 android.telecom.Call telecomCall, List<android.telecom.Call> conferenceableCalls) {
167 Log.i(this, "onConferenceableCallsChanged: " + telecomCall);
168 onDetailsChanged(telecomCall, telecomCall.getDetails());
169 }
170 };
171 private InCallState mInCallState = InCallState.NO_CALLS;
172 private ProximitySensor mProximitySensor;
173 private final PseudoScreenState mPseudoScreenState = new PseudoScreenState();
174 private boolean mServiceConnected;
Eric Erfanianccca3152017-02-22 16:32:36 -0800175 private InCallCameraManager mInCallCameraManager;
176 private FilteredNumberAsyncQueryHandler mFilteredQueryHandler;
177 private CallList.Listener mSpamCallListListener;
178 /** Whether or not we are currently bound and waiting for Telecom to send us a new call. */
179 private boolean mBoundAndWaitingForOutgoingCall;
180 /** Determines if the InCall UI is in fullscreen mode or not. */
181 private boolean mIsFullScreen = false;
182
183 private PhoneStateListener mPhoneStateListener =
184 new PhoneStateListener() {
185 @Override
186 public void onCallStateChanged(int state, String incomingNumber) {
187 if (state == TelephonyManager.CALL_STATE_RINGING) {
188 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
189 return;
190 }
191 // Check if the number is blocked, to silence the ringer.
192 String countryIso = GeoUtil.getCurrentCountryIso(mContext);
193 mFilteredQueryHandler.isBlockedNumber(
194 mOnCheckBlockedListener, incomingNumber, countryIso);
195 }
196 }
197 };
198 /**
199 * Is true when the activity has been previously started. Some code needs to know not just if the
200 * activity is currently up, but if it had been previously shown in foreground for this in-call
201 * session (e.g., StatusBarNotifier). This gets reset when the session ends in the tear-down
202 * method.
203 */
204 private boolean mIsActivityPreviouslyStarted = false;
205
206 /** Whether or not InCallService is bound to Telecom. */
207 private boolean mServiceBound = false;
208
209 /**
210 * When configuration changes Android kills the current activity and starts a new one. The flag is
211 * used to check if full clean up is necessary (activity is stopped and new activity won't be
212 * started), or if a new activity will be started right after the current one is destroyed, and
213 * therefore no need in release all resources.
214 */
215 private boolean mIsChangingConfigurations = false;
216
217 private boolean mAwaitingCallListUpdate = false;
218
219 private ExternalCallList.ExternalCallListener mExternalCallListener =
220 new ExternalCallList.ExternalCallListener() {
221
222 @Override
223 public void onExternalCallPulled(android.telecom.Call call) {
224 // Note: keep this code in sync with InCallPresenter#onCallAdded
225 LatencyReport latencyReport = new LatencyReport(call);
226 latencyReport.onCallBlockingDone();
227 // Note: External calls do not require spam checking.
228 mCallList.onCallAdded(mContext, call, latencyReport);
229 call.registerCallback(mCallCallback);
230 }
231
232 @Override
233 public void onExternalCallAdded(android.telecom.Call call) {
234 // No-op
235 }
236
237 @Override
238 public void onExternalCallRemoved(android.telecom.Call call) {
239 // No-op
240 }
241
242 @Override
243 public void onExternalCallUpdated(android.telecom.Call call) {
244 // No-op
245 }
246 };
247
248 private ThemeColorManager mThemeColorManager;
249 private VideoSurfaceTexture mLocalVideoSurfaceTexture;
250 private VideoSurfaceTexture mRemoteVideoSurfaceTexture;
251
Eric Erfanian10b34a52017-05-04 08:23:17 -0700252 /** Inaccessible constructor. Must use getRunningInstance() to get this singleton. */
Eric Erfanianccca3152017-02-22 16:32:36 -0800253 @VisibleForTesting
254 InCallPresenter() {}
255
256 public static synchronized InCallPresenter getInstance() {
257 if (sInCallPresenter == null) {
258 sInCallPresenter = new InCallPresenter();
259 }
260 return sInCallPresenter;
261 }
262
Eric Erfanian10b34a52017-05-04 08:23:17 -0700263 @VisibleForTesting
264 public static synchronized void setInstanceForTesting(InCallPresenter inCallPresenter) {
265 sInCallPresenter = inCallPresenter;
266 }
267
Eric Erfanianccca3152017-02-22 16:32:36 -0800268 /**
269 * Determines whether or not a call has no valid phone accounts that can be used to make the call
270 * with. Emergency calls do not require a phone account.
271 *
272 * @param call to check accounts for.
273 * @return {@code true} if the call has no call capable phone accounts set, {@code false} if the
274 * call contains a phone account that could be used to initiate it with, or is an emergency
275 * call.
276 */
277 public static boolean isCallWithNoValidAccounts(DialerCall call) {
278 if (call != null && !call.isEmergencyCall()) {
279 Bundle extras = call.getIntentExtras();
280
281 if (extras == null) {
282 extras = EMPTY_EXTRAS;
283 }
284
285 final List<PhoneAccountHandle> phoneAccountHandles =
286 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
287
288 if ((call.getAccountHandle() == null
289 && (phoneAccountHandles == null || phoneAccountHandles.isEmpty()))) {
290 Log.i(InCallPresenter.getInstance(), "No valid accounts for call " + call);
291 return true;
292 }
293 }
294 return false;
295 }
296
297 public InCallState getInCallState() {
298 return mInCallState;
299 }
300
301 public CallList getCallList() {
302 return mCallList;
303 }
304
305 public void setUp(
306 @NonNull Context context,
307 CallList callList,
308 ExternalCallList externalCallList,
309 StatusBarNotifier statusBarNotifier,
310 ExternalCallNotifier externalCallNotifier,
311 ContactInfoCache contactInfoCache,
312 ProximitySensor proximitySensor) {
313 if (mServiceConnected) {
314 Log.i(this, "New service connection replacing existing one.");
315 if (context != mContext || callList != mCallList) {
316 throw new IllegalStateException();
317 }
318 return;
319 }
320
321 Objects.requireNonNull(context);
322 mContext = context;
323
324 mContactInfoCache = contactInfoCache;
325
326 mStatusBarNotifier = statusBarNotifier;
327 mExternalCallNotifier = externalCallNotifier;
328 addListener(mStatusBarNotifier);
Eric Erfaniand8046e52017-04-06 09:41:50 -0700329 EnrichedCallComponent.get(mContext)
330 .getEnrichedCallManager()
331 .registerStateChangedListener(mStatusBarNotifier);
Eric Erfanianccca3152017-02-22 16:32:36 -0800332
333 mProximitySensor = proximitySensor;
334 addListener(mProximitySensor);
335
336 mThemeColorManager =
337 new ThemeColorManager(new InCallUIMaterialColorMapUtils(mContext.getResources()));
338
339 mCallList = callList;
340 mExternalCallList = externalCallList;
341 externalCallList.addExternalCallListener(mExternalCallNotifier);
342 externalCallList.addExternalCallListener(mExternalCallListener);
343
344 // This only gets called by the service so this is okay.
345 mServiceConnected = true;
346
347 // The final thing we do in this set up is add ourselves as a listener to CallList. This
348 // will kick off an update and the whole process can start.
349 mCallList.addListener(this);
350
351 // Create spam call list listener and add it to the list of listeners
352 mSpamCallListListener = new SpamCallListListener(context);
353 mCallList.addListener(mSpamCallListListener);
354
355 VideoPauseController.getInstance().setUp(this);
Eric Erfanianccca3152017-02-22 16:32:36 -0800356
357 mFilteredQueryHandler = new FilteredNumberAsyncQueryHandler(context);
358 mContext
359 .getSystemService(TelephonyManager.class)
360 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
361
362 Log.d(this, "Finished InCallPresenter.setUp");
363 }
364
365 /**
366 * Called when the telephony service has disconnected from us. This will happen when there are no
367 * more active calls. However, we may still want to continue showing the UI for certain cases like
368 * showing "Call Ended". What we really want is to wait for the activity and the service to both
369 * disconnect before we tear things down. This method sets a serviceConnected boolean and calls a
370 * secondary method that performs the aforementioned logic.
371 */
372 public void tearDown() {
373 Log.d(this, "tearDown");
374 mCallList.clearOnDisconnect();
375
376 mServiceConnected = false;
377
378 mContext
379 .getSystemService(TelephonyManager.class)
380 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
381
382 attemptCleanup();
383 VideoPauseController.getInstance().tearDown();
Eric Erfanianccca3152017-02-22 16:32:36 -0800384 }
385
386 private void attemptFinishActivity() {
387 final boolean doFinish = (mInCallActivity != null && isActivityStarted());
388 Log.i(this, "Hide in call UI: " + doFinish);
389 if (doFinish) {
390 mInCallActivity.setExcludeFromRecents(true);
391 mInCallActivity.finish();
Eric Erfanianccca3152017-02-22 16:32:36 -0800392 }
393 }
394
395 /**
396 * Called when the UI ends. Attempts to tear down everything if necessary. See {@link #tearDown()}
397 * for more insight on the tear-down process.
398 */
399 public void unsetActivity(InCallActivity inCallActivity) {
400 if (inCallActivity == null) {
401 throw new IllegalArgumentException("unregisterActivity cannot be called with null");
402 }
403 if (mInCallActivity == null) {
404 Log.i(this, "No InCallActivity currently set, no need to unset.");
405 return;
406 }
407 if (mInCallActivity != inCallActivity) {
408 Log.w(
409 this,
410 "Second instance of InCallActivity is trying to unregister when another"
411 + " instance is active. Ignoring.");
412 return;
413 }
414 updateActivity(null);
415 }
416
417 /**
418 * Updates the current instance of {@link InCallActivity} with the provided one. If a {@code null}
419 * activity is provided, it means that the activity was finished and we should attempt to cleanup.
420 */
421 private void updateActivity(InCallActivity inCallActivity) {
422 boolean updateListeners = false;
423 boolean doAttemptCleanup = false;
424
425 if (inCallActivity != null) {
426 if (mInCallActivity == null) {
427 updateListeners = true;
428 Log.i(this, "UI Initialized");
429 } else {
430 // since setActivity is called onStart(), it can be called multiple times.
431 // This is fine and ignorable, but we do not want to update the world every time
432 // this happens (like going to/from background) so we do not set updateListeners.
433 }
434
435 mInCallActivity = inCallActivity;
436 mInCallActivity.setExcludeFromRecents(false);
437
438 // By the time the UI finally comes up, the call may already be disconnected.
439 // If that's the case, we may need to show an error dialog.
440 if (mCallList != null && mCallList.getDisconnectedCall() != null) {
441 maybeShowErrorDialogOnDisconnect(mCallList.getDisconnectedCall());
442 }
443
444 // When the UI comes up, we need to first check the in-call state.
445 // If we are showing NO_CALLS, that means that a call probably connected and
446 // then immediately disconnected before the UI was able to come up.
447 // If we dont have any calls, start tearing down the UI instead.
448 // NOTE: This code relies on {@link #mInCallActivity} being set so we run it after
449 // it has been set.
450 if (mInCallState == InCallState.NO_CALLS) {
451 Log.i(this, "UI Initialized, but no calls left. shut down.");
452 attemptFinishActivity();
453 return;
454 }
455 } else {
456 Log.i(this, "UI Destroyed");
457 updateListeners = true;
458 mInCallActivity = null;
459
460 // We attempt cleanup for the destroy case but only after we recalculate the state
461 // to see if we need to come back up or stay shut down. This is why we do the
462 // cleanup after the call to onCallListChange() instead of directly here.
463 doAttemptCleanup = true;
464 }
465
466 // Messages can come from the telephony layer while the activity is coming up
467 // and while the activity is going down. So in both cases we need to recalculate what
468 // state we should be in after they complete.
469 // Examples: (1) A new incoming call could come in and then get disconnected before
470 // the activity is created.
471 // (2) All calls could disconnect and then get a new incoming call before the
472 // activity is destroyed.
473 //
474 // b/1122139 - We previously had a check for mServiceConnected here as well, but there are
475 // cases where we need to recalculate the current state even if the service in not
476 // connected. In particular the case where startOrFinish() is called while the app is
477 // already finish()ing. In that case, we skip updating the state with the knowledge that
478 // we will check again once the activity has finished. That means we have to recalculate the
479 // state here even if the service is disconnected since we may not have finished a state
480 // transition while finish()ing.
481 if (updateListeners) {
482 onCallListChange(mCallList);
483 }
484
485 if (doAttemptCleanup) {
486 attemptCleanup();
487 }
488 }
489
490 public void setManageConferenceActivity(
491 @Nullable ManageConferenceActivity manageConferenceActivity) {
492 mManageConferenceActivity = manageConferenceActivity;
493 }
494
495 public void onBringToForeground(boolean showDialpad) {
496 Log.i(this, "Bringing UI to foreground.");
497 bringToForeground(showDialpad);
498 }
499
500 public void onCallAdded(final android.telecom.Call call) {
501 LatencyReport latencyReport = new LatencyReport(call);
502 if (shouldAttemptBlocking(call)) {
503 maybeBlockCall(call, latencyReport);
504 } else {
505 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
506 mExternalCallList.onCallAdded(call);
507 } else {
508 latencyReport.onCallBlockingDone();
509 mCallList.onCallAdded(mContext, call, latencyReport);
510 }
511 }
512
513 // Since a call has been added we are no longer waiting for Telecom to send us a call.
514 setBoundAndWaitingForOutgoingCall(false, null);
515 call.registerCallback(mCallCallback);
516 }
517
518 private boolean shouldAttemptBlocking(android.telecom.Call call) {
519 if (call.getState() != android.telecom.Call.STATE_RINGING) {
520 return false;
521 }
522 if (TelecomCallUtil.isEmergencyCall(call)) {
523 Log.i(this, "Not attempting to block incoming emergency call");
524 return false;
525 }
526 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
527 Log.i(this, "Not attempting to block incoming call due to recent emergency call");
528 return false;
529 }
530 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
531 return false;
532 }
533 return true;
534 }
535
536 /**
537 * Checks whether a call should be blocked, and blocks it if so. Otherwise, it adds the call to
538 * the CallList so it can proceed as normal. There is a timeout, so if the function for checking
539 * whether a function is blocked does not return in a reasonable time, we proceed with adding the
540 * call anyways.
541 */
542 private void maybeBlockCall(final android.telecom.Call call, final LatencyReport latencyReport) {
543 final String countryIso = GeoUtil.getCurrentCountryIso(mContext);
544 final String number = TelecomCallUtil.getNumber(call);
545 final long timeAdded = System.currentTimeMillis();
546
547 // Though AtomicBoolean's can be scary, don't fear, as in this case it is only used on the
548 // main UI thread. It is needed so we can change its value within different scopes, since
549 // that cannot be done with a final boolean.
550 final AtomicBoolean hasTimedOut = new AtomicBoolean(false);
551
552 final Handler handler = new Handler();
553
554 // Proceed if the query is slow; the call may still be blocked after the query returns.
555 final Runnable runnable =
556 new Runnable() {
557 @Override
558 public void run() {
559 hasTimedOut.set(true);
560 latencyReport.onCallBlockingDone();
561 mCallList.onCallAdded(mContext, call, latencyReport);
562 }
563 };
564 handler.postDelayed(runnable, BLOCK_QUERY_TIMEOUT_MS);
565
566 OnCheckBlockedListener onCheckBlockedListener =
567 new OnCheckBlockedListener() {
568 @Override
569 public void onCheckComplete(final Integer id) {
570 if (isReadyForTearDown()) {
571 Log.i(this, "InCallPresenter is torn down, not adding call");
572 return;
573 }
574 if (!hasTimedOut.get()) {
575 handler.removeCallbacks(runnable);
576 }
577 if (id == null) {
578 if (!hasTimedOut.get()) {
579 latencyReport.onCallBlockingDone();
580 mCallList.onCallAdded(mContext, call, latencyReport);
581 }
582 } else if (id == FilteredNumberAsyncQueryHandler.INVALID_ID) {
583 Log.d(this, "checkForBlockedCall: invalid number, skipping block checking");
584 if (!hasTimedOut.get()) {
585 handler.removeCallbacks(runnable);
586
587 latencyReport.onCallBlockingDone();
588 mCallList.onCallAdded(mContext, call, latencyReport);
589 }
590 } else {
591 Log.i(this, "Rejecting incoming call from blocked number");
592 call.reject(false, null);
593 Logger.get(mContext).logInteraction(InteractionEvent.Type.CALL_BLOCKED);
594
595 /*
596 * If mContext is null, then the InCallPresenter was torn down before the
597 * block check had a chance to complete. The context is no longer valid, so
598 * don't attempt to remove the call log entry.
599 */
600 if (mContext == null) {
601 return;
602 }
603 // Register observer to update the call log.
604 // BlockedNumberContentObserver will unregister after successful log or timeout.
605 BlockedNumberContentObserver contentObserver =
606 new BlockedNumberContentObserver(mContext, new Handler(), number, timeAdded);
607 contentObserver.register();
608 }
609 }
610 };
611
612 mFilteredQueryHandler.isBlockedNumber(onCheckBlockedListener, number, countryIso);
613 }
614
615 public void onCallRemoved(android.telecom.Call call) {
616 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
617 mExternalCallList.onCallRemoved(call);
618 } else {
619 mCallList.onCallRemoved(mContext, call);
620 call.unregisterCallback(mCallCallback);
621 }
622 }
623
624 public void onCanAddCallChanged(boolean canAddCall) {
625 for (CanAddCallListener listener : mCanAddCallListeners) {
626 listener.onCanAddCallChanged(canAddCall);
627 }
628 }
629
630 @Override
631 public void onWiFiToLteHandover(DialerCall call) {
632 if (mInCallActivity != null) {
633 mInCallActivity.onWiFiToLteHandover(call);
634 }
635 }
636
637 @Override
638 public void onHandoverToWifiFailed(DialerCall call) {
639 if (mInCallActivity != null) {
640 mInCallActivity.onHandoverToWifiFailed(call);
641 }
642 }
643
644 /**
645 * Called when there is a change to the call list. Sets the In-Call state for the entire in-call
646 * app based on the information it gets from CallList. Dispatches the in-call state to all
647 * listeners. Can trigger the creation or destruction of the UI based on the states that is
648 * calculates.
649 */
650 @Override
651 public void onCallListChange(CallList callList) {
652 if (mInCallActivity != null && mInCallActivity.isInCallScreenAnimating()) {
653 mAwaitingCallListUpdate = true;
654 return;
655 }
656 if (callList == null) {
657 return;
658 }
659
660 mAwaitingCallListUpdate = false;
661
662 InCallState newState = getPotentialStateFromCallList(callList);
663 InCallState oldState = mInCallState;
664 Log.d(this, "onCallListChange oldState= " + oldState + " newState=" + newState);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700665
666 // If the user placed a call and was asked to choose the account, but then pressed "Home", the
667 // incall activity for that call will still exist (even if it's not visible). In the case of
668 // an incoming call in that situation, just disconnect that "waiting for account" call and
669 // dismiss the dialog. The same activity will be reused to handle the new incoming call. See
670 // b/33247755 for more details.
671 DialerCall waitingForAccountCall;
672 if (newState == InCallState.INCOMING
673 && (waitingForAccountCall = callList.getWaitingForAccountCall()) != null) {
674 waitingForAccountCall.disconnect();
675 mInCallActivity.dismissPendingDialogs();
676 }
677
Eric Erfanianccca3152017-02-22 16:32:36 -0800678 newState = startOrFinishUi(newState);
679 Log.d(this, "onCallListChange newState changed to " + newState);
680
681 // Set the new state before announcing it to the world
682 Log.i(this, "Phone switching state: " + oldState + " -> " + newState);
683 mInCallState = newState;
684
685 // notify listeners of new state
686 for (InCallStateListener listener : mListeners) {
687 Log.d(this, "Notify " + listener + " of state " + mInCallState.toString());
688 listener.onStateChange(oldState, mInCallState, callList);
689 }
690
691 if (isActivityStarted()) {
692 final boolean hasCall =
693 callList.getActiveOrBackgroundCall() != null || callList.getOutgoingCall() != null;
694 mInCallActivity.dismissKeyguard(hasCall);
695 }
696 }
697
698 /** Called when there is a new incoming call. */
699 @Override
700 public void onIncomingCall(DialerCall call) {
701 InCallState newState = startOrFinishUi(InCallState.INCOMING);
702 InCallState oldState = mInCallState;
703
704 Log.i(this, "Phone switching state: " + oldState + " -> " + newState);
705 mInCallState = newState;
706
707 for (IncomingCallListener listener : mIncomingCallListeners) {
708 listener.onIncomingCall(oldState, mInCallState, call);
709 }
710
711 if (mInCallActivity != null) {
712 // Re-evaluate which fragment is being shown.
713 mInCallActivity.onPrimaryCallStateChanged();
714 }
715 }
716
717 @Override
718 public void onUpgradeToVideo(DialerCall call) {
Eric Erfanian90508232017-03-24 09:31:16 -0700719 if (VideoUtils.hasReceivedVideoUpgradeRequest(call.getVideoTech().getSessionModificationState())
Eric Erfanianccca3152017-02-22 16:32:36 -0800720 && mInCallState == InCallPresenter.InCallState.INCOMING) {
721 LogUtil.i(
722 "InCallPresenter.onUpgradeToVideo",
723 "rejecting upgrade request due to existing incoming call");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700724 call.getVideoTech().declineVideoRequest();
Eric Erfanianccca3152017-02-22 16:32:36 -0800725 }
726
727 if (mInCallActivity != null) {
728 // Re-evaluate which fragment is being shown.
729 mInCallActivity.onPrimaryCallStateChanged();
730 }
731 }
732
733 @Override
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700734 public void onSessionModificationStateChange(DialerCall call) {
735 int newState = call.getVideoTech().getSessionModificationState();
Eric Erfanianccca3152017-02-22 16:32:36 -0800736 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "state: %d", newState);
737 if (mProximitySensor == null) {
738 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "proximitySensor is null");
739 return;
740 }
741 mProximitySensor.setIsAttemptingVideoCall(
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700742 call.hasSentVideoUpgradeRequest() || call.hasReceivedVideoUpgradeRequest());
Eric Erfanianccca3152017-02-22 16:32:36 -0800743 if (mInCallActivity != null) {
744 // Re-evaluate which fragment is being shown.
745 mInCallActivity.onPrimaryCallStateChanged();
746 }
747 }
748
749 /**
750 * Called when a call becomes disconnected. Called everytime an existing call changes from being
751 * connected (incoming/outgoing/active) to disconnected.
752 */
753 @Override
754 public void onDisconnect(DialerCall call) {
755 maybeShowErrorDialogOnDisconnect(call);
756
757 // We need to do the run the same code as onCallListChange.
758 onCallListChange(mCallList);
759
760 if (isActivityStarted()) {
761 mInCallActivity.dismissKeyguard(false);
762 }
763
764 if (call.isEmergencyCall()) {
765 FilteredNumbersUtil.recordLastEmergencyCallTime(mContext);
766 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800767
Eric Erfanianfc37b022017-03-21 10:11:17 -0700768 if (!mCallList.hasLiveCall()
769 && !call.getLogState().isIncoming
Eric Erfanian10b34a52017-05-04 08:23:17 -0700770 && !isSecretCode(call.getNumber())
Eric Erfanianfc37b022017-03-21 10:11:17 -0700771 && !CallerInfoUtils.isVoiceMailNumber(mContext, call)) {
Eric Erfanian10b34a52017-05-04 08:23:17 -0700772 PostCall.onCallDisconnected(mContext, call.getNumber(), call.getConnectTimeMillis());
Eric Erfanianccca3152017-02-22 16:32:36 -0800773 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800774 }
775
Eric Erfanian10b34a52017-05-04 08:23:17 -0700776 private boolean isSecretCode(@Nullable String number) {
777 return number != null
778 && (number.length() <= 8 || number.startsWith("*#*#") || number.endsWith("#*#*"));
779 }
780
Eric Erfanianccca3152017-02-22 16:32:36 -0800781 /** Given the call list, return the state in which the in-call screen should be. */
782 public InCallState getPotentialStateFromCallList(CallList callList) {
783
784 InCallState newState = InCallState.NO_CALLS;
785
786 if (callList == null) {
787 return newState;
788 }
789 if (callList.getIncomingCall() != null) {
790 newState = InCallState.INCOMING;
791 } else if (callList.getWaitingForAccountCall() != null) {
792 newState = InCallState.WAITING_FOR_ACCOUNT;
793 } else if (callList.getPendingOutgoingCall() != null) {
794 newState = InCallState.PENDING_OUTGOING;
795 } else if (callList.getOutgoingCall() != null) {
796 newState = InCallState.OUTGOING;
797 } else if (callList.getActiveCall() != null
798 || callList.getBackgroundCall() != null
799 || callList.getDisconnectedCall() != null
800 || callList.getDisconnectingCall() != null) {
801 newState = InCallState.INCALL;
802 }
803
804 if (newState == InCallState.NO_CALLS) {
805 if (mBoundAndWaitingForOutgoingCall) {
806 return InCallState.OUTGOING;
807 }
808 }
809
810 return newState;
811 }
812
813 public boolean isBoundAndWaitingForOutgoingCall() {
814 return mBoundAndWaitingForOutgoingCall;
815 }
816
817 public void setBoundAndWaitingForOutgoingCall(boolean isBound, PhoneAccountHandle handle) {
818 Log.i(this, "setBoundAndWaitingForOutgoingCall: " + isBound);
819 mBoundAndWaitingForOutgoingCall = isBound;
820 mThemeColorManager.setPendingPhoneAccountHandle(handle);
821 if (isBound && mInCallState == InCallState.NO_CALLS) {
822 mInCallState = InCallState.OUTGOING;
823 }
824 }
825
826 public void onShrinkAnimationComplete() {
827 if (mAwaitingCallListUpdate) {
828 onCallListChange(mCallList);
829 }
830 }
831
832 public void addIncomingCallListener(IncomingCallListener listener) {
833 Objects.requireNonNull(listener);
834 mIncomingCallListeners.add(listener);
835 }
836
837 public void removeIncomingCallListener(IncomingCallListener listener) {
838 if (listener != null) {
839 mIncomingCallListeners.remove(listener);
840 }
841 }
842
843 public void addListener(InCallStateListener listener) {
844 Objects.requireNonNull(listener);
845 mListeners.add(listener);
846 }
847
848 public void removeListener(InCallStateListener listener) {
849 if (listener != null) {
850 mListeners.remove(listener);
851 }
852 }
853
854 public void addDetailsListener(InCallDetailsListener listener) {
855 Objects.requireNonNull(listener);
856 mDetailsListeners.add(listener);
857 }
858
859 public void removeDetailsListener(InCallDetailsListener listener) {
860 if (listener != null) {
861 mDetailsListeners.remove(listener);
862 }
863 }
864
865 public void addCanAddCallListener(CanAddCallListener listener) {
866 Objects.requireNonNull(listener);
867 mCanAddCallListeners.add(listener);
868 }
869
870 public void removeCanAddCallListener(CanAddCallListener listener) {
871 if (listener != null) {
872 mCanAddCallListeners.remove(listener);
873 }
874 }
875
876 public void addOrientationListener(InCallOrientationListener listener) {
877 Objects.requireNonNull(listener);
878 mOrientationListeners.add(listener);
879 }
880
881 public void removeOrientationListener(InCallOrientationListener listener) {
882 if (listener != null) {
883 mOrientationListeners.remove(listener);
884 }
885 }
886
887 public void addInCallEventListener(InCallEventListener listener) {
888 Objects.requireNonNull(listener);
889 mInCallEventListeners.add(listener);
890 }
891
892 public void removeInCallEventListener(InCallEventListener listener) {
893 if (listener != null) {
894 mInCallEventListeners.remove(listener);
895 }
896 }
897
898 public ProximitySensor getProximitySensor() {
899 return mProximitySensor;
900 }
901
902 public PseudoScreenState getPseudoScreenState() {
903 return mPseudoScreenState;
904 }
905
906 /** Returns true if the incall app is the foreground application. */
907 public boolean isShowingInCallUi() {
908 if (!isActivityStarted()) {
909 return false;
910 }
911 if (mManageConferenceActivity != null && mManageConferenceActivity.isVisible()) {
912 return true;
913 }
914 return mInCallActivity.isVisible();
915 }
916
917 /**
918 * Returns true if the activity has been created and is running. Returns true as long as activity
919 * is not destroyed or finishing. This ensures that we return true even if the activity is paused
920 * (not in foreground).
921 */
922 public boolean isActivityStarted() {
923 return (mInCallActivity != null
924 && !mInCallActivity.isDestroyed()
925 && !mInCallActivity.isFinishing());
926 }
927
928 /**
929 * Determines if the In-Call app is currently changing configuration.
930 *
931 * @return {@code true} if the In-Call app is changing configuration.
932 */
933 public boolean isChangingConfigurations() {
934 return mIsChangingConfigurations;
935 }
936
937 /**
938 * Tracks whether the In-Call app is currently in the process of changing configuration (i.e.
939 * screen orientation).
940 */
941 /*package*/
942 void updateIsChangingConfigurations() {
943 mIsChangingConfigurations = false;
944 if (mInCallActivity != null) {
945 mIsChangingConfigurations = mInCallActivity.isChangingConfigurations();
946 }
947 Log.v(this, "updateIsChangingConfigurations = " + mIsChangingConfigurations);
948 }
949
950 /** Called when the activity goes in/out of the foreground. */
951 public void onUiShowing(boolean showing) {
952 // We need to update the notification bar when we leave the UI because that
953 // could trigger it to show again.
954 if (mStatusBarNotifier != null) {
955 mStatusBarNotifier.updateNotification(mCallList);
956 }
957
958 if (mProximitySensor != null) {
959 mProximitySensor.onInCallShowing(showing);
960 }
961
962 Intent broadcastIntent = Bindings.get(mContext).getUiReadyBroadcastIntent(mContext);
963 if (broadcastIntent != null) {
964 broadcastIntent.putExtra(EXTRA_FIRST_TIME_SHOWN, !mIsActivityPreviouslyStarted);
965
966 if (showing) {
967 Log.d(this, "Sending sticky broadcast: ", broadcastIntent);
968 mContext.sendStickyBroadcast(broadcastIntent);
969 } else {
970 Log.d(this, "Removing sticky broadcast: ", broadcastIntent);
971 mContext.removeStickyBroadcast(broadcastIntent);
972 }
973 }
974
975 if (showing) {
976 mIsActivityPreviouslyStarted = true;
977 } else {
978 updateIsChangingConfigurations();
979 }
980
981 for (InCallUiListener listener : mInCallUiListeners) {
982 listener.onUiShowing(showing);
983 }
984
985 if (mInCallActivity != null) {
986 // Re-evaluate which fragment is being shown.
987 mInCallActivity.onPrimaryCallStateChanged();
988 }
989 }
990
991 public void addInCallUiListener(InCallUiListener listener) {
992 mInCallUiListeners.add(listener);
993 }
994
995 public boolean removeInCallUiListener(InCallUiListener listener) {
996 return mInCallUiListeners.remove(listener);
997 }
998
999 /*package*/
1000 void onActivityStarted() {
1001 Log.d(this, "onActivityStarted");
1002 notifyVideoPauseController(true);
Eric Erfaniand8046e52017-04-06 09:41:50 -07001003 if (mStatusBarNotifier != null) {
1004 // TODO - b/36649622: Investigate this redundant call
1005 mStatusBarNotifier.updateNotification(mCallList);
1006 }
Eric Erfanianccca3152017-02-22 16:32:36 -08001007 }
1008
1009 /*package*/
1010 void onActivityStopped() {
1011 Log.d(this, "onActivityStopped");
1012 notifyVideoPauseController(false);
1013 }
1014
1015 private void notifyVideoPauseController(boolean showing) {
1016 Log.d(
1017 this, "notifyVideoPauseController: mIsChangingConfigurations=" + mIsChangingConfigurations);
1018 if (!mIsChangingConfigurations) {
1019 VideoPauseController.getInstance().onUiShowing(showing);
1020 }
1021 }
1022
1023 /** Brings the app into the foreground if possible. */
1024 public void bringToForeground(boolean showDialpad) {
1025 // Before we bring the incall UI to the foreground, we check to see if:
1026 // 1. It is not currently in the foreground
1027 // 2. We are in a state where we want to show the incall ui (i.e. there are calls to
1028 // be displayed)
1029 // If the activity hadn't actually been started previously, yet there are still calls
1030 // present (e.g. a call was accepted by a bluetooth or wired headset), we want to
1031 // bring it up the UI regardless.
1032 if (!isShowingInCallUi() && mInCallState != InCallState.NO_CALLS) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001033 showInCall(showDialpad, false /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001034 }
1035 }
1036
1037 public void onPostDialCharWait(String callId, String chars) {
1038 if (isActivityStarted()) {
1039 mInCallActivity.showPostCharWaitDialog(callId, chars);
1040 }
1041 }
1042
1043 /**
1044 * Handles the green CALL key while in-call.
1045 *
1046 * @return true if we consumed the event.
1047 */
1048 public boolean handleCallKey() {
1049 LogUtil.v("InCallPresenter.handleCallKey", null);
1050
1051 // The green CALL button means either "Answer", "Unhold", or
1052 // "Swap calls", or can be a no-op, depending on the current state
1053 // of the Phone.
1054
1055 /** INCOMING CALL */
1056 final CallList calls = mCallList;
1057 final DialerCall incomingCall = calls.getIncomingCall();
1058 LogUtil.v("InCallPresenter.handleCallKey", "incomingCall: " + incomingCall);
1059
1060 // (1) Attempt to answer a call
1061 if (incomingCall != null) {
1062 incomingCall.answer(VideoProfile.STATE_AUDIO_ONLY);
1063 return true;
1064 }
1065
1066 /** STATE_ACTIVE CALL */
1067 final DialerCall activeCall = calls.getActiveCall();
1068 if (activeCall != null) {
1069 // TODO: This logic is repeated from CallButtonPresenter.java. We should
1070 // consolidate this logic.
1071 final boolean canMerge =
1072 activeCall.can(android.telecom.Call.Details.CAPABILITY_MERGE_CONFERENCE);
1073 final boolean canSwap =
1074 activeCall.can(android.telecom.Call.Details.CAPABILITY_SWAP_CONFERENCE);
1075
1076 Log.v(
1077 this, "activeCall: " + activeCall + ", canMerge: " + canMerge + ", canSwap: " + canSwap);
1078
1079 // (2) Attempt actions on conference calls
1080 if (canMerge) {
1081 TelecomAdapter.getInstance().merge(activeCall.getId());
1082 return true;
1083 } else if (canSwap) {
1084 TelecomAdapter.getInstance().swap(activeCall.getId());
1085 return true;
1086 }
1087 }
1088
1089 /** BACKGROUND CALL */
1090 final DialerCall heldCall = calls.getBackgroundCall();
1091 if (heldCall != null) {
1092 // We have a hold call so presumeable it will always support HOLD...but
1093 // there is no harm in double checking.
1094 final boolean canHold = heldCall.can(android.telecom.Call.Details.CAPABILITY_HOLD);
1095
1096 Log.v(this, "heldCall: " + heldCall + ", canHold: " + canHold);
1097
1098 // (4) unhold call
1099 if (heldCall.getState() == DialerCall.State.ONHOLD && canHold) {
1100 heldCall.unhold();
1101 return true;
1102 }
1103 }
1104
1105 // Always consume hard keys
1106 return true;
1107 }
1108
1109 /**
1110 * A dialog could have prevented in-call screen from being previously finished. This function
1111 * checks to see if there should be any UI left and if not attempts to tear down the UI.
1112 */
1113 public void onDismissDialog() {
1114 Log.i(this, "Dialog dismissed");
1115 if (mInCallState == InCallState.NO_CALLS) {
1116 attemptFinishActivity();
1117 attemptCleanup();
1118 }
1119 }
1120
1121 /** Clears the previous fullscreen state. */
1122 public void clearFullscreen() {
1123 mIsFullScreen = false;
1124 }
1125
1126 /**
1127 * Changes the fullscreen mode of the in-call UI.
1128 *
1129 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1130 * otherwise.
1131 */
1132 public void setFullScreen(boolean isFullScreen) {
1133 setFullScreen(isFullScreen, false /* force */);
1134 }
1135
1136 /**
1137 * Changes the fullscreen mode of the in-call UI.
1138 *
1139 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1140 * otherwise.
1141 * @param force {@code true} if fullscreen mode should be set regardless of its current state.
1142 */
1143 public void setFullScreen(boolean isFullScreen, boolean force) {
1144 Log.i(this, "setFullScreen = " + isFullScreen);
1145
1146 // As a safeguard, ensure we cannot enter fullscreen if the dialpad is shown.
1147 if (isDialpadVisible()) {
1148 isFullScreen = false;
1149 Log.v(this, "setFullScreen overridden as dialpad is shown = " + isFullScreen);
1150 }
1151
1152 if (mIsFullScreen == isFullScreen && !force) {
1153 Log.v(this, "setFullScreen ignored as already in that state.");
1154 return;
1155 }
1156 mIsFullScreen = isFullScreen;
1157 notifyFullscreenModeChange(mIsFullScreen);
1158 }
1159
1160 /**
1161 * @return {@code true} if the in-call ui is currently in fullscreen mode, {@code false}
1162 * otherwise.
1163 */
1164 public boolean isFullscreen() {
1165 return mIsFullScreen;
1166 }
1167
1168 /**
1169 * Called by the {@link VideoCallPresenter} to inform of a change in full screen video status.
1170 *
1171 * @param isFullscreenMode {@code True} if entering full screen mode.
1172 */
1173 public void notifyFullscreenModeChange(boolean isFullscreenMode) {
1174 for (InCallEventListener listener : mInCallEventListeners) {
1175 listener.onFullscreenModeChanged(isFullscreenMode);
1176 }
1177 }
1178
1179 /**
1180 * For some disconnected causes, we show a dialog. This calls into the activity to show the dialog
1181 * if appropriate for the call.
1182 */
1183 private void maybeShowErrorDialogOnDisconnect(DialerCall call) {
1184 // For newly disconnected calls, we may want to show a dialog on specific error conditions
1185 if (isActivityStarted() && call.getState() == DialerCall.State.DISCONNECTED) {
1186 if (call.getAccountHandle() == null && !call.isConferenceCall()) {
1187 setDisconnectCauseForMissingAccounts(call);
1188 }
1189 mInCallActivity.maybeShowErrorDialogOnDisconnect(call.getDisconnectCause());
1190 }
1191 }
1192
1193 /**
1194 * When the state of in-call changes, this is the first method to get called. It determines if the
1195 * UI needs to be started or finished depending on the new state and does it.
1196 */
1197 private InCallState startOrFinishUi(InCallState newState) {
1198 Log.d(this, "startOrFinishUi: " + mInCallState + " -> " + newState);
1199
1200 // TODO: Consider a proper state machine implementation
1201
1202 // If the state isn't changing we have already done any starting/stopping of activities in
1203 // a previous pass...so lets cut out early
1204 if (newState == mInCallState) {
1205 return newState;
1206 }
1207
1208 // A new Incoming call means that the user needs to be notified of the the call (since
1209 // it wasn't them who initiated it). We do this through full screen notifications and
1210 // happens indirectly through {@link StatusBarNotifier}.
1211 //
1212 // The process for incoming calls is as follows:
1213 //
1214 // 1) CallList - Announces existence of new INCOMING call
1215 // 2) InCallPresenter - Gets announcement and calculates that the new InCallState
1216 // - should be set to INCOMING.
1217 // 3) InCallPresenter - This method is called to see if we need to start or finish
1218 // the app given the new state.
1219 // 4) StatusBarNotifier - Listens to InCallState changes. InCallPresenter calls
1220 // StatusBarNotifier explicitly to issue a FullScreen Notification
1221 // that will either start the InCallActivity or show the user a
1222 // top-level notification dialog if the user is in an immersive app.
1223 // That notification can also start the InCallActivity.
1224 // 5) InCallActivity - Main activity starts up and at the end of its onCreate will
1225 // call InCallPresenter::setActivity() to let the presenter
1226 // know that start-up is complete.
1227 //
1228 // [ AND NOW YOU'RE IN THE CALL. voila! ]
1229 //
1230 // Our app is started using a fullScreen notification. We need to do this whenever
1231 // we get an incoming call. Depending on the current context of the device, either a
1232 // incoming call HUN or the actual InCallActivity will be shown.
1233 final boolean startIncomingCallSequence = (InCallState.INCOMING == newState);
1234
1235 // A dialog to show on top of the InCallUI to select a PhoneAccount
1236 final boolean showAccountPicker = (InCallState.WAITING_FOR_ACCOUNT == newState);
1237
1238 // A new outgoing call indicates that the user just now dialed a number and when that
1239 // happens we need to display the screen immediately or show an account picker dialog if
1240 // no default is set. However, if the main InCallUI is already visible, we do not want to
1241 // re-initiate the start-up animation, so we do not need to do anything here.
1242 //
1243 // It is also possible to go into an intermediate state where the call has been initiated
1244 // but Telecom has not yet returned with the details of the call (handle, gateway, etc.).
1245 // This pending outgoing state can also launch the call screen.
1246 //
1247 // This is different from the incoming call sequence because we do not need to shock the
1248 // user with a top-level notification. Just show the call UI normally.
1249 boolean callCardFragmentVisible =
1250 mInCallActivity != null && mInCallActivity.getCallCardFragmentVisible();
1251 final boolean mainUiNotVisible = !isShowingInCallUi() || !callCardFragmentVisible;
1252 boolean showCallUi = InCallState.OUTGOING == newState && mainUiNotVisible;
1253
1254 // Direct transition from PENDING_OUTGOING -> INCALL means that there was an error in the
1255 // outgoing call process, so the UI should be brought up to show an error dialog.
1256 showCallUi |=
1257 (InCallState.PENDING_OUTGOING == mInCallState
1258 && InCallState.INCALL == newState
1259 && !isShowingInCallUi());
1260
1261 // Another exception - InCallActivity is in charge of disconnecting a call with no
1262 // valid accounts set. Bring the UI up if this is true for the current pending outgoing
1263 // call so that:
1264 // 1) The call can be disconnected correctly
1265 // 2) The UI comes up and correctly displays the error dialog.
1266 // TODO: Remove these special case conditions by making InCallPresenter a true state
1267 // machine. Telecom should also be the component responsible for disconnecting a call
1268 // with no valid accounts.
1269 showCallUi |=
1270 InCallState.PENDING_OUTGOING == newState
1271 && mainUiNotVisible
1272 && isCallWithNoValidAccounts(mCallList.getPendingOutgoingCall());
1273
1274 // The only time that we have an instance of mInCallActivity and it isn't started is
1275 // when it is being destroyed. In that case, lets avoid bringing up another instance of
1276 // the activity. When it is finally destroyed, we double check if we should bring it back
1277 // up so we aren't going to lose anything by avoiding a second startup here.
1278 boolean activityIsFinishing = mInCallActivity != null && !isActivityStarted();
1279 if (activityIsFinishing) {
1280 Log.i(this, "Undo the state change: " + newState + " -> " + mInCallState);
1281 return mInCallState;
1282 }
1283
1284 // We're about the bring up the in-call UI for outgoing and incoming call. If we still have
1285 // dialogs up, we need to clear them out before showing in-call screen. This is necessary
1286 // to fix the bug that dialog will show up when data reaches limit even after makeing new
1287 // outgoing call after user ignore it by pressing home button.
1288 if ((newState == InCallState.INCOMING || newState == InCallState.PENDING_OUTGOING)
1289 && !showCallUi
1290 && isActivityStarted()) {
1291 mInCallActivity.dismissPendingDialogs();
1292 }
1293
1294 if (showCallUi || showAccountPicker) {
1295 Log.i(this, "Start in call UI");
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001296 showInCall(false /* showDialpad */, !showAccountPicker /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001297 } else if (startIncomingCallSequence) {
1298 Log.i(this, "Start Full Screen in call UI");
1299
Eric Erfaniand8046e52017-04-06 09:41:50 -07001300 mStatusBarNotifier.updateNotification(mCallList);
Eric Erfanianccca3152017-02-22 16:32:36 -08001301 } else if (newState == InCallState.NO_CALLS) {
1302 // The new state is the no calls state. Tear everything down.
1303 attemptFinishActivity();
1304 attemptCleanup();
1305 }
1306
1307 return newState;
1308 }
1309
1310 /**
1311 * Sets the DisconnectCause for a call that was disconnected because it was missing a PhoneAccount
1312 * or PhoneAccounts to select from.
1313 */
1314 private void setDisconnectCauseForMissingAccounts(DialerCall call) {
1315
1316 Bundle extras = call.getIntentExtras();
1317 // Initialize the extras bundle to avoid NPE
1318 if (extras == null) {
1319 extras = new Bundle();
1320 }
1321
1322 final List<PhoneAccountHandle> phoneAccountHandles =
1323 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
1324
1325 if (phoneAccountHandles == null || phoneAccountHandles.isEmpty()) {
1326 String scheme = call.getHandle().getScheme();
1327 final String errorMsg =
1328 PhoneAccount.SCHEME_TEL.equals(scheme)
1329 ? mContext.getString(R.string.callFailed_simError)
1330 : mContext.getString(R.string.incall_error_supp_service_unknown);
1331 DisconnectCause disconnectCause =
1332 new DisconnectCause(DisconnectCause.ERROR, null, errorMsg, errorMsg);
1333 call.setDisconnectCause(disconnectCause);
1334 }
1335 }
1336
Eric Erfanianccca3152017-02-22 16:32:36 -08001337 /**
1338 * @return {@code true} if the InCallPresenter is ready to be torn down, {@code false} otherwise.
1339 * Calling classes should use this as an indication whether to interact with the
1340 * InCallPresenter or not.
1341 */
1342 public boolean isReadyForTearDown() {
1343 return mInCallActivity == null && !mServiceConnected && mInCallState == InCallState.NO_CALLS;
1344 }
1345
1346 /**
1347 * Checks to see if both the UI is gone and the service is disconnected. If so, tear it all down.
1348 */
1349 private void attemptCleanup() {
1350 if (isReadyForTearDown()) {
1351 Log.i(this, "Cleaning up");
1352
1353 cleanupSurfaces();
1354
1355 mIsActivityPreviouslyStarted = false;
1356 mIsChangingConfigurations = false;
1357
1358 // blow away stale contact info so that we get fresh data on
1359 // the next set of calls
1360 if (mContactInfoCache != null) {
1361 mContactInfoCache.clearCache();
1362 }
1363 mContactInfoCache = null;
1364
1365 if (mProximitySensor != null) {
1366 removeListener(mProximitySensor);
1367 mProximitySensor.tearDown();
1368 }
1369 mProximitySensor = null;
1370
1371 if (mStatusBarNotifier != null) {
1372 removeListener(mStatusBarNotifier);
Eric Erfaniand8046e52017-04-06 09:41:50 -07001373 EnrichedCallComponent.get(mContext)
1374 .getEnrichedCallManager()
1375 .unregisterStateChangedListener(mStatusBarNotifier);
Eric Erfanianccca3152017-02-22 16:32:36 -08001376 }
Eric Erfaniand8046e52017-04-06 09:41:50 -07001377
Eric Erfanianccca3152017-02-22 16:32:36 -08001378 if (mExternalCallNotifier != null && mExternalCallList != null) {
1379 mExternalCallList.removeExternalCallListener(mExternalCallNotifier);
1380 }
1381 mStatusBarNotifier = null;
1382
1383 if (mCallList != null) {
1384 mCallList.removeListener(this);
1385 mCallList.removeListener(mSpamCallListListener);
1386 }
1387 mCallList = null;
1388
1389 mContext = null;
1390 mInCallActivity = null;
1391 mManageConferenceActivity = null;
1392
1393 mListeners.clear();
1394 mIncomingCallListeners.clear();
1395 mDetailsListeners.clear();
1396 mCanAddCallListeners.clear();
1397 mOrientationListeners.clear();
1398 mInCallEventListeners.clear();
1399 mInCallUiListeners.clear();
1400
1401 Log.d(this, "Finished InCallPresenter.CleanUp");
1402 }
1403 }
1404
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001405 public void showInCall(boolean showDialpad, boolean newOutgoingCall) {
Eric Erfanianccca3152017-02-22 16:32:36 -08001406 Log.i(this, "Showing InCallActivity");
1407 mContext.startActivity(
1408 InCallActivity.getIntent(
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001409 mContext, showDialpad, newOutgoingCall, false /* forFullScreen */));
Eric Erfanianccca3152017-02-22 16:32:36 -08001410 }
1411
1412 public void onServiceBind() {
1413 mServiceBound = true;
1414 }
1415
1416 public void onServiceUnbind() {
1417 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(false, null);
1418 mServiceBound = false;
1419 }
1420
1421 public boolean isServiceBound() {
1422 return mServiceBound;
1423 }
1424
1425 public void maybeStartRevealAnimation(Intent intent) {
1426 if (intent == null || mInCallActivity != null) {
1427 return;
1428 }
1429 final Bundle extras = intent.getBundleExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS);
1430 if (extras == null) {
1431 // Incoming call, just show the in-call UI directly.
1432 return;
1433 }
1434
1435 if (extras.containsKey(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS)) {
1436 // Account selection dialog will show up so don't show the animation.
1437 return;
1438 }
1439
1440 final PhoneAccountHandle accountHandle =
1441 intent.getParcelableExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
1442 final Point touchPoint = extras.getParcelable(TouchPointManager.TOUCH_POINT);
Eric Erfanianccca3152017-02-22 16:32:36 -08001443
1444 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(true, accountHandle);
1445
1446 final Intent activityIntent =
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001447 InCallActivity.getIntent(mContext, false, true, false /* forFullScreen */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001448 activityIntent.putExtra(TouchPointManager.TOUCH_POINT, touchPoint);
1449 mContext.startActivity(activityIntent);
1450 }
1451
1452 /**
1453 * Retrieves the current in-call camera manager instance, creating if necessary.
1454 *
1455 * @return The {@link InCallCameraManager}.
1456 */
1457 public InCallCameraManager getInCallCameraManager() {
1458 synchronized (this) {
1459 if (mInCallCameraManager == null) {
1460 mInCallCameraManager = new InCallCameraManager(mContext);
1461 }
1462
1463 return mInCallCameraManager;
1464 }
1465 }
1466
1467 /**
1468 * Notifies listeners of changes in orientation and notify calls of rotation angle change.
1469 *
1470 * @param orientation The screen orientation of the device (one of: {@link
1471 * InCallOrientationEventListener#SCREEN_ORIENTATION_0}, {@link
1472 * InCallOrientationEventListener#SCREEN_ORIENTATION_90}, {@link
1473 * InCallOrientationEventListener#SCREEN_ORIENTATION_180}, {@link
1474 * InCallOrientationEventListener#SCREEN_ORIENTATION_270}).
1475 */
1476 public void onDeviceOrientationChange(@ScreenOrientation int orientation) {
1477 Log.d(this, "onDeviceOrientationChange: orientation= " + orientation);
1478
1479 if (mCallList != null) {
1480 mCallList.notifyCallsOfDeviceRotation(orientation);
1481 } else {
1482 Log.w(this, "onDeviceOrientationChange: CallList is null.");
1483 }
1484
1485 // Notify listeners of device orientation changed.
1486 for (InCallOrientationListener listener : mOrientationListeners) {
1487 listener.onDeviceOrientationChanged(orientation);
1488 }
1489 }
1490
1491 /**
1492 * Configures the in-call UI activity so it can change orientations or not. Enables the
1493 * orientation event listener if allowOrientationChange is true, disables it if false.
1494 *
1495 * @param allowOrientationChange {@code true} if the in-call UI can change between portrait and
1496 * landscape. {@code false} if the in-call UI should be locked in portrait.
1497 */
1498 public void setInCallAllowsOrientationChange(boolean allowOrientationChange) {
1499 if (mInCallActivity == null) {
1500 Log.e(this, "InCallActivity is null. Can't set requested orientation.");
1501 return;
1502 }
1503 mInCallActivity.setAllowOrientationChange(allowOrientationChange);
1504 }
1505
1506 public void enableScreenTimeout(boolean enable) {
1507 Log.v(this, "enableScreenTimeout: value=" + enable);
1508 if (mInCallActivity == null) {
1509 Log.e(this, "enableScreenTimeout: InCallActivity is null.");
1510 return;
1511 }
1512
1513 final Window window = mInCallActivity.getWindow();
1514 if (enable) {
1515 window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1516 } else {
1517 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1518 }
1519 }
1520
1521 /**
1522 * Hides or shows the conference manager fragment.
1523 *
1524 * @param show {@code true} if the conference manager should be shown, {@code false} if it should
1525 * be hidden.
1526 */
1527 public void showConferenceCallManager(boolean show) {
1528 if (mInCallActivity != null) {
1529 mInCallActivity.showConferenceFragment(show);
1530 }
1531 if (!show && mManageConferenceActivity != null) {
1532 mManageConferenceActivity.finish();
1533 }
1534 }
1535
1536 /**
1537 * Determines if the dialpad is visible.
1538 *
1539 * @return {@code true} if the dialpad is visible, {@code false} otherwise.
1540 */
1541 public boolean isDialpadVisible() {
1542 if (mInCallActivity == null) {
1543 return false;
1544 }
1545 return mInCallActivity.isDialpadVisible();
1546 }
1547
1548 public ThemeColorManager getThemeColorManager() {
1549 return mThemeColorManager;
1550 }
1551
1552 /** Called when the foreground call changes. */
1553 public void onForegroundCallChanged(DialerCall newForegroundCall) {
1554 mThemeColorManager.onForegroundCallChanged(mContext, newForegroundCall);
1555 if (mInCallActivity != null) {
1556 mInCallActivity.onForegroundCallChanged(newForegroundCall);
1557 }
1558 }
1559
1560 public InCallActivity getActivity() {
1561 return mInCallActivity;
1562 }
1563
1564 /** Called when the UI begins, and starts the callstate callbacks if necessary. */
1565 public void setActivity(InCallActivity inCallActivity) {
1566 if (inCallActivity == null) {
1567 throw new IllegalArgumentException("registerActivity cannot be called with null");
1568 }
1569 if (mInCallActivity != null && mInCallActivity != inCallActivity) {
1570 Log.w(this, "Setting a second activity before destroying the first.");
1571 }
1572 updateActivity(inCallActivity);
1573 }
1574
1575 ExternalCallNotifier getExternalCallNotifier() {
1576 return mExternalCallNotifier;
1577 }
1578
1579 VideoSurfaceTexture getLocalVideoSurfaceTexture() {
1580 if (mLocalVideoSurfaceTexture == null) {
1581 mLocalVideoSurfaceTexture = VideoSurfaceBindings.createLocalVideoSurfaceTexture();
1582 }
1583 return mLocalVideoSurfaceTexture;
1584 }
1585
1586 VideoSurfaceTexture getRemoteVideoSurfaceTexture() {
1587 if (mRemoteVideoSurfaceTexture == null) {
1588 mRemoteVideoSurfaceTexture = VideoSurfaceBindings.createRemoteVideoSurfaceTexture();
1589 }
1590 return mRemoteVideoSurfaceTexture;
1591 }
1592
1593 void cleanupSurfaces() {
1594 if (mRemoteVideoSurfaceTexture != null) {
1595 mRemoteVideoSurfaceTexture.setDoneWithSurface();
1596 mRemoteVideoSurfaceTexture = null;
1597 }
1598 if (mLocalVideoSurfaceTexture != null) {
1599 mLocalVideoSurfaceTexture.setDoneWithSurface();
1600 mLocalVideoSurfaceTexture = null;
1601 }
1602 }
1603
1604 /** All the main states of InCallActivity. */
1605 public enum InCallState {
1606 // InCall Screen is off and there are no calls
1607 NO_CALLS,
1608
1609 // Incoming-call screen is up
1610 INCOMING,
1611
1612 // In-call experience is showing
1613 INCALL,
1614
1615 // Waiting for user input before placing outgoing call
1616 WAITING_FOR_ACCOUNT,
1617
1618 // UI is starting up but no call has been initiated yet.
1619 // The UI is waiting for Telecom to respond.
1620 PENDING_OUTGOING,
1621
1622 // User is dialing out
1623 OUTGOING;
1624
1625 public boolean isIncoming() {
1626 return (this == INCOMING);
1627 }
1628
1629 public boolean isConnectingOrConnected() {
1630 return (this == INCOMING || this == OUTGOING || this == INCALL);
1631 }
1632 }
1633
1634 /** Interface implemented by classes that need to know about the InCall State. */
1635 public interface InCallStateListener {
1636
1637 // TODO: Enhance state to contain the call objects instead of passing CallList
1638 void onStateChange(InCallState oldState, InCallState newState, CallList callList);
1639 }
1640
1641 public interface IncomingCallListener {
1642
1643 void onIncomingCall(InCallState oldState, InCallState newState, DialerCall call);
1644 }
1645
1646 public interface CanAddCallListener {
1647
1648 void onCanAddCallChanged(boolean canAddCall);
1649 }
1650
1651 public interface InCallDetailsListener {
1652
1653 void onDetailsChanged(DialerCall call, android.telecom.Call.Details details);
1654 }
1655
1656 public interface InCallOrientationListener {
1657
1658 void onDeviceOrientationChanged(@ScreenOrientation int orientation);
1659 }
1660
1661 /**
1662 * Interface implemented by classes that need to know about events which occur within the In-Call
1663 * UI. Used as a means of communicating between fragments that make up the UI.
1664 */
1665 public interface InCallEventListener {
1666
1667 void onFullscreenModeChanged(boolean isFullscreenMode);
1668 }
1669
1670 public interface InCallUiListener {
1671
1672 void onUiShowing(boolean showing);
1673 }
1674}