blob: 0f3982ce4f1c7441f8009872879706b1e6f5ced5 [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 Erfaniand5e47f62017-03-15 14:41:07 -070060import com.android.incallui.videotech.VideoTech;
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 Erfaniand5e47f62017-03-15 14:41:07 -0700710 if (call.getVideoTech().getSessionModificationState()
711 == VideoTech.SESSION_MODIFICATION_STATE_RECEIVED_UPGRADE_TO_VIDEO_REQUEST
Eric Erfanianccca3152017-02-22 16:32:36 -0800712 && mInCallState == InCallPresenter.InCallState.INCOMING) {
713 LogUtil.i(
714 "InCallPresenter.onUpgradeToVideo",
715 "rejecting upgrade request due to existing incoming call");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700716 call.getVideoTech().declineVideoRequest();
Eric Erfanianccca3152017-02-22 16:32:36 -0800717 }
718
719 if (mInCallActivity != null) {
720 // Re-evaluate which fragment is being shown.
721 mInCallActivity.onPrimaryCallStateChanged();
722 }
723 }
724
725 @Override
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700726 public void onSessionModificationStateChange(DialerCall call) {
727 int newState = call.getVideoTech().getSessionModificationState();
Eric Erfanianccca3152017-02-22 16:32:36 -0800728 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "state: %d", newState);
729 if (mProximitySensor == null) {
730 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "proximitySensor is null");
731 return;
732 }
733 mProximitySensor.setIsAttemptingVideoCall(
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700734 call.hasSentVideoUpgradeRequest() || call.hasReceivedVideoUpgradeRequest());
Eric Erfanianccca3152017-02-22 16:32:36 -0800735 if (mInCallActivity != null) {
736 // Re-evaluate which fragment is being shown.
737 mInCallActivity.onPrimaryCallStateChanged();
738 }
739 }
740
741 /**
742 * Called when a call becomes disconnected. Called everytime an existing call changes from being
743 * connected (incoming/outgoing/active) to disconnected.
744 */
745 @Override
746 public void onDisconnect(DialerCall call) {
747 maybeShowErrorDialogOnDisconnect(call);
748
749 // We need to do the run the same code as onCallListChange.
750 onCallListChange(mCallList);
751
752 if (isActivityStarted()) {
753 mInCallActivity.dismissKeyguard(false);
754 }
755
756 if (call.isEmergencyCall()) {
757 FilteredNumbersUtil.recordLastEmergencyCallTime(mContext);
758 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800759
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700760 if (!call.getLogState().isIncoming && !mCallList.hasLiveCall()) {
761 PostCall.onCallDisconnected(mContext, call.getNumber(), call.getConnectTimeMillis());
Eric Erfanianccca3152017-02-22 16:32:36 -0800762 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800763 }
764
765 /** Given the call list, return the state in which the in-call screen should be. */
766 public InCallState getPotentialStateFromCallList(CallList callList) {
767
768 InCallState newState = InCallState.NO_CALLS;
769
770 if (callList == null) {
771 return newState;
772 }
773 if (callList.getIncomingCall() != null) {
774 newState = InCallState.INCOMING;
775 } else if (callList.getWaitingForAccountCall() != null) {
776 newState = InCallState.WAITING_FOR_ACCOUNT;
777 } else if (callList.getPendingOutgoingCall() != null) {
778 newState = InCallState.PENDING_OUTGOING;
779 } else if (callList.getOutgoingCall() != null) {
780 newState = InCallState.OUTGOING;
781 } else if (callList.getActiveCall() != null
782 || callList.getBackgroundCall() != null
783 || callList.getDisconnectedCall() != null
784 || callList.getDisconnectingCall() != null) {
785 newState = InCallState.INCALL;
786 }
787
788 if (newState == InCallState.NO_CALLS) {
789 if (mBoundAndWaitingForOutgoingCall) {
790 return InCallState.OUTGOING;
791 }
792 }
793
794 return newState;
795 }
796
797 public boolean isBoundAndWaitingForOutgoingCall() {
798 return mBoundAndWaitingForOutgoingCall;
799 }
800
801 public void setBoundAndWaitingForOutgoingCall(boolean isBound, PhoneAccountHandle handle) {
802 Log.i(this, "setBoundAndWaitingForOutgoingCall: " + isBound);
803 mBoundAndWaitingForOutgoingCall = isBound;
804 mThemeColorManager.setPendingPhoneAccountHandle(handle);
805 if (isBound && mInCallState == InCallState.NO_CALLS) {
806 mInCallState = InCallState.OUTGOING;
807 }
808 }
809
810 public void onShrinkAnimationComplete() {
811 if (mAwaitingCallListUpdate) {
812 onCallListChange(mCallList);
813 }
814 }
815
816 public void addIncomingCallListener(IncomingCallListener listener) {
817 Objects.requireNonNull(listener);
818 mIncomingCallListeners.add(listener);
819 }
820
821 public void removeIncomingCallListener(IncomingCallListener listener) {
822 if (listener != null) {
823 mIncomingCallListeners.remove(listener);
824 }
825 }
826
827 public void addListener(InCallStateListener listener) {
828 Objects.requireNonNull(listener);
829 mListeners.add(listener);
830 }
831
832 public void removeListener(InCallStateListener listener) {
833 if (listener != null) {
834 mListeners.remove(listener);
835 }
836 }
837
838 public void addDetailsListener(InCallDetailsListener listener) {
839 Objects.requireNonNull(listener);
840 mDetailsListeners.add(listener);
841 }
842
843 public void removeDetailsListener(InCallDetailsListener listener) {
844 if (listener != null) {
845 mDetailsListeners.remove(listener);
846 }
847 }
848
849 public void addCanAddCallListener(CanAddCallListener listener) {
850 Objects.requireNonNull(listener);
851 mCanAddCallListeners.add(listener);
852 }
853
854 public void removeCanAddCallListener(CanAddCallListener listener) {
855 if (listener != null) {
856 mCanAddCallListeners.remove(listener);
857 }
858 }
859
860 public void addOrientationListener(InCallOrientationListener listener) {
861 Objects.requireNonNull(listener);
862 mOrientationListeners.add(listener);
863 }
864
865 public void removeOrientationListener(InCallOrientationListener listener) {
866 if (listener != null) {
867 mOrientationListeners.remove(listener);
868 }
869 }
870
871 public void addInCallEventListener(InCallEventListener listener) {
872 Objects.requireNonNull(listener);
873 mInCallEventListeners.add(listener);
874 }
875
876 public void removeInCallEventListener(InCallEventListener listener) {
877 if (listener != null) {
878 mInCallEventListeners.remove(listener);
879 }
880 }
881
882 public ProximitySensor getProximitySensor() {
883 return mProximitySensor;
884 }
885
886 public PseudoScreenState getPseudoScreenState() {
887 return mPseudoScreenState;
888 }
889
890 /** Returns true if the incall app is the foreground application. */
891 public boolean isShowingInCallUi() {
892 if (!isActivityStarted()) {
893 return false;
894 }
895 if (mManageConferenceActivity != null && mManageConferenceActivity.isVisible()) {
896 return true;
897 }
898 return mInCallActivity.isVisible();
899 }
900
901 /**
902 * Returns true if the activity has been created and is running. Returns true as long as activity
903 * is not destroyed or finishing. This ensures that we return true even if the activity is paused
904 * (not in foreground).
905 */
906 public boolean isActivityStarted() {
907 return (mInCallActivity != null
908 && !mInCallActivity.isDestroyed()
909 && !mInCallActivity.isFinishing());
910 }
911
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700912 private boolean isActivityVisible() {
913 return mInCallActivity != null && mInCallActivity.isVisible();
914 }
915
916 boolean shouldShowFullScreenNotification() {
917 /**
918 * This is to cover the case where the incall activity is started but in the background, e.g.
919 * when the user pressed Home from the account selection dialog or an existing call. In the case
920 * that incall activity is already visible, there's no need to configure the notification with a
921 * full screen intent.
922 */
923 LogUtil.d(
924 "InCallPresenter.shouldShowFullScreenNotification",
925 "isActivityVisible: %b",
926 isActivityVisible());
927 return !isActivityVisible();
928 }
929
Eric Erfanianccca3152017-02-22 16:32:36 -0800930 /**
931 * Determines if the In-Call app is currently changing configuration.
932 *
933 * @return {@code true} if the In-Call app is changing configuration.
934 */
935 public boolean isChangingConfigurations() {
936 return mIsChangingConfigurations;
937 }
938
939 /**
940 * Tracks whether the In-Call app is currently in the process of changing configuration (i.e.
941 * screen orientation).
942 */
943 /*package*/
944 void updateIsChangingConfigurations() {
945 mIsChangingConfigurations = false;
946 if (mInCallActivity != null) {
947 mIsChangingConfigurations = mInCallActivity.isChangingConfigurations();
948 }
949 Log.v(this, "updateIsChangingConfigurations = " + mIsChangingConfigurations);
950 }
951
952 /** Called when the activity goes in/out of the foreground. */
953 public void onUiShowing(boolean showing) {
954 // We need to update the notification bar when we leave the UI because that
955 // could trigger it to show again.
956 if (mStatusBarNotifier != null) {
957 mStatusBarNotifier.updateNotification(mCallList);
958 }
959
960 if (mProximitySensor != null) {
961 mProximitySensor.onInCallShowing(showing);
962 }
963
964 Intent broadcastIntent = Bindings.get(mContext).getUiReadyBroadcastIntent(mContext);
965 if (broadcastIntent != null) {
966 broadcastIntent.putExtra(EXTRA_FIRST_TIME_SHOWN, !mIsActivityPreviouslyStarted);
967
968 if (showing) {
969 Log.d(this, "Sending sticky broadcast: ", broadcastIntent);
970 mContext.sendStickyBroadcast(broadcastIntent);
971 } else {
972 Log.d(this, "Removing sticky broadcast: ", broadcastIntent);
973 mContext.removeStickyBroadcast(broadcastIntent);
974 }
975 }
976
977 if (showing) {
978 mIsActivityPreviouslyStarted = true;
979 } else {
980 updateIsChangingConfigurations();
981 }
982
983 for (InCallUiListener listener : mInCallUiListeners) {
984 listener.onUiShowing(showing);
985 }
986
987 if (mInCallActivity != null) {
988 // Re-evaluate which fragment is being shown.
989 mInCallActivity.onPrimaryCallStateChanged();
990 }
991 }
992
993 public void addInCallUiListener(InCallUiListener listener) {
994 mInCallUiListeners.add(listener);
995 }
996
997 public boolean removeInCallUiListener(InCallUiListener listener) {
998 return mInCallUiListeners.remove(listener);
999 }
1000
1001 /*package*/
1002 void onActivityStarted() {
1003 Log.d(this, "onActivityStarted");
1004 notifyVideoPauseController(true);
1005 mStatusBarNotifier.updateNotification(mCallList);
1006 }
1007
1008 /*package*/
1009 void onActivityStopped() {
1010 Log.d(this, "onActivityStopped");
1011 notifyVideoPauseController(false);
1012 }
1013
1014 private void notifyVideoPauseController(boolean showing) {
1015 Log.d(
1016 this, "notifyVideoPauseController: mIsChangingConfigurations=" + mIsChangingConfigurations);
1017 if (!mIsChangingConfigurations) {
1018 VideoPauseController.getInstance().onUiShowing(showing);
1019 }
1020 }
1021
1022 /** Brings the app into the foreground if possible. */
1023 public void bringToForeground(boolean showDialpad) {
1024 // Before we bring the incall UI to the foreground, we check to see if:
1025 // 1. It is not currently in the foreground
1026 // 2. We are in a state where we want to show the incall ui (i.e. there are calls to
1027 // be displayed)
1028 // If the activity hadn't actually been started previously, yet there are still calls
1029 // present (e.g. a call was accepted by a bluetooth or wired headset), we want to
1030 // bring it up the UI regardless.
1031 if (!isShowingInCallUi() && mInCallState != InCallState.NO_CALLS) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001032 showInCall(showDialpad, false /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001033 }
1034 }
1035
1036 public void onPostDialCharWait(String callId, String chars) {
1037 if (isActivityStarted()) {
1038 mInCallActivity.showPostCharWaitDialog(callId, chars);
1039 }
1040 }
1041
1042 /**
1043 * Handles the green CALL key while in-call.
1044 *
1045 * @return true if we consumed the event.
1046 */
1047 public boolean handleCallKey() {
1048 LogUtil.v("InCallPresenter.handleCallKey", null);
1049
1050 // The green CALL button means either "Answer", "Unhold", or
1051 // "Swap calls", or can be a no-op, depending on the current state
1052 // of the Phone.
1053
1054 /** INCOMING CALL */
1055 final CallList calls = mCallList;
1056 final DialerCall incomingCall = calls.getIncomingCall();
1057 LogUtil.v("InCallPresenter.handleCallKey", "incomingCall: " + incomingCall);
1058
1059 // (1) Attempt to answer a call
1060 if (incomingCall != null) {
1061 incomingCall.answer(VideoProfile.STATE_AUDIO_ONLY);
1062 return true;
1063 }
1064
1065 /** STATE_ACTIVE CALL */
1066 final DialerCall activeCall = calls.getActiveCall();
1067 if (activeCall != null) {
1068 // TODO: This logic is repeated from CallButtonPresenter.java. We should
1069 // consolidate this logic.
1070 final boolean canMerge =
1071 activeCall.can(android.telecom.Call.Details.CAPABILITY_MERGE_CONFERENCE);
1072 final boolean canSwap =
1073 activeCall.can(android.telecom.Call.Details.CAPABILITY_SWAP_CONFERENCE);
1074
1075 Log.v(
1076 this, "activeCall: " + activeCall + ", canMerge: " + canMerge + ", canSwap: " + canSwap);
1077
1078 // (2) Attempt actions on conference calls
1079 if (canMerge) {
1080 TelecomAdapter.getInstance().merge(activeCall.getId());
1081 return true;
1082 } else if (canSwap) {
1083 TelecomAdapter.getInstance().swap(activeCall.getId());
1084 return true;
1085 }
1086 }
1087
1088 /** BACKGROUND CALL */
1089 final DialerCall heldCall = calls.getBackgroundCall();
1090 if (heldCall != null) {
1091 // We have a hold call so presumeable it will always support HOLD...but
1092 // there is no harm in double checking.
1093 final boolean canHold = heldCall.can(android.telecom.Call.Details.CAPABILITY_HOLD);
1094
1095 Log.v(this, "heldCall: " + heldCall + ", canHold: " + canHold);
1096
1097 // (4) unhold call
1098 if (heldCall.getState() == DialerCall.State.ONHOLD && canHold) {
1099 heldCall.unhold();
1100 return true;
1101 }
1102 }
1103
1104 // Always consume hard keys
1105 return true;
1106 }
1107
1108 /**
1109 * A dialog could have prevented in-call screen from being previously finished. This function
1110 * checks to see if there should be any UI left and if not attempts to tear down the UI.
1111 */
1112 public void onDismissDialog() {
1113 Log.i(this, "Dialog dismissed");
1114 if (mInCallState == InCallState.NO_CALLS) {
1115 attemptFinishActivity();
1116 attemptCleanup();
1117 }
1118 }
1119
1120 /** Clears the previous fullscreen state. */
1121 public void clearFullscreen() {
1122 mIsFullScreen = false;
1123 }
1124
1125 /**
1126 * Changes the fullscreen mode of the in-call UI.
1127 *
1128 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1129 * otherwise.
1130 */
1131 public void setFullScreen(boolean isFullScreen) {
1132 setFullScreen(isFullScreen, false /* force */);
1133 }
1134
1135 /**
1136 * Changes the fullscreen mode of the in-call UI.
1137 *
1138 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1139 * otherwise.
1140 * @param force {@code true} if fullscreen mode should be set regardless of its current state.
1141 */
1142 public void setFullScreen(boolean isFullScreen, boolean force) {
1143 Log.i(this, "setFullScreen = " + isFullScreen);
1144
1145 // As a safeguard, ensure we cannot enter fullscreen if the dialpad is shown.
1146 if (isDialpadVisible()) {
1147 isFullScreen = false;
1148 Log.v(this, "setFullScreen overridden as dialpad is shown = " + isFullScreen);
1149 }
1150
1151 if (mIsFullScreen == isFullScreen && !force) {
1152 Log.v(this, "setFullScreen ignored as already in that state.");
1153 return;
1154 }
1155 mIsFullScreen = isFullScreen;
1156 notifyFullscreenModeChange(mIsFullScreen);
1157 }
1158
1159 /**
1160 * @return {@code true} if the in-call ui is currently in fullscreen mode, {@code false}
1161 * otherwise.
1162 */
1163 public boolean isFullscreen() {
1164 return mIsFullScreen;
1165 }
1166
1167 /**
1168 * Called by the {@link VideoCallPresenter} to inform of a change in full screen video status.
1169 *
1170 * @param isFullscreenMode {@code True} if entering full screen mode.
1171 */
1172 public void notifyFullscreenModeChange(boolean isFullscreenMode) {
1173 for (InCallEventListener listener : mInCallEventListeners) {
1174 listener.onFullscreenModeChanged(isFullscreenMode);
1175 }
1176 }
1177
1178 /**
1179 * For some disconnected causes, we show a dialog. This calls into the activity to show the dialog
1180 * if appropriate for the call.
1181 */
1182 private void maybeShowErrorDialogOnDisconnect(DialerCall call) {
1183 // For newly disconnected calls, we may want to show a dialog on specific error conditions
1184 if (isActivityStarted() && call.getState() == DialerCall.State.DISCONNECTED) {
1185 if (call.getAccountHandle() == null && !call.isConferenceCall()) {
1186 setDisconnectCauseForMissingAccounts(call);
1187 }
1188 mInCallActivity.maybeShowErrorDialogOnDisconnect(call.getDisconnectCause());
1189 }
1190 }
1191
1192 /**
1193 * When the state of in-call changes, this is the first method to get called. It determines if the
1194 * UI needs to be started or finished depending on the new state and does it.
1195 */
1196 private InCallState startOrFinishUi(InCallState newState) {
1197 Log.d(this, "startOrFinishUi: " + mInCallState + " -> " + newState);
1198
1199 // TODO: Consider a proper state machine implementation
1200
1201 // If the state isn't changing we have already done any starting/stopping of activities in
1202 // a previous pass...so lets cut out early
1203 if (newState == mInCallState) {
1204 return newState;
1205 }
1206
1207 // A new Incoming call means that the user needs to be notified of the the call (since
1208 // it wasn't them who initiated it). We do this through full screen notifications and
1209 // happens indirectly through {@link StatusBarNotifier}.
1210 //
1211 // The process for incoming calls is as follows:
1212 //
1213 // 1) CallList - Announces existence of new INCOMING call
1214 // 2) InCallPresenter - Gets announcement and calculates that the new InCallState
1215 // - should be set to INCOMING.
1216 // 3) InCallPresenter - This method is called to see if we need to start or finish
1217 // the app given the new state.
1218 // 4) StatusBarNotifier - Listens to InCallState changes. InCallPresenter calls
1219 // StatusBarNotifier explicitly to issue a FullScreen Notification
1220 // that will either start the InCallActivity or show the user a
1221 // top-level notification dialog if the user is in an immersive app.
1222 // That notification can also start the InCallActivity.
1223 // 5) InCallActivity - Main activity starts up and at the end of its onCreate will
1224 // call InCallPresenter::setActivity() to let the presenter
1225 // know that start-up is complete.
1226 //
1227 // [ AND NOW YOU'RE IN THE CALL. voila! ]
1228 //
1229 // Our app is started using a fullScreen notification. We need to do this whenever
1230 // we get an incoming call. Depending on the current context of the device, either a
1231 // incoming call HUN or the actual InCallActivity will be shown.
1232 final boolean startIncomingCallSequence = (InCallState.INCOMING == newState);
1233
1234 // A dialog to show on top of the InCallUI to select a PhoneAccount
1235 final boolean showAccountPicker = (InCallState.WAITING_FOR_ACCOUNT == newState);
1236
1237 // A new outgoing call indicates that the user just now dialed a number and when that
1238 // happens we need to display the screen immediately or show an account picker dialog if
1239 // no default is set. However, if the main InCallUI is already visible, we do not want to
1240 // re-initiate the start-up animation, so we do not need to do anything here.
1241 //
1242 // It is also possible to go into an intermediate state where the call has been initiated
1243 // but Telecom has not yet returned with the details of the call (handle, gateway, etc.).
1244 // This pending outgoing state can also launch the call screen.
1245 //
1246 // This is different from the incoming call sequence because we do not need to shock the
1247 // user with a top-level notification. Just show the call UI normally.
1248 boolean callCardFragmentVisible =
1249 mInCallActivity != null && mInCallActivity.getCallCardFragmentVisible();
1250 final boolean mainUiNotVisible = !isShowingInCallUi() || !callCardFragmentVisible;
1251 boolean showCallUi = InCallState.OUTGOING == newState && mainUiNotVisible;
1252
1253 // Direct transition from PENDING_OUTGOING -> INCALL means that there was an error in the
1254 // outgoing call process, so the UI should be brought up to show an error dialog.
1255 showCallUi |=
1256 (InCallState.PENDING_OUTGOING == mInCallState
1257 && InCallState.INCALL == newState
1258 && !isShowingInCallUi());
1259
1260 // Another exception - InCallActivity is in charge of disconnecting a call with no
1261 // valid accounts set. Bring the UI up if this is true for the current pending outgoing
1262 // call so that:
1263 // 1) The call can be disconnected correctly
1264 // 2) The UI comes up and correctly displays the error dialog.
1265 // TODO: Remove these special case conditions by making InCallPresenter a true state
1266 // machine. Telecom should also be the component responsible for disconnecting a call
1267 // with no valid accounts.
1268 showCallUi |=
1269 InCallState.PENDING_OUTGOING == newState
1270 && mainUiNotVisible
1271 && isCallWithNoValidAccounts(mCallList.getPendingOutgoingCall());
1272
1273 // The only time that we have an instance of mInCallActivity and it isn't started is
1274 // when it is being destroyed. In that case, lets avoid bringing up another instance of
1275 // the activity. When it is finally destroyed, we double check if we should bring it back
1276 // up so we aren't going to lose anything by avoiding a second startup here.
1277 boolean activityIsFinishing = mInCallActivity != null && !isActivityStarted();
1278 if (activityIsFinishing) {
1279 Log.i(this, "Undo the state change: " + newState + " -> " + mInCallState);
1280 return mInCallState;
1281 }
1282
1283 // We're about the bring up the in-call UI for outgoing and incoming call. If we still have
1284 // dialogs up, we need to clear them out before showing in-call screen. This is necessary
1285 // to fix the bug that dialog will show up when data reaches limit even after makeing new
1286 // outgoing call after user ignore it by pressing home button.
1287 if ((newState == InCallState.INCOMING || newState == InCallState.PENDING_OUTGOING)
1288 && !showCallUi
1289 && isActivityStarted()) {
1290 mInCallActivity.dismissPendingDialogs();
1291 }
1292
1293 if (showCallUi || showAccountPicker) {
1294 Log.i(this, "Start in call UI");
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001295 showInCall(false /* showDialpad */, !showAccountPicker /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001296 } else if (startIncomingCallSequence) {
1297 Log.i(this, "Start Full Screen in call UI");
1298
1299 if (!startUi()) {
1300 // startUI refused to start the UI. This indicates that it needed to restart the
1301 // activity. When it finally restarts, it will call us back, so we do not actually
1302 // change the state yet (we return mInCallState instead of newState).
1303 return mInCallState;
1304 }
1305 } else if (newState == InCallState.NO_CALLS) {
1306 // The new state is the no calls state. Tear everything down.
1307 attemptFinishActivity();
1308 attemptCleanup();
1309 }
1310
1311 return newState;
1312 }
1313
1314 /**
1315 * Sets the DisconnectCause for a call that was disconnected because it was missing a PhoneAccount
1316 * or PhoneAccounts to select from.
1317 */
1318 private void setDisconnectCauseForMissingAccounts(DialerCall call) {
1319
1320 Bundle extras = call.getIntentExtras();
1321 // Initialize the extras bundle to avoid NPE
1322 if (extras == null) {
1323 extras = new Bundle();
1324 }
1325
1326 final List<PhoneAccountHandle> phoneAccountHandles =
1327 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
1328
1329 if (phoneAccountHandles == null || phoneAccountHandles.isEmpty()) {
1330 String scheme = call.getHandle().getScheme();
1331 final String errorMsg =
1332 PhoneAccount.SCHEME_TEL.equals(scheme)
1333 ? mContext.getString(R.string.callFailed_simError)
1334 : mContext.getString(R.string.incall_error_supp_service_unknown);
1335 DisconnectCause disconnectCause =
1336 new DisconnectCause(DisconnectCause.ERROR, null, errorMsg, errorMsg);
1337 call.setDisconnectCause(disconnectCause);
1338 }
1339 }
1340
1341 private boolean startUi() {
1342 boolean isCallWaiting =
1343 mCallList.getActiveCall() != null && mCallList.getIncomingCall() != null;
1344
1345 if (isCallWaiting) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001346 showInCall(false, false);
Eric Erfanianccca3152017-02-22 16:32:36 -08001347 } else {
1348 mStatusBarNotifier.updateNotification(mCallList);
1349 }
1350 return true;
1351 }
1352
1353 /**
1354 * @return {@code true} if the InCallPresenter is ready to be torn down, {@code false} otherwise.
1355 * Calling classes should use this as an indication whether to interact with the
1356 * InCallPresenter or not.
1357 */
1358 public boolean isReadyForTearDown() {
1359 return mInCallActivity == null && !mServiceConnected && mInCallState == InCallState.NO_CALLS;
1360 }
1361
1362 /**
1363 * Checks to see if both the UI is gone and the service is disconnected. If so, tear it all down.
1364 */
1365 private void attemptCleanup() {
1366 if (isReadyForTearDown()) {
1367 Log.i(this, "Cleaning up");
1368
1369 cleanupSurfaces();
1370
1371 mIsActivityPreviouslyStarted = false;
1372 mIsChangingConfigurations = false;
1373
1374 // blow away stale contact info so that we get fresh data on
1375 // the next set of calls
1376 if (mContactInfoCache != null) {
1377 mContactInfoCache.clearCache();
1378 }
1379 mContactInfoCache = null;
1380
1381 if (mProximitySensor != null) {
1382 removeListener(mProximitySensor);
1383 mProximitySensor.tearDown();
1384 }
1385 mProximitySensor = null;
1386
1387 if (mStatusBarNotifier != null) {
1388 removeListener(mStatusBarNotifier);
1389 }
1390 if (mExternalCallNotifier != null && mExternalCallList != null) {
1391 mExternalCallList.removeExternalCallListener(mExternalCallNotifier);
1392 }
1393 mStatusBarNotifier = null;
1394
1395 if (mCallList != null) {
1396 mCallList.removeListener(this);
1397 mCallList.removeListener(mSpamCallListListener);
1398 }
1399 mCallList = null;
1400
1401 mContext = null;
1402 mInCallActivity = null;
1403 mManageConferenceActivity = null;
1404
1405 mListeners.clear();
1406 mIncomingCallListeners.clear();
1407 mDetailsListeners.clear();
1408 mCanAddCallListeners.clear();
1409 mOrientationListeners.clear();
1410 mInCallEventListeners.clear();
1411 mInCallUiListeners.clear();
1412
1413 Log.d(this, "Finished InCallPresenter.CleanUp");
1414 }
1415 }
1416
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001417 public void showInCall(boolean showDialpad, boolean newOutgoingCall) {
Eric Erfanianccca3152017-02-22 16:32:36 -08001418 Log.i(this, "Showing InCallActivity");
1419 mContext.startActivity(
1420 InCallActivity.getIntent(
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001421 mContext, showDialpad, newOutgoingCall, false /* forFullScreen */));
Eric Erfanianccca3152017-02-22 16:32:36 -08001422 }
1423
1424 public void onServiceBind() {
1425 mServiceBound = true;
1426 }
1427
1428 public void onServiceUnbind() {
1429 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(false, null);
1430 mServiceBound = false;
1431 }
1432
1433 public boolean isServiceBound() {
1434 return mServiceBound;
1435 }
1436
1437 public void maybeStartRevealAnimation(Intent intent) {
1438 if (intent == null || mInCallActivity != null) {
1439 return;
1440 }
1441 final Bundle extras = intent.getBundleExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS);
1442 if (extras == null) {
1443 // Incoming call, just show the in-call UI directly.
1444 return;
1445 }
1446
1447 if (extras.containsKey(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS)) {
1448 // Account selection dialog will show up so don't show the animation.
1449 return;
1450 }
1451
1452 final PhoneAccountHandle accountHandle =
1453 intent.getParcelableExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
1454 final Point touchPoint = extras.getParcelable(TouchPointManager.TOUCH_POINT);
Eric Erfanianccca3152017-02-22 16:32:36 -08001455
1456 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(true, accountHandle);
1457
1458 final Intent activityIntent =
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001459 InCallActivity.getIntent(mContext, false, true, false /* forFullScreen */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001460 activityIntent.putExtra(TouchPointManager.TOUCH_POINT, touchPoint);
1461 mContext.startActivity(activityIntent);
1462 }
1463
1464 /**
1465 * Retrieves the current in-call camera manager instance, creating if necessary.
1466 *
1467 * @return The {@link InCallCameraManager}.
1468 */
1469 public InCallCameraManager getInCallCameraManager() {
1470 synchronized (this) {
1471 if (mInCallCameraManager == null) {
1472 mInCallCameraManager = new InCallCameraManager(mContext);
1473 }
1474
1475 return mInCallCameraManager;
1476 }
1477 }
1478
1479 /**
1480 * Notifies listeners of changes in orientation and notify calls of rotation angle change.
1481 *
1482 * @param orientation The screen orientation of the device (one of: {@link
1483 * InCallOrientationEventListener#SCREEN_ORIENTATION_0}, {@link
1484 * InCallOrientationEventListener#SCREEN_ORIENTATION_90}, {@link
1485 * InCallOrientationEventListener#SCREEN_ORIENTATION_180}, {@link
1486 * InCallOrientationEventListener#SCREEN_ORIENTATION_270}).
1487 */
1488 public void onDeviceOrientationChange(@ScreenOrientation int orientation) {
1489 Log.d(this, "onDeviceOrientationChange: orientation= " + orientation);
1490
1491 if (mCallList != null) {
1492 mCallList.notifyCallsOfDeviceRotation(orientation);
1493 } else {
1494 Log.w(this, "onDeviceOrientationChange: CallList is null.");
1495 }
1496
1497 // Notify listeners of device orientation changed.
1498 for (InCallOrientationListener listener : mOrientationListeners) {
1499 listener.onDeviceOrientationChanged(orientation);
1500 }
1501 }
1502
1503 /**
1504 * Configures the in-call UI activity so it can change orientations or not. Enables the
1505 * orientation event listener if allowOrientationChange is true, disables it if false.
1506 *
1507 * @param allowOrientationChange {@code true} if the in-call UI can change between portrait and
1508 * landscape. {@code false} if the in-call UI should be locked in portrait.
1509 */
1510 public void setInCallAllowsOrientationChange(boolean allowOrientationChange) {
1511 if (mInCallActivity == null) {
1512 Log.e(this, "InCallActivity is null. Can't set requested orientation.");
1513 return;
1514 }
1515 mInCallActivity.setAllowOrientationChange(allowOrientationChange);
1516 }
1517
1518 public void enableScreenTimeout(boolean enable) {
1519 Log.v(this, "enableScreenTimeout: value=" + enable);
1520 if (mInCallActivity == null) {
1521 Log.e(this, "enableScreenTimeout: InCallActivity is null.");
1522 return;
1523 }
1524
1525 final Window window = mInCallActivity.getWindow();
1526 if (enable) {
1527 window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1528 } else {
1529 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1530 }
1531 }
1532
1533 /**
1534 * Hides or shows the conference manager fragment.
1535 *
1536 * @param show {@code true} if the conference manager should be shown, {@code false} if it should
1537 * be hidden.
1538 */
1539 public void showConferenceCallManager(boolean show) {
1540 if (mInCallActivity != null) {
1541 mInCallActivity.showConferenceFragment(show);
1542 }
1543 if (!show && mManageConferenceActivity != null) {
1544 mManageConferenceActivity.finish();
1545 }
1546 }
1547
1548 /**
1549 * Determines if the dialpad is visible.
1550 *
1551 * @return {@code true} if the dialpad is visible, {@code false} otherwise.
1552 */
1553 public boolean isDialpadVisible() {
1554 if (mInCallActivity == null) {
1555 return false;
1556 }
1557 return mInCallActivity.isDialpadVisible();
1558 }
1559
1560 public ThemeColorManager getThemeColorManager() {
1561 return mThemeColorManager;
1562 }
1563
1564 /** Called when the foreground call changes. */
1565 public void onForegroundCallChanged(DialerCall newForegroundCall) {
1566 mThemeColorManager.onForegroundCallChanged(mContext, newForegroundCall);
1567 if (mInCallActivity != null) {
1568 mInCallActivity.onForegroundCallChanged(newForegroundCall);
1569 }
1570 }
1571
1572 public InCallActivity getActivity() {
1573 return mInCallActivity;
1574 }
1575
1576 /** Called when the UI begins, and starts the callstate callbacks if necessary. */
1577 public void setActivity(InCallActivity inCallActivity) {
1578 if (inCallActivity == null) {
1579 throw new IllegalArgumentException("registerActivity cannot be called with null");
1580 }
1581 if (mInCallActivity != null && mInCallActivity != inCallActivity) {
1582 Log.w(this, "Setting a second activity before destroying the first.");
1583 }
1584 updateActivity(inCallActivity);
1585 }
1586
1587 ExternalCallNotifier getExternalCallNotifier() {
1588 return mExternalCallNotifier;
1589 }
1590
1591 VideoSurfaceTexture getLocalVideoSurfaceTexture() {
1592 if (mLocalVideoSurfaceTexture == null) {
1593 mLocalVideoSurfaceTexture = VideoSurfaceBindings.createLocalVideoSurfaceTexture();
1594 }
1595 return mLocalVideoSurfaceTexture;
1596 }
1597
1598 VideoSurfaceTexture getRemoteVideoSurfaceTexture() {
1599 if (mRemoteVideoSurfaceTexture == null) {
1600 mRemoteVideoSurfaceTexture = VideoSurfaceBindings.createRemoteVideoSurfaceTexture();
1601 }
1602 return mRemoteVideoSurfaceTexture;
1603 }
1604
1605 void cleanupSurfaces() {
1606 if (mRemoteVideoSurfaceTexture != null) {
1607 mRemoteVideoSurfaceTexture.setDoneWithSurface();
1608 mRemoteVideoSurfaceTexture = null;
1609 }
1610 if (mLocalVideoSurfaceTexture != null) {
1611 mLocalVideoSurfaceTexture.setDoneWithSurface();
1612 mLocalVideoSurfaceTexture = null;
1613 }
1614 }
1615
1616 /** All the main states of InCallActivity. */
1617 public enum InCallState {
1618 // InCall Screen is off and there are no calls
1619 NO_CALLS,
1620
1621 // Incoming-call screen is up
1622 INCOMING,
1623
1624 // In-call experience is showing
1625 INCALL,
1626
1627 // Waiting for user input before placing outgoing call
1628 WAITING_FOR_ACCOUNT,
1629
1630 // UI is starting up but no call has been initiated yet.
1631 // The UI is waiting for Telecom to respond.
1632 PENDING_OUTGOING,
1633
1634 // User is dialing out
1635 OUTGOING;
1636
1637 public boolean isIncoming() {
1638 return (this == INCOMING);
1639 }
1640
1641 public boolean isConnectingOrConnected() {
1642 return (this == INCOMING || this == OUTGOING || this == INCALL);
1643 }
1644 }
1645
1646 /** Interface implemented by classes that need to know about the InCall State. */
1647 public interface InCallStateListener {
1648
1649 // TODO: Enhance state to contain the call objects instead of passing CallList
1650 void onStateChange(InCallState oldState, InCallState newState, CallList callList);
1651 }
1652
1653 public interface IncomingCallListener {
1654
1655 void onIncomingCall(InCallState oldState, InCallState newState, DialerCall call);
1656 }
1657
1658 public interface CanAddCallListener {
1659
1660 void onCanAddCallChanged(boolean canAddCall);
1661 }
1662
1663 public interface InCallDetailsListener {
1664
1665 void onDetailsChanged(DialerCall call, android.telecom.Call.Details details);
1666 }
1667
1668 public interface InCallOrientationListener {
1669
1670 void onDeviceOrientationChanged(@ScreenOrientation int orientation);
1671 }
1672
1673 /**
1674 * Interface implemented by classes that need to know about events which occur within the In-Call
1675 * UI. Used as a means of communicating between fragments that make up the UI.
1676 */
1677 public interface InCallEventListener {
1678
1679 void onFullscreenModeChanged(boolean isFullscreenMode);
1680 }
1681
1682 public interface InCallUiListener {
1683
1684 void onUiShowing(boolean showing);
1685 }
1686}