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