blob: db4d88486f5c00c14569c7a54c3b1470e25cfd02 [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;
37import com.android.contacts.common.GeoUtil;
38import com.android.contacts.common.compat.CallCompat;
39import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler;
40import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler.OnCheckBlockedListener;
41import com.android.dialer.blocking.FilteredNumbersUtil;
42import com.android.dialer.common.LogUtil;
43import com.android.dialer.logging.Logger;
44import com.android.dialer.logging.nano.InteractionEvent;
Eric Erfaniand5e47f62017-03-15 14:41:07 -070045import com.android.dialer.postcall.PostCall;
Eric Erfanianccca3152017-02-22 16:32:36 -080046import com.android.dialer.telecom.TelecomUtil;
47import com.android.dialer.util.TouchPointManager;
48import com.android.incallui.InCallOrientationEventListener.ScreenOrientation;
49import com.android.incallui.answerproximitysensor.PseudoScreenState;
50import com.android.incallui.call.CallList;
51import com.android.incallui.call.DialerCall;
Eric Erfanianccca3152017-02-22 16:32:36 -080052import com.android.incallui.call.ExternalCallList;
Eric Erfanianccca3152017-02-22 16:32:36 -080053import com.android.incallui.call.TelecomAdapter;
Eric Erfanianccca3152017-02-22 16:32:36 -080054import com.android.incallui.latencyreport.LatencyReport;
55import com.android.incallui.legacyblocking.BlockedNumberContentObserver;
56import com.android.incallui.spam.SpamCallListListener;
57import com.android.incallui.util.TelecomCallUtil;
58import com.android.incallui.videosurface.bindings.VideoSurfaceBindings;
59import com.android.incallui.videosurface.protocol.VideoSurfaceTexture;
Eric Erfanian90508232017-03-24 09:31:16 -070060import com.android.incallui.videotech.utils.VideoUtils;
Eric Erfanianccca3152017-02-22 16:32:36 -080061import java.util.Collections;
62import java.util.List;
63import java.util.Objects;
64import java.util.Set;
65import java.util.concurrent.ConcurrentHashMap;
66import java.util.concurrent.CopyOnWriteArrayList;
67import java.util.concurrent.atomic.AtomicBoolean;
68
69/**
70 * Takes updates from the CallList and notifies the InCallActivity (UI) of the changes. Responsible
71 * for starting the activity for a new call and finishing the activity when all calls are
72 * disconnected. Creates and manages the in-call state and provides a listener pattern for the
73 * presenters that want to listen in on the in-call state changes. TODO: This class has become more
74 * of a state machine at this point. Consider renaming.
75 */
Eric Erfaniand5e47f62017-03-15 14:41:07 -070076public class InCallPresenter implements CallList.Listener {
Eric Erfanianccca3152017-02-22 16:32:36 -080077
78 private static final String EXTRA_FIRST_TIME_SHOWN =
79 "com.android.incallui.intent.extra.FIRST_TIME_SHOWN";
80
81 private static final long BLOCK_QUERY_TIMEOUT_MS = 1000;
82
83 private static final Bundle EMPTY_EXTRAS = new Bundle();
84
85 private static InCallPresenter sInCallPresenter;
86
87 /**
88 * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is load factor before
89 * resizing, 1 means we only expect a single thread to access the map so make only a single shard
90 */
91 private final Set<InCallStateListener> mListeners =
92 Collections.newSetFromMap(new ConcurrentHashMap<InCallStateListener, Boolean>(8, 0.9f, 1));
93
94 private final List<IncomingCallListener> mIncomingCallListeners = new CopyOnWriteArrayList<>();
95 private final Set<InCallDetailsListener> mDetailsListeners =
96 Collections.newSetFromMap(new ConcurrentHashMap<InCallDetailsListener, Boolean>(8, 0.9f, 1));
97 private final Set<CanAddCallListener> mCanAddCallListeners =
98 Collections.newSetFromMap(new ConcurrentHashMap<CanAddCallListener, Boolean>(8, 0.9f, 1));
99 private final Set<InCallUiListener> mInCallUiListeners =
100 Collections.newSetFromMap(new ConcurrentHashMap<InCallUiListener, Boolean>(8, 0.9f, 1));
101 private final Set<InCallOrientationListener> mOrientationListeners =
102 Collections.newSetFromMap(
103 new ConcurrentHashMap<InCallOrientationListener, Boolean>(8, 0.9f, 1));
104 private final Set<InCallEventListener> mInCallEventListeners =
105 Collections.newSetFromMap(new ConcurrentHashMap<InCallEventListener, Boolean>(8, 0.9f, 1));
106
107 private StatusBarNotifier mStatusBarNotifier;
108 private ExternalCallNotifier mExternalCallNotifier;
109 private ContactInfoCache mContactInfoCache;
110 private Context mContext;
111 private final OnCheckBlockedListener mOnCheckBlockedListener =
112 new OnCheckBlockedListener() {
113 @Override
114 public void onCheckComplete(final Integer id) {
115 if (id != null && id != FilteredNumberAsyncQueryHandler.INVALID_ID) {
116 // Silence the ringer now to prevent ringing and vibration before the call is
117 // terminated when Telecom attempts to add it.
118 TelecomUtil.silenceRinger(mContext);
119 }
120 }
121 };
122 private CallList mCallList;
123 private ExternalCallList mExternalCallList;
124 private InCallActivity mInCallActivity;
125 private ManageConferenceActivity mManageConferenceActivity;
126 private final android.telecom.Call.Callback mCallCallback =
127 new android.telecom.Call.Callback() {
128 @Override
129 public void onPostDialWait(
130 android.telecom.Call telecomCall, String remainingPostDialSequence) {
131 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
132 if (call == null) {
133 Log.w(this, "DialerCall not found in call list: " + telecomCall);
134 return;
135 }
136 onPostDialCharWait(call.getId(), remainingPostDialSequence);
137 }
138
139 @Override
140 public void onDetailsChanged(
141 android.telecom.Call telecomCall, android.telecom.Call.Details details) {
142 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
143 if (call == null) {
144 Log.w(this, "DialerCall not found in call list: " + telecomCall);
145 return;
146 }
147
148 if (details.hasProperty(Details.PROPERTY_IS_EXTERNAL_CALL)
149 && !mExternalCallList.isCallTracked(telecomCall)) {
150
151 // A regular call became an external call so swap call lists.
152 Log.i(this, "Call became external: " + telecomCall);
153 mCallList.onInternalCallMadeExternal(mContext, telecomCall);
154 mExternalCallList.onCallAdded(telecomCall);
155 return;
156 }
157
158 for (InCallDetailsListener listener : mDetailsListeners) {
159 listener.onDetailsChanged(call, details);
160 }
161 }
162
163 @Override
164 public void onConferenceableCallsChanged(
165 android.telecom.Call telecomCall, List<android.telecom.Call> conferenceableCalls) {
166 Log.i(this, "onConferenceableCallsChanged: " + telecomCall);
167 onDetailsChanged(telecomCall, telecomCall.getDetails());
168 }
169 };
170 private InCallState mInCallState = InCallState.NO_CALLS;
171 private ProximitySensor mProximitySensor;
172 private final PseudoScreenState mPseudoScreenState = new PseudoScreenState();
173 private boolean mServiceConnected;
Eric Erfanianccca3152017-02-22 16:32:36 -0800174 private InCallCameraManager mInCallCameraManager;
175 private FilteredNumberAsyncQueryHandler mFilteredQueryHandler;
176 private CallList.Listener mSpamCallListListener;
177 /** Whether or not we are currently bound and waiting for Telecom to send us a new call. */
178 private boolean mBoundAndWaitingForOutgoingCall;
179 /** Determines if the InCall UI is in fullscreen mode or not. */
180 private boolean mIsFullScreen = false;
181
182 private PhoneStateListener mPhoneStateListener =
183 new PhoneStateListener() {
184 @Override
185 public void onCallStateChanged(int state, String incomingNumber) {
186 if (state == TelephonyManager.CALL_STATE_RINGING) {
187 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
188 return;
189 }
190 // Check if the number is blocked, to silence the ringer.
191 String countryIso = GeoUtil.getCurrentCountryIso(mContext);
192 mFilteredQueryHandler.isBlockedNumber(
193 mOnCheckBlockedListener, incomingNumber, countryIso);
194 }
195 }
196 };
197 /**
198 * Is true when the activity has been previously started. Some code needs to know not just if the
199 * activity is currently up, but if it had been previously shown in foreground for this in-call
200 * session (e.g., StatusBarNotifier). This gets reset when the session ends in the tear-down
201 * method.
202 */
203 private boolean mIsActivityPreviouslyStarted = false;
204
205 /** Whether or not InCallService is bound to Telecom. */
206 private boolean mServiceBound = false;
207
208 /**
209 * When configuration changes Android kills the current activity and starts a new one. The flag is
210 * used to check if full clean up is necessary (activity is stopped and new activity won't be
211 * started), or if a new activity will be started right after the current one is destroyed, and
212 * therefore no need in release all resources.
213 */
214 private boolean mIsChangingConfigurations = false;
215
216 private boolean mAwaitingCallListUpdate = false;
217
218 private ExternalCallList.ExternalCallListener mExternalCallListener =
219 new ExternalCallList.ExternalCallListener() {
220
221 @Override
222 public void onExternalCallPulled(android.telecom.Call call) {
223 // Note: keep this code in sync with InCallPresenter#onCallAdded
224 LatencyReport latencyReport = new LatencyReport(call);
225 latencyReport.onCallBlockingDone();
226 // Note: External calls do not require spam checking.
227 mCallList.onCallAdded(mContext, call, latencyReport);
228 call.registerCallback(mCallCallback);
229 }
230
231 @Override
232 public void onExternalCallAdded(android.telecom.Call call) {
233 // No-op
234 }
235
236 @Override
237 public void onExternalCallRemoved(android.telecom.Call call) {
238 // No-op
239 }
240
241 @Override
242 public void onExternalCallUpdated(android.telecom.Call call) {
243 // No-op
244 }
245 };
246
247 private ThemeColorManager mThemeColorManager;
248 private VideoSurfaceTexture mLocalVideoSurfaceTexture;
249 private VideoSurfaceTexture mRemoteVideoSurfaceTexture;
250
251 /** Inaccessible constructor. Must use getInstance() to get this singleton. */
252 @VisibleForTesting
253 InCallPresenter() {}
254
255 public static synchronized InCallPresenter getInstance() {
256 if (sInCallPresenter == null) {
257 sInCallPresenter = new InCallPresenter();
258 }
259 return sInCallPresenter;
260 }
261
262 /**
263 * Determines whether or not a call has no valid phone accounts that can be used to make the call
264 * with. Emergency calls do not require a phone account.
265 *
266 * @param call to check accounts for.
267 * @return {@code true} if the call has no call capable phone accounts set, {@code false} if the
268 * call contains a phone account that could be used to initiate it with, or is an emergency
269 * call.
270 */
271 public static boolean isCallWithNoValidAccounts(DialerCall call) {
272 if (call != null && !call.isEmergencyCall()) {
273 Bundle extras = call.getIntentExtras();
274
275 if (extras == null) {
276 extras = EMPTY_EXTRAS;
277 }
278
279 final List<PhoneAccountHandle> phoneAccountHandles =
280 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
281
282 if ((call.getAccountHandle() == null
283 && (phoneAccountHandles == null || phoneAccountHandles.isEmpty()))) {
284 Log.i(InCallPresenter.getInstance(), "No valid accounts for call " + call);
285 return true;
286 }
287 }
288 return false;
289 }
290
291 public InCallState getInCallState() {
292 return mInCallState;
293 }
294
295 public CallList getCallList() {
296 return mCallList;
297 }
298
299 public void setUp(
300 @NonNull Context context,
301 CallList callList,
302 ExternalCallList externalCallList,
303 StatusBarNotifier statusBarNotifier,
304 ExternalCallNotifier externalCallNotifier,
305 ContactInfoCache contactInfoCache,
306 ProximitySensor proximitySensor) {
307 if (mServiceConnected) {
308 Log.i(this, "New service connection replacing existing one.");
309 if (context != mContext || callList != mCallList) {
310 throw new IllegalStateException();
311 }
312 return;
313 }
314
315 Objects.requireNonNull(context);
316 mContext = context;
317
318 mContactInfoCache = contactInfoCache;
319
320 mStatusBarNotifier = statusBarNotifier;
321 mExternalCallNotifier = externalCallNotifier;
322 addListener(mStatusBarNotifier);
323
324 mProximitySensor = proximitySensor;
325 addListener(mProximitySensor);
326
327 mThemeColorManager =
328 new ThemeColorManager(new InCallUIMaterialColorMapUtils(mContext.getResources()));
329
330 mCallList = callList;
331 mExternalCallList = externalCallList;
332 externalCallList.addExternalCallListener(mExternalCallNotifier);
333 externalCallList.addExternalCallListener(mExternalCallListener);
334
335 // This only gets called by the service so this is okay.
336 mServiceConnected = true;
337
338 // The final thing we do in this set up is add ourselves as a listener to CallList. This
339 // will kick off an update and the whole process can start.
340 mCallList.addListener(this);
341
342 // Create spam call list listener and add it to the list of listeners
343 mSpamCallListListener = new SpamCallListListener(context);
344 mCallList.addListener(mSpamCallListListener);
345
346 VideoPauseController.getInstance().setUp(this);
Eric Erfanianccca3152017-02-22 16:32:36 -0800347
348 mFilteredQueryHandler = new FilteredNumberAsyncQueryHandler(context);
349 mContext
350 .getSystemService(TelephonyManager.class)
351 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
352
353 Log.d(this, "Finished InCallPresenter.setUp");
354 }
355
356 /**
357 * Called when the telephony service has disconnected from us. This will happen when there are no
358 * more active calls. However, we may still want to continue showing the UI for certain cases like
359 * showing "Call Ended". What we really want is to wait for the activity and the service to both
360 * disconnect before we tear things down. This method sets a serviceConnected boolean and calls a
361 * secondary method that performs the aforementioned logic.
362 */
363 public void tearDown() {
364 Log.d(this, "tearDown");
365 mCallList.clearOnDisconnect();
366
367 mServiceConnected = false;
368
369 mContext
370 .getSystemService(TelephonyManager.class)
371 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
372
373 attemptCleanup();
374 VideoPauseController.getInstance().tearDown();
Eric Erfanianccca3152017-02-22 16:32:36 -0800375 }
376
377 private void attemptFinishActivity() {
378 final boolean doFinish = (mInCallActivity != null && isActivityStarted());
379 Log.i(this, "Hide in call UI: " + doFinish);
380 if (doFinish) {
381 mInCallActivity.setExcludeFromRecents(true);
382 mInCallActivity.finish();
Eric Erfanianccca3152017-02-22 16:32:36 -0800383 }
384 }
385
386 /**
387 * Called when the UI ends. Attempts to tear down everything if necessary. See {@link #tearDown()}
388 * for more insight on the tear-down process.
389 */
390 public void unsetActivity(InCallActivity inCallActivity) {
391 if (inCallActivity == null) {
392 throw new IllegalArgumentException("unregisterActivity cannot be called with null");
393 }
394 if (mInCallActivity == null) {
395 Log.i(this, "No InCallActivity currently set, no need to unset.");
396 return;
397 }
398 if (mInCallActivity != inCallActivity) {
399 Log.w(
400 this,
401 "Second instance of InCallActivity is trying to unregister when another"
402 + " instance is active. Ignoring.");
403 return;
404 }
405 updateActivity(null);
406 }
407
408 /**
409 * Updates the current instance of {@link InCallActivity} with the provided one. If a {@code null}
410 * activity is provided, it means that the activity was finished and we should attempt to cleanup.
411 */
412 private void updateActivity(InCallActivity inCallActivity) {
413 boolean updateListeners = false;
414 boolean doAttemptCleanup = false;
415
416 if (inCallActivity != null) {
417 if (mInCallActivity == null) {
418 updateListeners = true;
419 Log.i(this, "UI Initialized");
420 } else {
421 // since setActivity is called onStart(), it can be called multiple times.
422 // This is fine and ignorable, but we do not want to update the world every time
423 // this happens (like going to/from background) so we do not set updateListeners.
424 }
425
426 mInCallActivity = inCallActivity;
427 mInCallActivity.setExcludeFromRecents(false);
428
429 // By the time the UI finally comes up, the call may already be disconnected.
430 // If that's the case, we may need to show an error dialog.
431 if (mCallList != null && mCallList.getDisconnectedCall() != null) {
432 maybeShowErrorDialogOnDisconnect(mCallList.getDisconnectedCall());
433 }
434
435 // When the UI comes up, we need to first check the in-call state.
436 // If we are showing NO_CALLS, that means that a call probably connected and
437 // then immediately disconnected before the UI was able to come up.
438 // If we dont have any calls, start tearing down the UI instead.
439 // NOTE: This code relies on {@link #mInCallActivity} being set so we run it after
440 // it has been set.
441 if (mInCallState == InCallState.NO_CALLS) {
442 Log.i(this, "UI Initialized, but no calls left. shut down.");
443 attemptFinishActivity();
444 return;
445 }
446 } else {
447 Log.i(this, "UI Destroyed");
448 updateListeners = true;
449 mInCallActivity = null;
450
451 // We attempt cleanup for the destroy case but only after we recalculate the state
452 // to see if we need to come back up or stay shut down. This is why we do the
453 // cleanup after the call to onCallListChange() instead of directly here.
454 doAttemptCleanup = true;
455 }
456
457 // Messages can come from the telephony layer while the activity is coming up
458 // and while the activity is going down. So in both cases we need to recalculate what
459 // state we should be in after they complete.
460 // Examples: (1) A new incoming call could come in and then get disconnected before
461 // the activity is created.
462 // (2) All calls could disconnect and then get a new incoming call before the
463 // activity is destroyed.
464 //
465 // b/1122139 - We previously had a check for mServiceConnected here as well, but there are
466 // cases where we need to recalculate the current state even if the service in not
467 // connected. In particular the case where startOrFinish() is called while the app is
468 // already finish()ing. In that case, we skip updating the state with the knowledge that
469 // we will check again once the activity has finished. That means we have to recalculate the
470 // state here even if the service is disconnected since we may not have finished a state
471 // transition while finish()ing.
472 if (updateListeners) {
473 onCallListChange(mCallList);
474 }
475
476 if (doAttemptCleanup) {
477 attemptCleanup();
478 }
479 }
480
481 public void setManageConferenceActivity(
482 @Nullable ManageConferenceActivity manageConferenceActivity) {
483 mManageConferenceActivity = manageConferenceActivity;
484 }
485
486 public void onBringToForeground(boolean showDialpad) {
487 Log.i(this, "Bringing UI to foreground.");
488 bringToForeground(showDialpad);
489 }
490
491 public void onCallAdded(final android.telecom.Call call) {
492 LatencyReport latencyReport = new LatencyReport(call);
493 if (shouldAttemptBlocking(call)) {
494 maybeBlockCall(call, latencyReport);
495 } else {
496 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
497 mExternalCallList.onCallAdded(call);
498 } else {
499 latencyReport.onCallBlockingDone();
500 mCallList.onCallAdded(mContext, call, latencyReport);
501 }
502 }
503
504 // Since a call has been added we are no longer waiting for Telecom to send us a call.
505 setBoundAndWaitingForOutgoingCall(false, null);
506 call.registerCallback(mCallCallback);
507 }
508
509 private boolean shouldAttemptBlocking(android.telecom.Call call) {
510 if (call.getState() != android.telecom.Call.STATE_RINGING) {
511 return false;
512 }
513 if (TelecomCallUtil.isEmergencyCall(call)) {
514 Log.i(this, "Not attempting to block incoming emergency call");
515 return false;
516 }
517 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
518 Log.i(this, "Not attempting to block incoming call due to recent emergency call");
519 return false;
520 }
521 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
522 return false;
523 }
524 return true;
525 }
526
527 /**
528 * Checks whether a call should be blocked, and blocks it if so. Otherwise, it adds the call to
529 * the CallList so it can proceed as normal. There is a timeout, so if the function for checking
530 * whether a function is blocked does not return in a reasonable time, we proceed with adding the
531 * call anyways.
532 */
533 private void maybeBlockCall(final android.telecom.Call call, final LatencyReport latencyReport) {
534 final String countryIso = GeoUtil.getCurrentCountryIso(mContext);
535 final String number = TelecomCallUtil.getNumber(call);
536 final long timeAdded = System.currentTimeMillis();
537
538 // Though AtomicBoolean's can be scary, don't fear, as in this case it is only used on the
539 // main UI thread. It is needed so we can change its value within different scopes, since
540 // that cannot be done with a final boolean.
541 final AtomicBoolean hasTimedOut = new AtomicBoolean(false);
542
543 final Handler handler = new Handler();
544
545 // Proceed if the query is slow; the call may still be blocked after the query returns.
546 final Runnable runnable =
547 new Runnable() {
548 @Override
549 public void run() {
550 hasTimedOut.set(true);
551 latencyReport.onCallBlockingDone();
552 mCallList.onCallAdded(mContext, call, latencyReport);
553 }
554 };
555 handler.postDelayed(runnable, BLOCK_QUERY_TIMEOUT_MS);
556
557 OnCheckBlockedListener onCheckBlockedListener =
558 new OnCheckBlockedListener() {
559 @Override
560 public void onCheckComplete(final Integer id) {
561 if (isReadyForTearDown()) {
562 Log.i(this, "InCallPresenter is torn down, not adding call");
563 return;
564 }
565 if (!hasTimedOut.get()) {
566 handler.removeCallbacks(runnable);
567 }
568 if (id == null) {
569 if (!hasTimedOut.get()) {
570 latencyReport.onCallBlockingDone();
571 mCallList.onCallAdded(mContext, call, latencyReport);
572 }
573 } else if (id == FilteredNumberAsyncQueryHandler.INVALID_ID) {
574 Log.d(this, "checkForBlockedCall: invalid number, skipping block checking");
575 if (!hasTimedOut.get()) {
576 handler.removeCallbacks(runnable);
577
578 latencyReport.onCallBlockingDone();
579 mCallList.onCallAdded(mContext, call, latencyReport);
580 }
581 } else {
582 Log.i(this, "Rejecting incoming call from blocked number");
583 call.reject(false, null);
584 Logger.get(mContext).logInteraction(InteractionEvent.Type.CALL_BLOCKED);
585
586 /*
587 * If mContext is null, then the InCallPresenter was torn down before the
588 * block check had a chance to complete. The context is no longer valid, so
589 * don't attempt to remove the call log entry.
590 */
591 if (mContext == null) {
592 return;
593 }
594 // Register observer to update the call log.
595 // BlockedNumberContentObserver will unregister after successful log or timeout.
596 BlockedNumberContentObserver contentObserver =
597 new BlockedNumberContentObserver(mContext, new Handler(), number, timeAdded);
598 contentObserver.register();
599 }
600 }
601 };
602
603 mFilteredQueryHandler.isBlockedNumber(onCheckBlockedListener, number, countryIso);
604 }
605
606 public void onCallRemoved(android.telecom.Call call) {
607 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
608 mExternalCallList.onCallRemoved(call);
609 } else {
610 mCallList.onCallRemoved(mContext, call);
611 call.unregisterCallback(mCallCallback);
612 }
613 }
614
615 public void onCanAddCallChanged(boolean canAddCall) {
616 for (CanAddCallListener listener : mCanAddCallListeners) {
617 listener.onCanAddCallChanged(canAddCall);
618 }
619 }
620
621 @Override
622 public void onWiFiToLteHandover(DialerCall call) {
623 if (mInCallActivity != null) {
624 mInCallActivity.onWiFiToLteHandover(call);
625 }
626 }
627
628 @Override
629 public void onHandoverToWifiFailed(DialerCall call) {
630 if (mInCallActivity != null) {
631 mInCallActivity.onHandoverToWifiFailed(call);
632 }
633 }
634
635 /**
636 * Called when there is a change to the call list. Sets the In-Call state for the entire in-call
637 * app based on the information it gets from CallList. Dispatches the in-call state to all
638 * listeners. Can trigger the creation or destruction of the UI based on the states that is
639 * calculates.
640 */
641 @Override
642 public void onCallListChange(CallList callList) {
643 if (mInCallActivity != null && mInCallActivity.isInCallScreenAnimating()) {
644 mAwaitingCallListUpdate = true;
645 return;
646 }
647 if (callList == null) {
648 return;
649 }
650
651 mAwaitingCallListUpdate = false;
652
653 InCallState newState = getPotentialStateFromCallList(callList);
654 InCallState oldState = mInCallState;
655 Log.d(this, "onCallListChange oldState= " + oldState + " newState=" + newState);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700656
657 // If the user placed a call and was asked to choose the account, but then pressed "Home", the
658 // incall activity for that call will still exist (even if it's not visible). In the case of
659 // an incoming call in that situation, just disconnect that "waiting for account" call and
660 // dismiss the dialog. The same activity will be reused to handle the new incoming call. See
661 // b/33247755 for more details.
662 DialerCall waitingForAccountCall;
663 if (newState == InCallState.INCOMING
664 && (waitingForAccountCall = callList.getWaitingForAccountCall()) != null) {
665 waitingForAccountCall.disconnect();
666 mInCallActivity.dismissPendingDialogs();
667 }
668
Eric Erfanianccca3152017-02-22 16:32:36 -0800669 newState = startOrFinishUi(newState);
670 Log.d(this, "onCallListChange newState changed to " + newState);
671
672 // Set the new state before announcing it to the world
673 Log.i(this, "Phone switching state: " + oldState + " -> " + newState);
674 mInCallState = newState;
675
676 // notify listeners of new state
677 for (InCallStateListener listener : mListeners) {
678 Log.d(this, "Notify " + listener + " of state " + mInCallState.toString());
679 listener.onStateChange(oldState, mInCallState, callList);
680 }
681
682 if (isActivityStarted()) {
683 final boolean hasCall =
684 callList.getActiveOrBackgroundCall() != null || callList.getOutgoingCall() != null;
685 mInCallActivity.dismissKeyguard(hasCall);
686 }
687 }
688
689 /** Called when there is a new incoming call. */
690 @Override
691 public void onIncomingCall(DialerCall call) {
692 InCallState newState = startOrFinishUi(InCallState.INCOMING);
693 InCallState oldState = mInCallState;
694
695 Log.i(this, "Phone switching state: " + oldState + " -> " + newState);
696 mInCallState = newState;
697
698 for (IncomingCallListener listener : mIncomingCallListeners) {
699 listener.onIncomingCall(oldState, mInCallState, call);
700 }
701
702 if (mInCallActivity != null) {
703 // Re-evaluate which fragment is being shown.
704 mInCallActivity.onPrimaryCallStateChanged();
705 }
706 }
707
708 @Override
709 public void onUpgradeToVideo(DialerCall call) {
Eric Erfanian90508232017-03-24 09:31:16 -0700710 if (VideoUtils.hasReceivedVideoUpgradeRequest(call.getVideoTech().getSessionModificationState())
Eric Erfanianccca3152017-02-22 16:32:36 -0800711 && mInCallState == InCallPresenter.InCallState.INCOMING) {
712 LogUtil.i(
713 "InCallPresenter.onUpgradeToVideo",
714 "rejecting upgrade request due to existing incoming call");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700715 call.getVideoTech().declineVideoRequest();
Eric Erfanianccca3152017-02-22 16:32:36 -0800716 }
717
718 if (mInCallActivity != null) {
719 // Re-evaluate which fragment is being shown.
720 mInCallActivity.onPrimaryCallStateChanged();
721 }
722 }
723
724 @Override
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700725 public void onSessionModificationStateChange(DialerCall call) {
726 int newState = call.getVideoTech().getSessionModificationState();
Eric Erfanianccca3152017-02-22 16:32:36 -0800727 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "state: %d", newState);
728 if (mProximitySensor == null) {
729 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "proximitySensor is null");
730 return;
731 }
732 mProximitySensor.setIsAttemptingVideoCall(
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700733 call.hasSentVideoUpgradeRequest() || call.hasReceivedVideoUpgradeRequest());
Eric Erfanianccca3152017-02-22 16:32:36 -0800734 if (mInCallActivity != null) {
735 // Re-evaluate which fragment is being shown.
736 mInCallActivity.onPrimaryCallStateChanged();
737 }
738 }
739
740 /**
741 * Called when a call becomes disconnected. Called everytime an existing call changes from being
742 * connected (incoming/outgoing/active) to disconnected.
743 */
744 @Override
745 public void onDisconnect(DialerCall call) {
746 maybeShowErrorDialogOnDisconnect(call);
747
748 // We need to do the run the same code as onCallListChange.
749 onCallListChange(mCallList);
750
751 if (isActivityStarted()) {
752 mInCallActivity.dismissKeyguard(false);
753 }
754
755 if (call.isEmergencyCall()) {
756 FilteredNumbersUtil.recordLastEmergencyCallTime(mContext);
757 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800758
Eric Erfanianfc37b022017-03-21 10:11:17 -0700759 if (!mCallList.hasLiveCall()
760 && !call.getLogState().isIncoming
761 && !CallerInfoUtils.isVoiceMailNumber(mContext, call)) {
762 PostCall.onCallDisconnected(mContext, call.getNumber(), call.getTimeAddedMs());
Eric Erfanianccca3152017-02-22 16:32:36 -0800763 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800764 }
765
766 /** Given the call list, return the state in which the in-call screen should be. */
767 public InCallState getPotentialStateFromCallList(CallList callList) {
768
769 InCallState newState = InCallState.NO_CALLS;
770
771 if (callList == null) {
772 return newState;
773 }
774 if (callList.getIncomingCall() != null) {
775 newState = InCallState.INCOMING;
776 } else if (callList.getWaitingForAccountCall() != null) {
777 newState = InCallState.WAITING_FOR_ACCOUNT;
778 } else if (callList.getPendingOutgoingCall() != null) {
779 newState = InCallState.PENDING_OUTGOING;
780 } else if (callList.getOutgoingCall() != null) {
781 newState = InCallState.OUTGOING;
782 } else if (callList.getActiveCall() != null
783 || callList.getBackgroundCall() != null
784 || callList.getDisconnectedCall() != null
785 || callList.getDisconnectingCall() != null) {
786 newState = InCallState.INCALL;
787 }
788
789 if (newState == InCallState.NO_CALLS) {
790 if (mBoundAndWaitingForOutgoingCall) {
791 return InCallState.OUTGOING;
792 }
793 }
794
795 return newState;
796 }
797
798 public boolean isBoundAndWaitingForOutgoingCall() {
799 return mBoundAndWaitingForOutgoingCall;
800 }
801
802 public void setBoundAndWaitingForOutgoingCall(boolean isBound, PhoneAccountHandle handle) {
803 Log.i(this, "setBoundAndWaitingForOutgoingCall: " + isBound);
804 mBoundAndWaitingForOutgoingCall = isBound;
805 mThemeColorManager.setPendingPhoneAccountHandle(handle);
806 if (isBound && mInCallState == InCallState.NO_CALLS) {
807 mInCallState = InCallState.OUTGOING;
808 }
809 }
810
811 public void onShrinkAnimationComplete() {
812 if (mAwaitingCallListUpdate) {
813 onCallListChange(mCallList);
814 }
815 }
816
817 public void addIncomingCallListener(IncomingCallListener listener) {
818 Objects.requireNonNull(listener);
819 mIncomingCallListeners.add(listener);
820 }
821
822 public void removeIncomingCallListener(IncomingCallListener listener) {
823 if (listener != null) {
824 mIncomingCallListeners.remove(listener);
825 }
826 }
827
828 public void addListener(InCallStateListener listener) {
829 Objects.requireNonNull(listener);
830 mListeners.add(listener);
831 }
832
833 public void removeListener(InCallStateListener listener) {
834 if (listener != null) {
835 mListeners.remove(listener);
836 }
837 }
838
839 public void addDetailsListener(InCallDetailsListener listener) {
840 Objects.requireNonNull(listener);
841 mDetailsListeners.add(listener);
842 }
843
844 public void removeDetailsListener(InCallDetailsListener listener) {
845 if (listener != null) {
846 mDetailsListeners.remove(listener);
847 }
848 }
849
850 public void addCanAddCallListener(CanAddCallListener listener) {
851 Objects.requireNonNull(listener);
852 mCanAddCallListeners.add(listener);
853 }
854
855 public void removeCanAddCallListener(CanAddCallListener listener) {
856 if (listener != null) {
857 mCanAddCallListeners.remove(listener);
858 }
859 }
860
861 public void addOrientationListener(InCallOrientationListener listener) {
862 Objects.requireNonNull(listener);
863 mOrientationListeners.add(listener);
864 }
865
866 public void removeOrientationListener(InCallOrientationListener listener) {
867 if (listener != null) {
868 mOrientationListeners.remove(listener);
869 }
870 }
871
872 public void addInCallEventListener(InCallEventListener listener) {
873 Objects.requireNonNull(listener);
874 mInCallEventListeners.add(listener);
875 }
876
877 public void removeInCallEventListener(InCallEventListener listener) {
878 if (listener != null) {
879 mInCallEventListeners.remove(listener);
880 }
881 }
882
883 public ProximitySensor getProximitySensor() {
884 return mProximitySensor;
885 }
886
887 public PseudoScreenState getPseudoScreenState() {
888 return mPseudoScreenState;
889 }
890
891 /** Returns true if the incall app is the foreground application. */
892 public boolean isShowingInCallUi() {
893 if (!isActivityStarted()) {
894 return false;
895 }
896 if (mManageConferenceActivity != null && mManageConferenceActivity.isVisible()) {
897 return true;
898 }
899 return mInCallActivity.isVisible();
900 }
901
902 /**
903 * Returns true if the activity has been created and is running. Returns true as long as activity
904 * is not destroyed or finishing. This ensures that we return true even if the activity is paused
905 * (not in foreground).
906 */
907 public boolean isActivityStarted() {
908 return (mInCallActivity != null
909 && !mInCallActivity.isDestroyed()
910 && !mInCallActivity.isFinishing());
911 }
912
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700913 private boolean isActivityVisible() {
914 return mInCallActivity != null && mInCallActivity.isVisible();
915 }
916
917 boolean shouldShowFullScreenNotification() {
918 /**
919 * This is to cover the case where the incall activity is started but in the background, e.g.
920 * when the user pressed Home from the account selection dialog or an existing call. In the case
921 * that incall activity is already visible, there's no need to configure the notification with a
922 * full screen intent.
923 */
924 LogUtil.d(
925 "InCallPresenter.shouldShowFullScreenNotification",
926 "isActivityVisible: %b",
927 isActivityVisible());
928 return !isActivityVisible();
929 }
930
Eric Erfanianccca3152017-02-22 16:32:36 -0800931 /**
932 * Determines if the In-Call app is currently changing configuration.
933 *
934 * @return {@code true} if the In-Call app is changing configuration.
935 */
936 public boolean isChangingConfigurations() {
937 return mIsChangingConfigurations;
938 }
939
940 /**
941 * Tracks whether the In-Call app is currently in the process of changing configuration (i.e.
942 * screen orientation).
943 */
944 /*package*/
945 void updateIsChangingConfigurations() {
946 mIsChangingConfigurations = false;
947 if (mInCallActivity != null) {
948 mIsChangingConfigurations = mInCallActivity.isChangingConfigurations();
949 }
950 Log.v(this, "updateIsChangingConfigurations = " + mIsChangingConfigurations);
951 }
952
953 /** Called when the activity goes in/out of the foreground. */
954 public void onUiShowing(boolean showing) {
955 // We need to update the notification bar when we leave the UI because that
956 // could trigger it to show again.
957 if (mStatusBarNotifier != null) {
958 mStatusBarNotifier.updateNotification(mCallList);
959 }
960
961 if (mProximitySensor != null) {
962 mProximitySensor.onInCallShowing(showing);
963 }
964
965 Intent broadcastIntent = Bindings.get(mContext).getUiReadyBroadcastIntent(mContext);
966 if (broadcastIntent != null) {
967 broadcastIntent.putExtra(EXTRA_FIRST_TIME_SHOWN, !mIsActivityPreviouslyStarted);
968
969 if (showing) {
970 Log.d(this, "Sending sticky broadcast: ", broadcastIntent);
971 mContext.sendStickyBroadcast(broadcastIntent);
972 } else {
973 Log.d(this, "Removing sticky broadcast: ", broadcastIntent);
974 mContext.removeStickyBroadcast(broadcastIntent);
975 }
976 }
977
978 if (showing) {
979 mIsActivityPreviouslyStarted = true;
980 } else {
981 updateIsChangingConfigurations();
982 }
983
984 for (InCallUiListener listener : mInCallUiListeners) {
985 listener.onUiShowing(showing);
986 }
987
988 if (mInCallActivity != null) {
989 // Re-evaluate which fragment is being shown.
990 mInCallActivity.onPrimaryCallStateChanged();
991 }
992 }
993
994 public void addInCallUiListener(InCallUiListener listener) {
995 mInCallUiListeners.add(listener);
996 }
997
998 public boolean removeInCallUiListener(InCallUiListener listener) {
999 return mInCallUiListeners.remove(listener);
1000 }
1001
1002 /*package*/
1003 void onActivityStarted() {
1004 Log.d(this, "onActivityStarted");
1005 notifyVideoPauseController(true);
1006 mStatusBarNotifier.updateNotification(mCallList);
1007 }
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
1300 if (!startUi()) {
1301 // startUI refused to start the UI. This indicates that it needed to restart the
1302 // activity. When it finally restarts, it will call us back, so we do not actually
1303 // change the state yet (we return mInCallState instead of newState).
1304 return mInCallState;
1305 }
1306 } else if (newState == InCallState.NO_CALLS) {
1307 // The new state is the no calls state. Tear everything down.
1308 attemptFinishActivity();
1309 attemptCleanup();
1310 }
1311
1312 return newState;
1313 }
1314
1315 /**
1316 * Sets the DisconnectCause for a call that was disconnected because it was missing a PhoneAccount
1317 * or PhoneAccounts to select from.
1318 */
1319 private void setDisconnectCauseForMissingAccounts(DialerCall call) {
1320
1321 Bundle extras = call.getIntentExtras();
1322 // Initialize the extras bundle to avoid NPE
1323 if (extras == null) {
1324 extras = new Bundle();
1325 }
1326
1327 final List<PhoneAccountHandle> phoneAccountHandles =
1328 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
1329
1330 if (phoneAccountHandles == null || phoneAccountHandles.isEmpty()) {
1331 String scheme = call.getHandle().getScheme();
1332 final String errorMsg =
1333 PhoneAccount.SCHEME_TEL.equals(scheme)
1334 ? mContext.getString(R.string.callFailed_simError)
1335 : mContext.getString(R.string.incall_error_supp_service_unknown);
1336 DisconnectCause disconnectCause =
1337 new DisconnectCause(DisconnectCause.ERROR, null, errorMsg, errorMsg);
1338 call.setDisconnectCause(disconnectCause);
1339 }
1340 }
1341
1342 private boolean startUi() {
1343 boolean isCallWaiting =
1344 mCallList.getActiveCall() != null && mCallList.getIncomingCall() != null;
1345
1346 if (isCallWaiting) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001347 showInCall(false, false);
Eric Erfanianccca3152017-02-22 16:32:36 -08001348 } else {
1349 mStatusBarNotifier.updateNotification(mCallList);
1350 }
1351 return true;
1352 }
1353
1354 /**
1355 * @return {@code true} if the InCallPresenter is ready to be torn down, {@code false} otherwise.
1356 * Calling classes should use this as an indication whether to interact with the
1357 * InCallPresenter or not.
1358 */
1359 public boolean isReadyForTearDown() {
1360 return mInCallActivity == null && !mServiceConnected && mInCallState == InCallState.NO_CALLS;
1361 }
1362
1363 /**
1364 * Checks to see if both the UI is gone and the service is disconnected. If so, tear it all down.
1365 */
1366 private void attemptCleanup() {
1367 if (isReadyForTearDown()) {
1368 Log.i(this, "Cleaning up");
1369
1370 cleanupSurfaces();
1371
1372 mIsActivityPreviouslyStarted = false;
1373 mIsChangingConfigurations = false;
1374
1375 // blow away stale contact info so that we get fresh data on
1376 // the next set of calls
1377 if (mContactInfoCache != null) {
1378 mContactInfoCache.clearCache();
1379 }
1380 mContactInfoCache = null;
1381
1382 if (mProximitySensor != null) {
1383 removeListener(mProximitySensor);
1384 mProximitySensor.tearDown();
1385 }
1386 mProximitySensor = null;
1387
1388 if (mStatusBarNotifier != null) {
1389 removeListener(mStatusBarNotifier);
1390 }
1391 if (mExternalCallNotifier != null && mExternalCallList != null) {
1392 mExternalCallList.removeExternalCallListener(mExternalCallNotifier);
1393 }
1394 mStatusBarNotifier = null;
1395
1396 if (mCallList != null) {
1397 mCallList.removeListener(this);
1398 mCallList.removeListener(mSpamCallListListener);
1399 }
1400 mCallList = null;
1401
1402 mContext = null;
1403 mInCallActivity = null;
1404 mManageConferenceActivity = null;
1405
1406 mListeners.clear();
1407 mIncomingCallListeners.clear();
1408 mDetailsListeners.clear();
1409 mCanAddCallListeners.clear();
1410 mOrientationListeners.clear();
1411 mInCallEventListeners.clear();
1412 mInCallUiListeners.clear();
1413
1414 Log.d(this, "Finished InCallPresenter.CleanUp");
1415 }
1416 }
1417
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001418 public void showInCall(boolean showDialpad, boolean newOutgoingCall) {
Eric Erfanianccca3152017-02-22 16:32:36 -08001419 Log.i(this, "Showing InCallActivity");
1420 mContext.startActivity(
1421 InCallActivity.getIntent(
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001422 mContext, showDialpad, newOutgoingCall, false /* forFullScreen */));
Eric Erfanianccca3152017-02-22 16:32:36 -08001423 }
1424
1425 public void onServiceBind() {
1426 mServiceBound = true;
1427 }
1428
1429 public void onServiceUnbind() {
1430 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(false, null);
1431 mServiceBound = false;
1432 }
1433
1434 public boolean isServiceBound() {
1435 return mServiceBound;
1436 }
1437
1438 public void maybeStartRevealAnimation(Intent intent) {
1439 if (intent == null || mInCallActivity != null) {
1440 return;
1441 }
1442 final Bundle extras = intent.getBundleExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS);
1443 if (extras == null) {
1444 // Incoming call, just show the in-call UI directly.
1445 return;
1446 }
1447
1448 if (extras.containsKey(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS)) {
1449 // Account selection dialog will show up so don't show the animation.
1450 return;
1451 }
1452
1453 final PhoneAccountHandle accountHandle =
1454 intent.getParcelableExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
1455 final Point touchPoint = extras.getParcelable(TouchPointManager.TOUCH_POINT);
Eric Erfanianccca3152017-02-22 16:32:36 -08001456
1457 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(true, accountHandle);
1458
1459 final Intent activityIntent =
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001460 InCallActivity.getIntent(mContext, false, true, false /* forFullScreen */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001461 activityIntent.putExtra(TouchPointManager.TOUCH_POINT, touchPoint);
1462 mContext.startActivity(activityIntent);
1463 }
1464
1465 /**
1466 * Retrieves the current in-call camera manager instance, creating if necessary.
1467 *
1468 * @return The {@link InCallCameraManager}.
1469 */
1470 public InCallCameraManager getInCallCameraManager() {
1471 synchronized (this) {
1472 if (mInCallCameraManager == null) {
1473 mInCallCameraManager = new InCallCameraManager(mContext);
1474 }
1475
1476 return mInCallCameraManager;
1477 }
1478 }
1479
1480 /**
1481 * Notifies listeners of changes in orientation and notify calls of rotation angle change.
1482 *
1483 * @param orientation The screen orientation of the device (one of: {@link
1484 * InCallOrientationEventListener#SCREEN_ORIENTATION_0}, {@link
1485 * InCallOrientationEventListener#SCREEN_ORIENTATION_90}, {@link
1486 * InCallOrientationEventListener#SCREEN_ORIENTATION_180}, {@link
1487 * InCallOrientationEventListener#SCREEN_ORIENTATION_270}).
1488 */
1489 public void onDeviceOrientationChange(@ScreenOrientation int orientation) {
1490 Log.d(this, "onDeviceOrientationChange: orientation= " + orientation);
1491
1492 if (mCallList != null) {
1493 mCallList.notifyCallsOfDeviceRotation(orientation);
1494 } else {
1495 Log.w(this, "onDeviceOrientationChange: CallList is null.");
1496 }
1497
1498 // Notify listeners of device orientation changed.
1499 for (InCallOrientationListener listener : mOrientationListeners) {
1500 listener.onDeviceOrientationChanged(orientation);
1501 }
1502 }
1503
1504 /**
1505 * Configures the in-call UI activity so it can change orientations or not. Enables the
1506 * orientation event listener if allowOrientationChange is true, disables it if false.
1507 *
1508 * @param allowOrientationChange {@code true} if the in-call UI can change between portrait and
1509 * landscape. {@code false} if the in-call UI should be locked in portrait.
1510 */
1511 public void setInCallAllowsOrientationChange(boolean allowOrientationChange) {
1512 if (mInCallActivity == null) {
1513 Log.e(this, "InCallActivity is null. Can't set requested orientation.");
1514 return;
1515 }
1516 mInCallActivity.setAllowOrientationChange(allowOrientationChange);
1517 }
1518
1519 public void enableScreenTimeout(boolean enable) {
1520 Log.v(this, "enableScreenTimeout: value=" + enable);
1521 if (mInCallActivity == null) {
1522 Log.e(this, "enableScreenTimeout: InCallActivity is null.");
1523 return;
1524 }
1525
1526 final Window window = mInCallActivity.getWindow();
1527 if (enable) {
1528 window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1529 } else {
1530 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1531 }
1532 }
1533
1534 /**
1535 * Hides or shows the conference manager fragment.
1536 *
1537 * @param show {@code true} if the conference manager should be shown, {@code false} if it should
1538 * be hidden.
1539 */
1540 public void showConferenceCallManager(boolean show) {
1541 if (mInCallActivity != null) {
1542 mInCallActivity.showConferenceFragment(show);
1543 }
1544 if (!show && mManageConferenceActivity != null) {
1545 mManageConferenceActivity.finish();
1546 }
1547 }
1548
1549 /**
1550 * Determines if the dialpad is visible.
1551 *
1552 * @return {@code true} if the dialpad is visible, {@code false} otherwise.
1553 */
1554 public boolean isDialpadVisible() {
1555 if (mInCallActivity == null) {
1556 return false;
1557 }
1558 return mInCallActivity.isDialpadVisible();
1559 }
1560
1561 public ThemeColorManager getThemeColorManager() {
1562 return mThemeColorManager;
1563 }
1564
1565 /** Called when the foreground call changes. */
1566 public void onForegroundCallChanged(DialerCall newForegroundCall) {
1567 mThemeColorManager.onForegroundCallChanged(mContext, newForegroundCall);
1568 if (mInCallActivity != null) {
1569 mInCallActivity.onForegroundCallChanged(newForegroundCall);
1570 }
1571 }
1572
1573 public InCallActivity getActivity() {
1574 return mInCallActivity;
1575 }
1576
1577 /** Called when the UI begins, and starts the callstate callbacks if necessary. */
1578 public void setActivity(InCallActivity inCallActivity) {
1579 if (inCallActivity == null) {
1580 throw new IllegalArgumentException("registerActivity cannot be called with null");
1581 }
1582 if (mInCallActivity != null && mInCallActivity != inCallActivity) {
1583 Log.w(this, "Setting a second activity before destroying the first.");
1584 }
1585 updateActivity(inCallActivity);
1586 }
1587
1588 ExternalCallNotifier getExternalCallNotifier() {
1589 return mExternalCallNotifier;
1590 }
1591
1592 VideoSurfaceTexture getLocalVideoSurfaceTexture() {
1593 if (mLocalVideoSurfaceTexture == null) {
1594 mLocalVideoSurfaceTexture = VideoSurfaceBindings.createLocalVideoSurfaceTexture();
1595 }
1596 return mLocalVideoSurfaceTexture;
1597 }
1598
1599 VideoSurfaceTexture getRemoteVideoSurfaceTexture() {
1600 if (mRemoteVideoSurfaceTexture == null) {
1601 mRemoteVideoSurfaceTexture = VideoSurfaceBindings.createRemoteVideoSurfaceTexture();
1602 }
1603 return mRemoteVideoSurfaceTexture;
1604 }
1605
1606 void cleanupSurfaces() {
1607 if (mRemoteVideoSurfaceTexture != null) {
1608 mRemoteVideoSurfaceTexture.setDoneWithSurface();
1609 mRemoteVideoSurfaceTexture = null;
1610 }
1611 if (mLocalVideoSurfaceTexture != null) {
1612 mLocalVideoSurfaceTexture.setDoneWithSurface();
1613 mLocalVideoSurfaceTexture = null;
1614 }
1615 }
1616
1617 /** All the main states of InCallActivity. */
1618 public enum InCallState {
1619 // InCall Screen is off and there are no calls
1620 NO_CALLS,
1621
1622 // Incoming-call screen is up
1623 INCOMING,
1624
1625 // In-call experience is showing
1626 INCALL,
1627
1628 // Waiting for user input before placing outgoing call
1629 WAITING_FOR_ACCOUNT,
1630
1631 // UI is starting up but no call has been initiated yet.
1632 // The UI is waiting for Telecom to respond.
1633 PENDING_OUTGOING,
1634
1635 // User is dialing out
1636 OUTGOING;
1637
1638 public boolean isIncoming() {
1639 return (this == INCOMING);
1640 }
1641
1642 public boolean isConnectingOrConnected() {
1643 return (this == INCOMING || this == OUTGOING || this == INCALL);
1644 }
1645 }
1646
1647 /** Interface implemented by classes that need to know about the InCall State. */
1648 public interface InCallStateListener {
1649
1650 // TODO: Enhance state to contain the call objects instead of passing CallList
1651 void onStateChange(InCallState oldState, InCallState newState, CallList callList);
1652 }
1653
1654 public interface IncomingCallListener {
1655
1656 void onIncomingCall(InCallState oldState, InCallState newState, DialerCall call);
1657 }
1658
1659 public interface CanAddCallListener {
1660
1661 void onCanAddCallChanged(boolean canAddCall);
1662 }
1663
1664 public interface InCallDetailsListener {
1665
1666 void onDetailsChanged(DialerCall call, android.telecom.Call.Details details);
1667 }
1668
1669 public interface InCallOrientationListener {
1670
1671 void onDeviceOrientationChanged(@ScreenOrientation int orientation);
1672 }
1673
1674 /**
1675 * Interface implemented by classes that need to know about events which occur within the In-Call
1676 * UI. Used as a means of communicating between fragments that make up the UI.
1677 */
1678 public interface InCallEventListener {
1679
1680 void onFullscreenModeChanged(boolean isFullscreenMode);
1681 }
1682
1683 public interface InCallUiListener {
1684
1685 void onUiShowing(boolean showing);
1686 }
1687}