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