blob: 3debd704e5c62f54b8dc58608973ad8f5a40d9fc [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;
Eric Erfanian2ca43182017-08-31 06:57:16 -070024import android.os.Trace;
twyen8efb4952017-10-06 16:35:54 -070025import android.support.annotation.MainThread;
Eric Erfanianccca3152017-02-22 16:32:36 -080026import android.support.annotation.NonNull;
27import android.support.annotation.Nullable;
28import android.support.annotation.VisibleForTesting;
Eric Erfanian83b20212017-05-31 08:53:10 -070029import android.support.v4.os.UserManagerCompat;
Eric Erfanianccca3152017-02-22 16:32:36 -080030import android.telecom.Call.Details;
yueg77cb8e52017-10-27 16:42:51 -070031import android.telecom.CallAudioState;
Eric Erfanianccca3152017-02-22 16:32:36 -080032import android.telecom.DisconnectCause;
33import android.telecom.PhoneAccount;
34import android.telecom.PhoneAccountHandle;
35import android.telecom.TelecomManager;
36import android.telecom.VideoProfile;
37import android.telephony.PhoneStateListener;
38import android.telephony.TelephonyManager;
twyen8efb4952017-10-06 16:35:54 -070039import android.util.ArraySet;
Eric Erfanianccca3152017-02-22 16:32:36 -080040import android.view.Window;
41import android.view.WindowManager;
Eric Erfanianccca3152017-02-22 16:32:36 -080042import com.android.contacts.common.compat.CallCompat;
43import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler;
44import com.android.dialer.blocking.FilteredNumberAsyncQueryHandler.OnCheckBlockedListener;
Eric Erfanian83b20212017-05-31 08:53:10 -070045import com.android.dialer.blocking.FilteredNumberCompat;
Eric Erfanianccca3152017-02-22 16:32:36 -080046import com.android.dialer.blocking.FilteredNumbersUtil;
twyen8efb4952017-10-06 16:35:54 -070047import com.android.dialer.common.Assert;
Eric Erfanianccca3152017-02-22 16:32:36 -080048import com.android.dialer.common.LogUtil;
zachh6a4cebd2017-10-24 17:10:06 -070049import com.android.dialer.common.concurrent.DialerExecutorComponent;
Eric Erfaniand8046e52017-04-06 09:41:50 -070050import com.android.dialer.enrichedcall.EnrichedCallComponent;
Eric Erfanian10b34a52017-05-04 08:23:17 -070051import com.android.dialer.location.GeoUtil;
Eric Erfanian8369df02017-05-03 10:27:13 -070052import com.android.dialer.logging.InteractionEvent;
Eric Erfanianccca3152017-02-22 16:32:36 -080053import com.android.dialer.logging.Logger;
Eric Erfaniand5e47f62017-03-15 14:41:07 -070054import com.android.dialer.postcall.PostCall;
twyena4745bd2017-12-12 18:40:11 -080055import com.android.dialer.telecom.TelecomCallUtil;
Eric Erfanianccca3152017-02-22 16:32:36 -080056import com.android.dialer.telecom.TelecomUtil;
57import com.android.dialer.util.TouchPointManager;
58import com.android.incallui.InCallOrientationEventListener.ScreenOrientation;
59import com.android.incallui.answerproximitysensor.PseudoScreenState;
yueg77cb8e52017-10-27 16:42:51 -070060import com.android.incallui.audiomode.AudioModeProvider;
Eric Erfanianccca3152017-02-22 16:32:36 -080061import com.android.incallui.call.CallList;
62import com.android.incallui.call.DialerCall;
Eric Erfanianccca3152017-02-22 16:32:36 -080063import com.android.incallui.call.ExternalCallList;
Eric Erfanianccca3152017-02-22 16:32:36 -080064import com.android.incallui.call.TelecomAdapter;
Eric Erfanian2ca43182017-08-31 06:57:16 -070065import com.android.incallui.disconnectdialog.DisconnectMessage;
twyen8efb4952017-10-06 16:35:54 -070066import com.android.incallui.incalluilock.InCallUiLock;
Eric Erfanianccca3152017-02-22 16:32:36 -080067import com.android.incallui.latencyreport.LatencyReport;
68import com.android.incallui.legacyblocking.BlockedNumberContentObserver;
69import com.android.incallui.spam.SpamCallListListener;
Eric Erfanianccca3152017-02-22 16:32:36 -080070import com.android.incallui.videosurface.bindings.VideoSurfaceBindings;
71import com.android.incallui.videosurface.protocol.VideoSurfaceTexture;
Eric Erfanian90508232017-03-24 09:31:16 -070072import com.android.incallui.videotech.utils.VideoUtils;
Eric Erfanianccca3152017-02-22 16:32:36 -080073import java.util.Collections;
74import java.util.List;
75import java.util.Objects;
76import java.util.Set;
77import java.util.concurrent.ConcurrentHashMap;
78import java.util.concurrent.CopyOnWriteArrayList;
79import java.util.concurrent.atomic.AtomicBoolean;
80
81/**
82 * Takes updates from the CallList and notifies the InCallActivity (UI) of the changes. Responsible
83 * for starting the activity for a new call and finishing the activity when all calls are
84 * disconnected. Creates and manages the in-call state and provides a listener pattern for the
85 * presenters that want to listen in on the in-call state changes. TODO: This class has become more
86 * of a state machine at this point. Consider renaming.
87 */
yueg77cb8e52017-10-27 16:42:51 -070088public class InCallPresenter implements CallList.Listener, AudioModeProvider.AudioModeListener {
Eric Erfanian2ca43182017-08-31 06:57:16 -070089 private static final String PIXEL2017_SYSTEM_FEATURE =
90 "com.google.android.feature.PIXEL_2017_EXPERIENCE";
Eric Erfanianccca3152017-02-22 16:32:36 -080091
92 private static final long BLOCK_QUERY_TIMEOUT_MS = 1000;
93
94 private static final Bundle EMPTY_EXTRAS = new Bundle();
95
96 private static InCallPresenter sInCallPresenter;
97
98 /**
99 * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is load factor before
100 * resizing, 1 means we only expect a single thread to access the map so make only a single shard
101 */
102 private final Set<InCallStateListener> mListeners =
103 Collections.newSetFromMap(new ConcurrentHashMap<InCallStateListener, Boolean>(8, 0.9f, 1));
104
105 private final List<IncomingCallListener> mIncomingCallListeners = new CopyOnWriteArrayList<>();
106 private final Set<InCallDetailsListener> mDetailsListeners =
107 Collections.newSetFromMap(new ConcurrentHashMap<InCallDetailsListener, Boolean>(8, 0.9f, 1));
108 private final Set<CanAddCallListener> mCanAddCallListeners =
109 Collections.newSetFromMap(new ConcurrentHashMap<CanAddCallListener, Boolean>(8, 0.9f, 1));
110 private final Set<InCallUiListener> mInCallUiListeners =
111 Collections.newSetFromMap(new ConcurrentHashMap<InCallUiListener, Boolean>(8, 0.9f, 1));
112 private final Set<InCallOrientationListener> mOrientationListeners =
113 Collections.newSetFromMap(
114 new ConcurrentHashMap<InCallOrientationListener, Boolean>(8, 0.9f, 1));
115 private final Set<InCallEventListener> mInCallEventListeners =
116 Collections.newSetFromMap(new ConcurrentHashMap<InCallEventListener, Boolean>(8, 0.9f, 1));
117
118 private StatusBarNotifier mStatusBarNotifier;
119 private ExternalCallNotifier mExternalCallNotifier;
120 private ContactInfoCache mContactInfoCache;
121 private Context mContext;
122 private final OnCheckBlockedListener mOnCheckBlockedListener =
123 new OnCheckBlockedListener() {
124 @Override
125 public void onCheckComplete(final Integer id) {
126 if (id != null && id != FilteredNumberAsyncQueryHandler.INVALID_ID) {
127 // Silence the ringer now to prevent ringing and vibration before the call is
128 // terminated when Telecom attempts to add it.
129 TelecomUtil.silenceRinger(mContext);
130 }
131 }
132 };
133 private CallList mCallList;
134 private ExternalCallList mExternalCallList;
135 private InCallActivity mInCallActivity;
136 private ManageConferenceActivity mManageConferenceActivity;
137 private final android.telecom.Call.Callback mCallCallback =
138 new android.telecom.Call.Callback() {
139 @Override
140 public void onPostDialWait(
141 android.telecom.Call telecomCall, String remainingPostDialSequence) {
142 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
143 if (call == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700144 LogUtil.w(
145 "InCallPresenter.onPostDialWait",
146 "DialerCall not found in call list: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800147 return;
148 }
149 onPostDialCharWait(call.getId(), remainingPostDialSequence);
150 }
151
152 @Override
153 public void onDetailsChanged(
154 android.telecom.Call telecomCall, android.telecom.Call.Details details) {
155 final DialerCall call = mCallList.getDialerCallFromTelecomCall(telecomCall);
156 if (call == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700157 LogUtil.w(
158 "InCallPresenter.onDetailsChanged",
159 "DialerCall not found in call list: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800160 return;
161 }
162
163 if (details.hasProperty(Details.PROPERTY_IS_EXTERNAL_CALL)
164 && !mExternalCallList.isCallTracked(telecomCall)) {
165
166 // A regular call became an external call so swap call lists.
Eric Erfanian2ca43182017-08-31 06:57:16 -0700167 LogUtil.i("InCallPresenter.onDetailsChanged", "Call became external: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800168 mCallList.onInternalCallMadeExternal(mContext, telecomCall);
169 mExternalCallList.onCallAdded(telecomCall);
170 return;
171 }
172
173 for (InCallDetailsListener listener : mDetailsListeners) {
174 listener.onDetailsChanged(call, details);
175 }
176 }
177
178 @Override
179 public void onConferenceableCallsChanged(
180 android.telecom.Call telecomCall, List<android.telecom.Call> conferenceableCalls) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700181 LogUtil.i(
182 "InCallPresenter.onConferenceableCallsChanged",
183 "onConferenceableCallsChanged: " + telecomCall);
Eric Erfanianccca3152017-02-22 16:32:36 -0800184 onDetailsChanged(telecomCall, telecomCall.getDetails());
185 }
186 };
187 private InCallState mInCallState = InCallState.NO_CALLS;
188 private ProximitySensor mProximitySensor;
189 private final PseudoScreenState mPseudoScreenState = new PseudoScreenState();
190 private boolean mServiceConnected;
Eric Erfanianccca3152017-02-22 16:32:36 -0800191 private InCallCameraManager mInCallCameraManager;
192 private FilteredNumberAsyncQueryHandler mFilteredQueryHandler;
193 private CallList.Listener mSpamCallListListener;
194 /** Whether or not we are currently bound and waiting for Telecom to send us a new call. */
195 private boolean mBoundAndWaitingForOutgoingCall;
196 /** Determines if the InCall UI is in fullscreen mode or not. */
197 private boolean mIsFullScreen = false;
198
Eric Erfanian2ca43182017-08-31 06:57:16 -0700199 private boolean mScreenTimeoutEnabled = true;
200
Eric Erfanianccca3152017-02-22 16:32:36 -0800201 private PhoneStateListener mPhoneStateListener =
202 new PhoneStateListener() {
203 @Override
204 public void onCallStateChanged(int state, String incomingNumber) {
205 if (state == TelephonyManager.CALL_STATE_RINGING) {
206 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
207 return;
208 }
209 // Check if the number is blocked, to silence the ringer.
210 String countryIso = GeoUtil.getCurrentCountryIso(mContext);
211 mFilteredQueryHandler.isBlockedNumber(
212 mOnCheckBlockedListener, incomingNumber, countryIso);
213 }
214 }
215 };
twyena4745bd2017-12-12 18:40:11 -0800216
Eric Erfanianccca3152017-02-22 16:32:36 -0800217 /** Whether or not InCallService is bound to Telecom. */
218 private boolean mServiceBound = false;
219
220 /**
221 * When configuration changes Android kills the current activity and starts a new one. The flag is
222 * used to check if full clean up is necessary (activity is stopped and new activity won't be
223 * started), or if a new activity will be started right after the current one is destroyed, and
224 * therefore no need in release all resources.
225 */
226 private boolean mIsChangingConfigurations = false;
227
228 private boolean mAwaitingCallListUpdate = false;
229
230 private ExternalCallList.ExternalCallListener mExternalCallListener =
231 new ExternalCallList.ExternalCallListener() {
232
233 @Override
234 public void onExternalCallPulled(android.telecom.Call call) {
235 // Note: keep this code in sync with InCallPresenter#onCallAdded
236 LatencyReport latencyReport = new LatencyReport(call);
237 latencyReport.onCallBlockingDone();
238 // Note: External calls do not require spam checking.
239 mCallList.onCallAdded(mContext, call, latencyReport);
240 call.registerCallback(mCallCallback);
241 }
242
243 @Override
244 public void onExternalCallAdded(android.telecom.Call call) {
245 // No-op
246 }
247
248 @Override
249 public void onExternalCallRemoved(android.telecom.Call call) {
250 // No-op
251 }
252
253 @Override
254 public void onExternalCallUpdated(android.telecom.Call call) {
255 // No-op
256 }
257 };
258
259 private ThemeColorManager mThemeColorManager;
260 private VideoSurfaceTexture mLocalVideoSurfaceTexture;
261 private VideoSurfaceTexture mRemoteVideoSurfaceTexture;
262
Eric Erfanian10b34a52017-05-04 08:23:17 -0700263 /** Inaccessible constructor. Must use getRunningInstance() to get this singleton. */
Eric Erfanianccca3152017-02-22 16:32:36 -0800264 @VisibleForTesting
265 InCallPresenter() {}
266
267 public static synchronized InCallPresenter getInstance() {
268 if (sInCallPresenter == null) {
wangqic8cf79e2017-10-17 09:21:00 -0700269 Trace.beginSection("InCallPresenter.Constructor");
Eric Erfanianccca3152017-02-22 16:32:36 -0800270 sInCallPresenter = new InCallPresenter();
wangqic8cf79e2017-10-17 09:21:00 -0700271 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800272 }
273 return sInCallPresenter;
274 }
275
Eric Erfanian10b34a52017-05-04 08:23:17 -0700276 @VisibleForTesting
277 public static synchronized void setInstanceForTesting(InCallPresenter inCallPresenter) {
278 sInCallPresenter = inCallPresenter;
279 }
280
Eric Erfanianccca3152017-02-22 16:32:36 -0800281 /**
282 * Determines whether or not a call has no valid phone accounts that can be used to make the call
283 * with. Emergency calls do not require a phone account.
284 *
285 * @param call to check accounts for.
286 * @return {@code true} if the call has no call capable phone accounts set, {@code false} if the
287 * call contains a phone account that could be used to initiate it with, or is an emergency
288 * call.
289 */
290 public static boolean isCallWithNoValidAccounts(DialerCall call) {
291 if (call != null && !call.isEmergencyCall()) {
292 Bundle extras = call.getIntentExtras();
293
294 if (extras == null) {
295 extras = EMPTY_EXTRAS;
296 }
297
298 final List<PhoneAccountHandle> phoneAccountHandles =
299 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
300
301 if ((call.getAccountHandle() == null
302 && (phoneAccountHandles == null || phoneAccountHandles.isEmpty()))) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700303 LogUtil.i(
304 "InCallPresenter.isCallWithNoValidAccounts", "No valid accounts for call " + call);
Eric Erfanianccca3152017-02-22 16:32:36 -0800305 return true;
306 }
307 }
308 return false;
309 }
310
311 public InCallState getInCallState() {
312 return mInCallState;
313 }
314
315 public CallList getCallList() {
316 return mCallList;
317 }
318
319 public void setUp(
320 @NonNull Context context,
321 CallList callList,
322 ExternalCallList externalCallList,
323 StatusBarNotifier statusBarNotifier,
324 ExternalCallNotifier externalCallNotifier,
325 ContactInfoCache contactInfoCache,
Eric Erfanian83b20212017-05-31 08:53:10 -0700326 ProximitySensor proximitySensor,
327 FilteredNumberAsyncQueryHandler filteredNumberQueryHandler) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700328 Trace.beginSection("InCallPresenter.setUp");
Eric Erfanianccca3152017-02-22 16:32:36 -0800329 if (mServiceConnected) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700330 LogUtil.i("InCallPresenter.setUp", "New service connection replacing existing one.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800331 if (context != mContext || callList != mCallList) {
332 throw new IllegalStateException();
333 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700334 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800335 return;
336 }
337
338 Objects.requireNonNull(context);
339 mContext = context;
340
341 mContactInfoCache = contactInfoCache;
342
343 mStatusBarNotifier = statusBarNotifier;
344 mExternalCallNotifier = externalCallNotifier;
345 addListener(mStatusBarNotifier);
Eric Erfaniand8046e52017-04-06 09:41:50 -0700346 EnrichedCallComponent.get(mContext)
347 .getEnrichedCallManager()
348 .registerStateChangedListener(mStatusBarNotifier);
Eric Erfanianccca3152017-02-22 16:32:36 -0800349
350 mProximitySensor = proximitySensor;
351 addListener(mProximitySensor);
352
wangqi8d662ca2017-10-26 11:27:19 -0700353 if (mThemeColorManager == null) {
354 mThemeColorManager =
355 new ThemeColorManager(new InCallUIMaterialColorMapUtils(mContext.getResources()));
356 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800357
358 mCallList = callList;
359 mExternalCallList = externalCallList;
360 externalCallList.addExternalCallListener(mExternalCallNotifier);
361 externalCallList.addExternalCallListener(mExternalCallListener);
362
363 // This only gets called by the service so this is okay.
364 mServiceConnected = true;
365
366 // The final thing we do in this set up is add ourselves as a listener to CallList. This
367 // will kick off an update and the whole process can start.
368 mCallList.addListener(this);
369
370 // Create spam call list listener and add it to the list of listeners
zachh6a4cebd2017-10-24 17:10:06 -0700371 mSpamCallListListener =
372 new SpamCallListListener(
373 context, DialerExecutorComponent.get(context).dialerExecutorFactory());
Eric Erfanianccca3152017-02-22 16:32:36 -0800374 mCallList.addListener(mSpamCallListListener);
375
376 VideoPauseController.getInstance().setUp(this);
Eric Erfanianccca3152017-02-22 16:32:36 -0800377
Eric Erfanian83b20212017-05-31 08:53:10 -0700378 mFilteredQueryHandler = filteredNumberQueryHandler;
Eric Erfanianccca3152017-02-22 16:32:36 -0800379 mContext
380 .getSystemService(TelephonyManager.class)
381 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
382
yueg77cb8e52017-10-27 16:42:51 -0700383 AudioModeProvider.getInstance().addListener(this);
384
Eric Erfanian2ca43182017-08-31 06:57:16 -0700385 LogUtil.d("InCallPresenter.setUp", "Finished InCallPresenter.setUp");
386 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800387 }
388
389 /**
390 * Called when the telephony service has disconnected from us. This will happen when there are no
391 * more active calls. However, we may still want to continue showing the UI for certain cases like
392 * showing "Call Ended". What we really want is to wait for the activity and the service to both
393 * disconnect before we tear things down. This method sets a serviceConnected boolean and calls a
394 * secondary method that performs the aforementioned logic.
395 */
396 public void tearDown() {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700397 LogUtil.d("InCallPresenter.tearDown", "tearDown");
Eric Erfanianccca3152017-02-22 16:32:36 -0800398 mCallList.clearOnDisconnect();
399
400 mServiceConnected = false;
401
402 mContext
403 .getSystemService(TelephonyManager.class)
404 .listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
405
406 attemptCleanup();
407 VideoPauseController.getInstance().tearDown();
yueg77cb8e52017-10-27 16:42:51 -0700408 AudioModeProvider.getInstance().removeListener(this);
Eric Erfanianccca3152017-02-22 16:32:36 -0800409 }
410
411 private void attemptFinishActivity() {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700412 mScreenTimeoutEnabled = true;
Eric Erfanianccca3152017-02-22 16:32:36 -0800413 final boolean doFinish = (mInCallActivity != null && isActivityStarted());
Eric Erfanian2ca43182017-08-31 06:57:16 -0700414 LogUtil.i("InCallPresenter.attemptFinishActivity", "Hide in call UI: " + doFinish);
Eric Erfanianccca3152017-02-22 16:32:36 -0800415 if (doFinish) {
416 mInCallActivity.setExcludeFromRecents(true);
417 mInCallActivity.finish();
Eric Erfanianccca3152017-02-22 16:32:36 -0800418 }
419 }
420
421 /**
422 * Called when the UI ends. Attempts to tear down everything if necessary. See {@link #tearDown()}
423 * for more insight on the tear-down process.
424 */
425 public void unsetActivity(InCallActivity inCallActivity) {
426 if (inCallActivity == null) {
427 throw new IllegalArgumentException("unregisterActivity cannot be called with null");
428 }
429 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700430 LogUtil.i(
431 "InCallPresenter.unsetActivity", "No InCallActivity currently set, no need to unset.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800432 return;
433 }
434 if (mInCallActivity != inCallActivity) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700435 LogUtil.w(
436 "InCallPresenter.unsetActivity",
Eric Erfanianccca3152017-02-22 16:32:36 -0800437 "Second instance of InCallActivity is trying to unregister when another"
438 + " instance is active. Ignoring.");
439 return;
440 }
441 updateActivity(null);
442 }
443
444 /**
445 * Updates the current instance of {@link InCallActivity} with the provided one. If a {@code null}
446 * activity is provided, it means that the activity was finished and we should attempt to cleanup.
447 */
448 private void updateActivity(InCallActivity inCallActivity) {
wangqi9982f0d2017-10-11 17:46:07 -0700449 Trace.beginSection("InCallPresenter.updateActivity");
Eric Erfanianccca3152017-02-22 16:32:36 -0800450 boolean updateListeners = false;
451 boolean doAttemptCleanup = false;
452
453 if (inCallActivity != null) {
454 if (mInCallActivity == null) {
Eric Erfanian938468d2017-10-24 14:05:52 -0700455 mContext = inCallActivity.getApplicationContext();
Eric Erfanianccca3152017-02-22 16:32:36 -0800456 updateListeners = true;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700457 LogUtil.i("InCallPresenter.updateActivity", "UI Initialized");
Eric Erfanianccca3152017-02-22 16:32:36 -0800458 } else {
459 // since setActivity is called onStart(), it can be called multiple times.
460 // This is fine and ignorable, but we do not want to update the world every time
461 // this happens (like going to/from background) so we do not set updateListeners.
462 }
463
464 mInCallActivity = inCallActivity;
465 mInCallActivity.setExcludeFromRecents(false);
466
467 // By the time the UI finally comes up, the call may already be disconnected.
468 // If that's the case, we may need to show an error dialog.
469 if (mCallList != null && mCallList.getDisconnectedCall() != null) {
linyuh7b86f562017-11-16 11:24:09 -0800470 showDialogOrToastForDisconnectedCall(mCallList.getDisconnectedCall());
Eric Erfanianccca3152017-02-22 16:32:36 -0800471 }
472
473 // When the UI comes up, we need to first check the in-call state.
474 // If we are showing NO_CALLS, that means that a call probably connected and
475 // then immediately disconnected before the UI was able to come up.
476 // If we dont have any calls, start tearing down the UI instead.
477 // NOTE: This code relies on {@link #mInCallActivity} being set so we run it after
478 // it has been set.
479 if (mInCallState == InCallState.NO_CALLS) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700480 LogUtil.i("InCallPresenter.updateActivity", "UI Initialized, but no calls left. Shut down");
Eric Erfanianccca3152017-02-22 16:32:36 -0800481 attemptFinishActivity();
wangqi9982f0d2017-10-11 17:46:07 -0700482 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800483 return;
484 }
485 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700486 LogUtil.i("InCallPresenter.updateActivity", "UI Destroyed");
Eric Erfanianccca3152017-02-22 16:32:36 -0800487 updateListeners = true;
488 mInCallActivity = null;
489
490 // We attempt cleanup for the destroy case but only after we recalculate the state
491 // to see if we need to come back up or stay shut down. This is why we do the
492 // cleanup after the call to onCallListChange() instead of directly here.
493 doAttemptCleanup = true;
494 }
495
496 // Messages can come from the telephony layer while the activity is coming up
497 // and while the activity is going down. So in both cases we need to recalculate what
498 // state we should be in after they complete.
499 // Examples: (1) A new incoming call could come in and then get disconnected before
500 // the activity is created.
501 // (2) All calls could disconnect and then get a new incoming call before the
502 // activity is destroyed.
503 //
Eric Erfanian938468d2017-10-24 14:05:52 -0700504 // a bug - We previously had a check for mServiceConnected here as well, but there are
Eric Erfanianccca3152017-02-22 16:32:36 -0800505 // cases where we need to recalculate the current state even if the service in not
506 // connected. In particular the case where startOrFinish() is called while the app is
507 // already finish()ing. In that case, we skip updating the state with the knowledge that
508 // we will check again once the activity has finished. That means we have to recalculate the
509 // state here even if the service is disconnected since we may not have finished a state
510 // transition while finish()ing.
511 if (updateListeners) {
512 onCallListChange(mCallList);
513 }
514
515 if (doAttemptCleanup) {
516 attemptCleanup();
517 }
wangqi9982f0d2017-10-11 17:46:07 -0700518 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800519 }
520
521 public void setManageConferenceActivity(
522 @Nullable ManageConferenceActivity manageConferenceActivity) {
523 mManageConferenceActivity = manageConferenceActivity;
524 }
525
526 public void onBringToForeground(boolean showDialpad) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700527 LogUtil.i("InCallPresenter.onBringToForeground", "Bringing UI to foreground.");
Eric Erfanianccca3152017-02-22 16:32:36 -0800528 bringToForeground(showDialpad);
529 }
530
531 public void onCallAdded(final android.telecom.Call call) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700532 Trace.beginSection("InCallPresenter.onCallAdded");
Eric Erfanianccca3152017-02-22 16:32:36 -0800533 LatencyReport latencyReport = new LatencyReport(call);
534 if (shouldAttemptBlocking(call)) {
535 maybeBlockCall(call, latencyReport);
536 } else {
537 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
538 mExternalCallList.onCallAdded(call);
539 } else {
540 latencyReport.onCallBlockingDone();
541 mCallList.onCallAdded(mContext, call, latencyReport);
542 }
543 }
544
545 // Since a call has been added we are no longer waiting for Telecom to send us a call.
546 setBoundAndWaitingForOutgoingCall(false, null);
547 call.registerCallback(mCallCallback);
zachh78e54ac2017-12-05 16:38:35 -0800548 // TODO(maxwelb): Return the future in recordPhoneLookupInfo and propagate.
549 PhoneLookupHistoryRecorder.recordPhoneLookupInfo(mContext.getApplicationContext(), call);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700550 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800551 }
552
553 private boolean shouldAttemptBlocking(android.telecom.Call call) {
554 if (call.getState() != android.telecom.Call.STATE_RINGING) {
555 return false;
556 }
Eric Erfanian83b20212017-05-31 08:53:10 -0700557 if (!UserManagerCompat.isUserUnlocked(mContext)) {
558 LogUtil.i(
559 "InCallPresenter.shouldAttemptBlocking",
560 "not attempting to block incoming call because user is locked");
561 return false;
562 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800563 if (TelecomCallUtil.isEmergencyCall(call)) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700564 LogUtil.i(
565 "InCallPresenter.shouldAttemptBlocking",
566 "Not attempting to block incoming emergency call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800567 return false;
568 }
569 if (FilteredNumbersUtil.hasRecentEmergencyCall(mContext)) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700570 LogUtil.i(
571 "InCallPresenter.shouldAttemptBlocking",
572 "Not attempting to block incoming call due to recent emergency call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800573 return false;
574 }
575 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
576 return false;
577 }
Eric Erfanian83b20212017-05-31 08:53:10 -0700578 if (FilteredNumberCompat.useNewFiltering(mContext)) {
579 LogUtil.i(
580 "InCallPresenter.shouldAttemptBlocking",
581 "not attempting to block incoming call because framework blocking is in use");
582 return false;
583 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800584 return true;
585 }
586
587 /**
588 * Checks whether a call should be blocked, and blocks it if so. Otherwise, it adds the call to
589 * the CallList so it can proceed as normal. There is a timeout, so if the function for checking
590 * whether a function is blocked does not return in a reasonable time, we proceed with adding the
591 * call anyways.
592 */
593 private void maybeBlockCall(final android.telecom.Call call, final LatencyReport latencyReport) {
594 final String countryIso = GeoUtil.getCurrentCountryIso(mContext);
595 final String number = TelecomCallUtil.getNumber(call);
596 final long timeAdded = System.currentTimeMillis();
597
598 // Though AtomicBoolean's can be scary, don't fear, as in this case it is only used on the
599 // main UI thread. It is needed so we can change its value within different scopes, since
600 // that cannot be done with a final boolean.
601 final AtomicBoolean hasTimedOut = new AtomicBoolean(false);
602
603 final Handler handler = new Handler();
604
605 // Proceed if the query is slow; the call may still be blocked after the query returns.
606 final Runnable runnable =
607 new Runnable() {
608 @Override
609 public void run() {
610 hasTimedOut.set(true);
611 latencyReport.onCallBlockingDone();
612 mCallList.onCallAdded(mContext, call, latencyReport);
613 }
614 };
615 handler.postDelayed(runnable, BLOCK_QUERY_TIMEOUT_MS);
616
617 OnCheckBlockedListener onCheckBlockedListener =
618 new OnCheckBlockedListener() {
619 @Override
620 public void onCheckComplete(final Integer id) {
621 if (isReadyForTearDown()) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700622 LogUtil.i("InCallPresenter.onCheckComplete", "torn down, not adding call");
Eric Erfanianccca3152017-02-22 16:32:36 -0800623 return;
624 }
625 if (!hasTimedOut.get()) {
626 handler.removeCallbacks(runnable);
627 }
628 if (id == null) {
629 if (!hasTimedOut.get()) {
630 latencyReport.onCallBlockingDone();
631 mCallList.onCallAdded(mContext, call, latencyReport);
632 }
633 } else if (id == FilteredNumberAsyncQueryHandler.INVALID_ID) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700634 LogUtil.d(
635 "InCallPresenter.onCheckComplete", "invalid number, skipping block checking");
Eric Erfanianccca3152017-02-22 16:32:36 -0800636 if (!hasTimedOut.get()) {
637 handler.removeCallbacks(runnable);
638
639 latencyReport.onCallBlockingDone();
640 mCallList.onCallAdded(mContext, call, latencyReport);
641 }
642 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700643 LogUtil.i(
644 "InCallPresenter.onCheckComplete", "Rejecting incoming call from blocked number");
Eric Erfanianccca3152017-02-22 16:32:36 -0800645 call.reject(false, null);
646 Logger.get(mContext).logInteraction(InteractionEvent.Type.CALL_BLOCKED);
647
648 /*
649 * If mContext is null, then the InCallPresenter was torn down before the
650 * block check had a chance to complete. The context is no longer valid, so
651 * don't attempt to remove the call log entry.
652 */
653 if (mContext == null) {
654 return;
655 }
656 // Register observer to update the call log.
657 // BlockedNumberContentObserver will unregister after successful log or timeout.
658 BlockedNumberContentObserver contentObserver =
659 new BlockedNumberContentObserver(mContext, new Handler(), number, timeAdded);
660 contentObserver.register();
661 }
662 }
663 };
664
665 mFilteredQueryHandler.isBlockedNumber(onCheckBlockedListener, number, countryIso);
666 }
667
668 public void onCallRemoved(android.telecom.Call call) {
669 if (call.getDetails().hasProperty(CallCompat.Details.PROPERTY_IS_EXTERNAL_CALL)) {
670 mExternalCallList.onCallRemoved(call);
671 } else {
672 mCallList.onCallRemoved(mContext, call);
673 call.unregisterCallback(mCallCallback);
674 }
675 }
676
677 public void onCanAddCallChanged(boolean canAddCall) {
678 for (CanAddCallListener listener : mCanAddCallListeners) {
679 listener.onCanAddCallChanged(canAddCall);
680 }
681 }
682
683 @Override
684 public void onWiFiToLteHandover(DialerCall call) {
685 if (mInCallActivity != null) {
linyuh7b86f562017-11-16 11:24:09 -0800686 mInCallActivity.showToastForWiFiToLteHandover(call);
Eric Erfanianccca3152017-02-22 16:32:36 -0800687 }
688 }
689
690 @Override
691 public void onHandoverToWifiFailed(DialerCall call) {
692 if (mInCallActivity != null) {
linyuh7b86f562017-11-16 11:24:09 -0800693 mInCallActivity.showDialogOrToastForWifiHandoverFailure(call);
Eric Erfanianccca3152017-02-22 16:32:36 -0800694 }
695 }
696
Eric Erfanianc857f902017-05-15 14:05:33 -0700697 @Override
698 public void onInternationalCallOnWifi(@NonNull DialerCall call) {
699 LogUtil.enterBlock("InCallPresenter.onInternationalCallOnWifi");
700 if (mInCallActivity != null) {
linyuh7b86f562017-11-16 11:24:09 -0800701 mInCallActivity.showDialogForInternationalCallOnWifi(call);
Eric Erfanianc857f902017-05-15 14:05:33 -0700702 }
703 }
704
Eric Erfanianccca3152017-02-22 16:32:36 -0800705 /**
706 * Called when there is a change to the call list. Sets the In-Call state for the entire in-call
707 * app based on the information it gets from CallList. Dispatches the in-call state to all
708 * listeners. Can trigger the creation or destruction of the UI based on the states that is
709 * calculates.
710 */
711 @Override
712 public void onCallListChange(CallList callList) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700713 Trace.beginSection("InCallPresenter.onCallListChange");
Eric Erfanianccca3152017-02-22 16:32:36 -0800714 if (mInCallActivity != null && mInCallActivity.isInCallScreenAnimating()) {
715 mAwaitingCallListUpdate = true;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700716 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800717 return;
718 }
719 if (callList == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700720 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800721 return;
722 }
723
724 mAwaitingCallListUpdate = false;
725
726 InCallState newState = getPotentialStateFromCallList(callList);
727 InCallState oldState = mInCallState;
Eric Erfanian2ca43182017-08-31 06:57:16 -0700728 LogUtil.d(
729 "InCallPresenter.onCallListChange",
730 "onCallListChange oldState= " + oldState + " newState=" + newState);
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700731
732 // If the user placed a call and was asked to choose the account, but then pressed "Home", the
733 // incall activity for that call will still exist (even if it's not visible). In the case of
734 // an incoming call in that situation, just disconnect that "waiting for account" call and
735 // dismiss the dialog. The same activity will be reused to handle the new incoming call. See
Eric Erfanian938468d2017-10-24 14:05:52 -0700736 // a bug for more details.
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700737 DialerCall waitingForAccountCall;
738 if (newState == InCallState.INCOMING
739 && (waitingForAccountCall = callList.getWaitingForAccountCall()) != null) {
740 waitingForAccountCall.disconnect();
Eric Erfanian2ca43182017-08-31 06:57:16 -0700741 // The InCallActivity might be destroyed or not started yet at this point.
742 if (isActivityStarted()) {
743 mInCallActivity.dismissPendingDialogs();
744 }
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700745 }
746
Eric Erfanianccca3152017-02-22 16:32:36 -0800747 newState = startOrFinishUi(newState);
Eric Erfanian2ca43182017-08-31 06:57:16 -0700748 LogUtil.d(
749 "InCallPresenter.onCallListChange", "onCallListChange newState changed to " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800750
751 // Set the new state before announcing it to the world
Eric Erfanian2ca43182017-08-31 06:57:16 -0700752 LogUtil.i(
753 "InCallPresenter.onCallListChange",
754 "Phone switching state: " + oldState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800755 mInCallState = newState;
756
757 // notify listeners of new state
758 for (InCallStateListener listener : mListeners) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700759 LogUtil.d(
760 "InCallPresenter.onCallListChange",
761 "Notify " + listener + " of state " + mInCallState.toString());
Eric Erfanianccca3152017-02-22 16:32:36 -0800762 listener.onStateChange(oldState, mInCallState, callList);
763 }
764
765 if (isActivityStarted()) {
766 final boolean hasCall =
767 callList.getActiveOrBackgroundCall() != null || callList.getOutgoingCall() != null;
768 mInCallActivity.dismissKeyguard(hasCall);
769 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700770 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800771 }
772
773 /** Called when there is a new incoming call. */
774 @Override
775 public void onIncomingCall(DialerCall call) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700776 Trace.beginSection("InCallPresenter.onIncomingCall");
Eric Erfanianccca3152017-02-22 16:32:36 -0800777 InCallState newState = startOrFinishUi(InCallState.INCOMING);
778 InCallState oldState = mInCallState;
779
Eric Erfanian2ca43182017-08-31 06:57:16 -0700780 LogUtil.i(
781 "InCallPresenter.onIncomingCall", "Phone switching state: " + oldState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -0800782 mInCallState = newState;
783
wangqicf61ca02017-08-31 15:32:55 -0700784 Trace.beginSection("listener.onIncomingCall");
Eric Erfanianccca3152017-02-22 16:32:36 -0800785 for (IncomingCallListener listener : mIncomingCallListeners) {
786 listener.onIncomingCall(oldState, mInCallState, call);
787 }
wangqicf61ca02017-08-31 15:32:55 -0700788 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800789
wangqicf61ca02017-08-31 15:32:55 -0700790 Trace.beginSection("onPrimaryCallStateChanged");
Eric Erfanianccca3152017-02-22 16:32:36 -0800791 if (mInCallActivity != null) {
792 // Re-evaluate which fragment is being shown.
793 mInCallActivity.onPrimaryCallStateChanged();
794 }
Eric Erfanian2ca43182017-08-31 06:57:16 -0700795 Trace.endSection();
wangqicf61ca02017-08-31 15:32:55 -0700796 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -0800797 }
798
799 @Override
800 public void onUpgradeToVideo(DialerCall call) {
Eric Erfanian90508232017-03-24 09:31:16 -0700801 if (VideoUtils.hasReceivedVideoUpgradeRequest(call.getVideoTech().getSessionModificationState())
Eric Erfanianccca3152017-02-22 16:32:36 -0800802 && mInCallState == InCallPresenter.InCallState.INCOMING) {
803 LogUtil.i(
804 "InCallPresenter.onUpgradeToVideo",
805 "rejecting upgrade request due to existing incoming call");
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700806 call.getVideoTech().declineVideoRequest();
Eric Erfanianccca3152017-02-22 16:32:36 -0800807 }
808
809 if (mInCallActivity != null) {
810 // Re-evaluate which fragment is being shown.
811 mInCallActivity.onPrimaryCallStateChanged();
812 }
813 }
814
815 @Override
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700816 public void onSessionModificationStateChange(DialerCall call) {
817 int newState = call.getVideoTech().getSessionModificationState();
Eric Erfanianccca3152017-02-22 16:32:36 -0800818 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "state: %d", newState);
819 if (mProximitySensor == null) {
820 LogUtil.i("InCallPresenter.onSessionModificationStateChange", "proximitySensor is null");
821 return;
822 }
823 mProximitySensor.setIsAttemptingVideoCall(
Eric Erfaniand5e47f62017-03-15 14:41:07 -0700824 call.hasSentVideoUpgradeRequest() || call.hasReceivedVideoUpgradeRequest());
Eric Erfanianccca3152017-02-22 16:32:36 -0800825 if (mInCallActivity != null) {
826 // Re-evaluate which fragment is being shown.
827 mInCallActivity.onPrimaryCallStateChanged();
828 }
829 }
830
831 /**
832 * Called when a call becomes disconnected. Called everytime an existing call changes from being
833 * connected (incoming/outgoing/active) to disconnected.
834 */
835 @Override
836 public void onDisconnect(DialerCall call) {
linyuh7b86f562017-11-16 11:24:09 -0800837 showDialogOrToastForDisconnectedCall(call);
Eric Erfanianccca3152017-02-22 16:32:36 -0800838
839 // We need to do the run the same code as onCallListChange.
840 onCallListChange(mCallList);
841
842 if (isActivityStarted()) {
843 mInCallActivity.dismissKeyguard(false);
844 }
845
846 if (call.isEmergencyCall()) {
847 FilteredNumbersUtil.recordLastEmergencyCallTime(mContext);
848 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800849
Eric Erfanianfc37b022017-03-21 10:11:17 -0700850 if (!mCallList.hasLiveCall()
851 && !call.getLogState().isIncoming
Eric Erfanian10b34a52017-05-04 08:23:17 -0700852 && !isSecretCode(call.getNumber())
wangqi9982f0d2017-10-11 17:46:07 -0700853 && !call.isVoiceMailNumber()) {
Eric Erfanian10b34a52017-05-04 08:23:17 -0700854 PostCall.onCallDisconnected(mContext, call.getNumber(), call.getConnectTimeMillis());
Eric Erfanianccca3152017-02-22 16:32:36 -0800855 }
Eric Erfanianccca3152017-02-22 16:32:36 -0800856 }
857
Eric Erfanian10b34a52017-05-04 08:23:17 -0700858 private boolean isSecretCode(@Nullable String number) {
859 return number != null
860 && (number.length() <= 8 || number.startsWith("*#*#") || number.endsWith("#*#*"));
861 }
862
Eric Erfanianccca3152017-02-22 16:32:36 -0800863 /** Given the call list, return the state in which the in-call screen should be. */
864 public InCallState getPotentialStateFromCallList(CallList callList) {
865
866 InCallState newState = InCallState.NO_CALLS;
867
868 if (callList == null) {
869 return newState;
870 }
871 if (callList.getIncomingCall() != null) {
872 newState = InCallState.INCOMING;
873 } else if (callList.getWaitingForAccountCall() != null) {
874 newState = InCallState.WAITING_FOR_ACCOUNT;
875 } else if (callList.getPendingOutgoingCall() != null) {
876 newState = InCallState.PENDING_OUTGOING;
877 } else if (callList.getOutgoingCall() != null) {
878 newState = InCallState.OUTGOING;
879 } else if (callList.getActiveCall() != null
880 || callList.getBackgroundCall() != null
881 || callList.getDisconnectedCall() != null
882 || callList.getDisconnectingCall() != null) {
883 newState = InCallState.INCALL;
884 }
885
886 if (newState == InCallState.NO_CALLS) {
887 if (mBoundAndWaitingForOutgoingCall) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700888 return InCallState.PENDING_OUTGOING;
Eric Erfanianccca3152017-02-22 16:32:36 -0800889 }
890 }
891
892 return newState;
893 }
894
895 public boolean isBoundAndWaitingForOutgoingCall() {
896 return mBoundAndWaitingForOutgoingCall;
897 }
898
899 public void setBoundAndWaitingForOutgoingCall(boolean isBound, PhoneAccountHandle handle) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700900 LogUtil.i(
901 "InCallPresenter.setBoundAndWaitingForOutgoingCall",
902 "setBoundAndWaitingForOutgoingCall: " + isBound);
Eric Erfanianccca3152017-02-22 16:32:36 -0800903 mBoundAndWaitingForOutgoingCall = isBound;
904 mThemeColorManager.setPendingPhoneAccountHandle(handle);
905 if (isBound && mInCallState == InCallState.NO_CALLS) {
Eric Erfanian2ca43182017-08-31 06:57:16 -0700906 mInCallState = InCallState.PENDING_OUTGOING;
Eric Erfanianccca3152017-02-22 16:32:36 -0800907 }
908 }
909
910 public void onShrinkAnimationComplete() {
911 if (mAwaitingCallListUpdate) {
912 onCallListChange(mCallList);
913 }
914 }
915
916 public void addIncomingCallListener(IncomingCallListener listener) {
917 Objects.requireNonNull(listener);
918 mIncomingCallListeners.add(listener);
919 }
920
921 public void removeIncomingCallListener(IncomingCallListener listener) {
922 if (listener != null) {
923 mIncomingCallListeners.remove(listener);
924 }
925 }
926
927 public void addListener(InCallStateListener listener) {
928 Objects.requireNonNull(listener);
929 mListeners.add(listener);
930 }
931
932 public void removeListener(InCallStateListener listener) {
933 if (listener != null) {
934 mListeners.remove(listener);
935 }
936 }
937
938 public void addDetailsListener(InCallDetailsListener listener) {
939 Objects.requireNonNull(listener);
940 mDetailsListeners.add(listener);
941 }
942
943 public void removeDetailsListener(InCallDetailsListener listener) {
944 if (listener != null) {
945 mDetailsListeners.remove(listener);
946 }
947 }
948
949 public void addCanAddCallListener(CanAddCallListener listener) {
950 Objects.requireNonNull(listener);
951 mCanAddCallListeners.add(listener);
952 }
953
954 public void removeCanAddCallListener(CanAddCallListener listener) {
955 if (listener != null) {
956 mCanAddCallListeners.remove(listener);
957 }
958 }
959
960 public void addOrientationListener(InCallOrientationListener listener) {
961 Objects.requireNonNull(listener);
962 mOrientationListeners.add(listener);
963 }
964
965 public void removeOrientationListener(InCallOrientationListener listener) {
966 if (listener != null) {
967 mOrientationListeners.remove(listener);
968 }
969 }
970
971 public void addInCallEventListener(InCallEventListener listener) {
972 Objects.requireNonNull(listener);
973 mInCallEventListeners.add(listener);
974 }
975
976 public void removeInCallEventListener(InCallEventListener listener) {
977 if (listener != null) {
978 mInCallEventListeners.remove(listener);
979 }
980 }
981
982 public ProximitySensor getProximitySensor() {
983 return mProximitySensor;
984 }
985
986 public PseudoScreenState getPseudoScreenState() {
987 return mPseudoScreenState;
988 }
989
990 /** Returns true if the incall app is the foreground application. */
991 public boolean isShowingInCallUi() {
992 if (!isActivityStarted()) {
993 return false;
994 }
995 if (mManageConferenceActivity != null && mManageConferenceActivity.isVisible()) {
996 return true;
997 }
998 return mInCallActivity.isVisible();
999 }
1000
1001 /**
1002 * Returns true if the activity has been created and is running. Returns true as long as activity
1003 * is not destroyed or finishing. This ensures that we return true even if the activity is paused
1004 * (not in foreground).
1005 */
1006 public boolean isActivityStarted() {
1007 return (mInCallActivity != null
1008 && !mInCallActivity.isDestroyed()
1009 && !mInCallActivity.isFinishing());
1010 }
1011
1012 /**
1013 * Determines if the In-Call app is currently changing configuration.
1014 *
1015 * @return {@code true} if the In-Call app is changing configuration.
1016 */
1017 public boolean isChangingConfigurations() {
1018 return mIsChangingConfigurations;
1019 }
1020
1021 /**
1022 * Tracks whether the In-Call app is currently in the process of changing configuration (i.e.
1023 * screen orientation).
1024 */
1025 /*package*/
1026 void updateIsChangingConfigurations() {
1027 mIsChangingConfigurations = false;
1028 if (mInCallActivity != null) {
1029 mIsChangingConfigurations = mInCallActivity.isChangingConfigurations();
1030 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001031 LogUtil.v(
1032 "InCallPresenter.updateIsChangingConfigurations",
1033 "updateIsChangingConfigurations = " + mIsChangingConfigurations);
Eric Erfanianccca3152017-02-22 16:32:36 -08001034 }
1035
1036 /** Called when the activity goes in/out of the foreground. */
1037 public void onUiShowing(boolean showing) {
1038 // We need to update the notification bar when we leave the UI because that
1039 // could trigger it to show again.
1040 if (mStatusBarNotifier != null) {
wangqic8cf79e2017-10-17 09:21:00 -07001041 mStatusBarNotifier.updateNotification();
Eric Erfanianccca3152017-02-22 16:32:36 -08001042 }
1043
1044 if (mProximitySensor != null) {
1045 mProximitySensor.onInCallShowing(showing);
1046 }
1047
yueg092b21c2017-11-15 16:20:07 -08001048 if (!showing) {
Eric Erfanianccca3152017-02-22 16:32:36 -08001049 updateIsChangingConfigurations();
1050 }
1051
1052 for (InCallUiListener listener : mInCallUiListeners) {
1053 listener.onUiShowing(showing);
1054 }
1055
1056 if (mInCallActivity != null) {
1057 // Re-evaluate which fragment is being shown.
1058 mInCallActivity.onPrimaryCallStateChanged();
1059 }
1060 }
1061
Eric Erfanian2ca43182017-08-31 06:57:16 -07001062 public void refreshUi() {
1063 if (mInCallActivity != null) {
1064 // Re-evaluate which fragment is being shown.
1065 mInCallActivity.onPrimaryCallStateChanged();
1066 }
1067 }
1068
Eric Erfanianccca3152017-02-22 16:32:36 -08001069 public void addInCallUiListener(InCallUiListener listener) {
1070 mInCallUiListeners.add(listener);
1071 }
1072
1073 public boolean removeInCallUiListener(InCallUiListener listener) {
1074 return mInCallUiListeners.remove(listener);
1075 }
1076
1077 /*package*/
1078 void onActivityStarted() {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001079 LogUtil.d("InCallPresenter.onActivityStarted", "onActivityStarted");
Eric Erfanianccca3152017-02-22 16:32:36 -08001080 notifyVideoPauseController(true);
Eric Erfanian2ca43182017-08-31 06:57:16 -07001081 applyScreenTimeout();
Eric Erfanianccca3152017-02-22 16:32:36 -08001082 }
1083
1084 /*package*/
1085 void onActivityStopped() {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001086 LogUtil.d("InCallPresenter.onActivityStopped", "onActivityStopped");
Eric Erfanianccca3152017-02-22 16:32:36 -08001087 notifyVideoPauseController(false);
1088 }
1089
1090 private void notifyVideoPauseController(boolean showing) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001091 LogUtil.d(
1092 "InCallPresenter.notifyVideoPauseController",
1093 "mIsChangingConfigurations=" + mIsChangingConfigurations);
Eric Erfanianccca3152017-02-22 16:32:36 -08001094 if (!mIsChangingConfigurations) {
1095 VideoPauseController.getInstance().onUiShowing(showing);
1096 }
1097 }
1098
1099 /** Brings the app into the foreground if possible. */
1100 public void bringToForeground(boolean showDialpad) {
1101 // Before we bring the incall UI to the foreground, we check to see if:
1102 // 1. It is not currently in the foreground
1103 // 2. We are in a state where we want to show the incall ui (i.e. there are calls to
1104 // be displayed)
1105 // If the activity hadn't actually been started previously, yet there are still calls
1106 // present (e.g. a call was accepted by a bluetooth or wired headset), we want to
1107 // bring it up the UI regardless.
1108 if (!isShowingInCallUi() && mInCallState != InCallState.NO_CALLS) {
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001109 showInCall(showDialpad, false /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001110 }
1111 }
1112
1113 public void onPostDialCharWait(String callId, String chars) {
1114 if (isActivityStarted()) {
linyuhc3968e62017-11-20 17:40:50 -08001115 mInCallActivity.showDialogForPostCharWait(callId, chars);
Eric Erfanianccca3152017-02-22 16:32:36 -08001116 }
1117 }
1118
1119 /**
1120 * Handles the green CALL key while in-call.
1121 *
1122 * @return true if we consumed the event.
1123 */
1124 public boolean handleCallKey() {
1125 LogUtil.v("InCallPresenter.handleCallKey", null);
1126
1127 // The green CALL button means either "Answer", "Unhold", or
1128 // "Swap calls", or can be a no-op, depending on the current state
1129 // of the Phone.
1130
1131 /** INCOMING CALL */
1132 final CallList calls = mCallList;
1133 final DialerCall incomingCall = calls.getIncomingCall();
1134 LogUtil.v("InCallPresenter.handleCallKey", "incomingCall: " + incomingCall);
1135
1136 // (1) Attempt to answer a call
1137 if (incomingCall != null) {
1138 incomingCall.answer(VideoProfile.STATE_AUDIO_ONLY);
1139 return true;
1140 }
1141
1142 /** STATE_ACTIVE CALL */
1143 final DialerCall activeCall = calls.getActiveCall();
1144 if (activeCall != null) {
1145 // TODO: This logic is repeated from CallButtonPresenter.java. We should
1146 // consolidate this logic.
1147 final boolean canMerge =
1148 activeCall.can(android.telecom.Call.Details.CAPABILITY_MERGE_CONFERENCE);
1149 final boolean canSwap =
1150 activeCall.can(android.telecom.Call.Details.CAPABILITY_SWAP_CONFERENCE);
1151
Eric Erfanian2ca43182017-08-31 06:57:16 -07001152 LogUtil.v(
1153 "InCallPresenter.handleCallKey",
1154 "activeCall: " + activeCall + ", canMerge: " + canMerge + ", canSwap: " + canSwap);
Eric Erfanianccca3152017-02-22 16:32:36 -08001155
1156 // (2) Attempt actions on conference calls
1157 if (canMerge) {
1158 TelecomAdapter.getInstance().merge(activeCall.getId());
1159 return true;
1160 } else if (canSwap) {
1161 TelecomAdapter.getInstance().swap(activeCall.getId());
1162 return true;
1163 }
1164 }
1165
1166 /** BACKGROUND CALL */
1167 final DialerCall heldCall = calls.getBackgroundCall();
1168 if (heldCall != null) {
1169 // We have a hold call so presumeable it will always support HOLD...but
1170 // there is no harm in double checking.
1171 final boolean canHold = heldCall.can(android.telecom.Call.Details.CAPABILITY_HOLD);
1172
Eric Erfanian2ca43182017-08-31 06:57:16 -07001173 LogUtil.v("InCallPresenter.handleCallKey", "heldCall: " + heldCall + ", canHold: " + canHold);
Eric Erfanianccca3152017-02-22 16:32:36 -08001174
1175 // (4) unhold call
1176 if (heldCall.getState() == DialerCall.State.ONHOLD && canHold) {
1177 heldCall.unhold();
1178 return true;
1179 }
1180 }
1181
1182 // Always consume hard keys
1183 return true;
1184 }
1185
Eric Erfanianccca3152017-02-22 16:32:36 -08001186 /** Clears the previous fullscreen state. */
1187 public void clearFullscreen() {
1188 mIsFullScreen = false;
1189 }
1190
1191 /**
1192 * Changes the fullscreen mode of the in-call UI.
1193 *
1194 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1195 * otherwise.
1196 */
1197 public void setFullScreen(boolean isFullScreen) {
1198 setFullScreen(isFullScreen, false /* force */);
1199 }
1200
1201 /**
1202 * Changes the fullscreen mode of the in-call UI.
1203 *
1204 * @param isFullScreen {@code true} if in-call should be in fullscreen mode, {@code false}
1205 * otherwise.
1206 * @param force {@code true} if fullscreen mode should be set regardless of its current state.
1207 */
1208 public void setFullScreen(boolean isFullScreen, boolean force) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001209 LogUtil.i("InCallPresenter.setFullScreen", "setFullScreen = " + isFullScreen);
Eric Erfanianccca3152017-02-22 16:32:36 -08001210
1211 // As a safeguard, ensure we cannot enter fullscreen if the dialpad is shown.
1212 if (isDialpadVisible()) {
1213 isFullScreen = false;
Eric Erfanian2ca43182017-08-31 06:57:16 -07001214 LogUtil.v(
1215 "InCallPresenter.setFullScreen",
1216 "setFullScreen overridden as dialpad is shown = " + isFullScreen);
Eric Erfanianccca3152017-02-22 16:32:36 -08001217 }
1218
1219 if (mIsFullScreen == isFullScreen && !force) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001220 LogUtil.v("InCallPresenter.setFullScreen", "setFullScreen ignored as already in that state.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001221 return;
1222 }
1223 mIsFullScreen = isFullScreen;
1224 notifyFullscreenModeChange(mIsFullScreen);
1225 }
1226
1227 /**
1228 * @return {@code true} if the in-call ui is currently in fullscreen mode, {@code false}
1229 * otherwise.
1230 */
1231 public boolean isFullscreen() {
1232 return mIsFullScreen;
1233 }
1234
1235 /**
1236 * Called by the {@link VideoCallPresenter} to inform of a change in full screen video status.
1237 *
1238 * @param isFullscreenMode {@code True} if entering full screen mode.
1239 */
1240 public void notifyFullscreenModeChange(boolean isFullscreenMode) {
1241 for (InCallEventListener listener : mInCallEventListeners) {
1242 listener.onFullscreenModeChanged(isFullscreenMode);
1243 }
1244 }
1245
linyuh7b86f562017-11-16 11:24:09 -08001246 /** Instruct the in-call activity to show an error dialog or toast for a disconnected call. */
1247 private void showDialogOrToastForDisconnectedCall(DialerCall call) {
1248 if (!isActivityStarted() || call.getState() != DialerCall.State.DISCONNECTED) {
1249 return;
Eric Erfanianccca3152017-02-22 16:32:36 -08001250 }
linyuh7b86f562017-11-16 11:24:09 -08001251
1252 // For newly disconnected calls, we may want to show a dialog on specific error conditions
1253 if (call.getAccountHandle() == null && !call.isConferenceCall()) {
1254 setDisconnectCauseForMissingAccounts(call);
1255 }
1256
1257 mInCallActivity.showDialogOrToastForDisconnectedCall(
1258 new DisconnectMessage(mInCallActivity, call));
Eric Erfanianccca3152017-02-22 16:32:36 -08001259 }
1260
1261 /**
1262 * When the state of in-call changes, this is the first method to get called. It determines if the
1263 * UI needs to be started or finished depending on the new state and does it.
1264 */
1265 private InCallState startOrFinishUi(InCallState newState) {
wangqicf61ca02017-08-31 15:32:55 -07001266 Trace.beginSection("InCallPresenter.startOrFinishUi");
Eric Erfanian2ca43182017-08-31 06:57:16 -07001267 LogUtil.d(
1268 "InCallPresenter.startOrFinishUi", "startOrFinishUi: " + mInCallState + " -> " + newState);
Eric Erfanianccca3152017-02-22 16:32:36 -08001269
1270 // TODO: Consider a proper state machine implementation
1271
1272 // If the state isn't changing we have already done any starting/stopping of activities in
1273 // a previous pass...so lets cut out early
1274 if (newState == mInCallState) {
wangqicf61ca02017-08-31 15:32:55 -07001275 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001276 return newState;
1277 }
1278
1279 // A new Incoming call means that the user needs to be notified of the the call (since
1280 // it wasn't them who initiated it). We do this through full screen notifications and
1281 // happens indirectly through {@link StatusBarNotifier}.
1282 //
1283 // The process for incoming calls is as follows:
1284 //
1285 // 1) CallList - Announces existence of new INCOMING call
1286 // 2) InCallPresenter - Gets announcement and calculates that the new InCallState
1287 // - should be set to INCOMING.
1288 // 3) InCallPresenter - This method is called to see if we need to start or finish
1289 // the app given the new state.
1290 // 4) StatusBarNotifier - Listens to InCallState changes. InCallPresenter calls
1291 // StatusBarNotifier explicitly to issue a FullScreen Notification
1292 // that will either start the InCallActivity or show the user a
1293 // top-level notification dialog if the user is in an immersive app.
1294 // That notification can also start the InCallActivity.
1295 // 5) InCallActivity - Main activity starts up and at the end of its onCreate will
1296 // call InCallPresenter::setActivity() to let the presenter
1297 // know that start-up is complete.
1298 //
1299 // [ AND NOW YOU'RE IN THE CALL. voila! ]
1300 //
1301 // Our app is started using a fullScreen notification. We need to do this whenever
1302 // we get an incoming call. Depending on the current context of the device, either a
1303 // incoming call HUN or the actual InCallActivity will be shown.
1304 final boolean startIncomingCallSequence = (InCallState.INCOMING == newState);
1305
1306 // A dialog to show on top of the InCallUI to select a PhoneAccount
1307 final boolean showAccountPicker = (InCallState.WAITING_FOR_ACCOUNT == newState);
1308
1309 // A new outgoing call indicates that the user just now dialed a number and when that
1310 // happens we need to display the screen immediately or show an account picker dialog if
1311 // no default is set. However, if the main InCallUI is already visible, we do not want to
1312 // re-initiate the start-up animation, so we do not need to do anything here.
1313 //
1314 // It is also possible to go into an intermediate state where the call has been initiated
1315 // but Telecom has not yet returned with the details of the call (handle, gateway, etc.).
1316 // This pending outgoing state can also launch the call screen.
1317 //
1318 // This is different from the incoming call sequence because we do not need to shock the
1319 // user with a top-level notification. Just show the call UI normally.
1320 boolean callCardFragmentVisible =
1321 mInCallActivity != null && mInCallActivity.getCallCardFragmentVisible();
1322 final boolean mainUiNotVisible = !isShowingInCallUi() || !callCardFragmentVisible;
1323 boolean showCallUi = InCallState.OUTGOING == newState && mainUiNotVisible;
1324
1325 // Direct transition from PENDING_OUTGOING -> INCALL means that there was an error in the
1326 // outgoing call process, so the UI should be brought up to show an error dialog.
1327 showCallUi |=
1328 (InCallState.PENDING_OUTGOING == mInCallState
1329 && InCallState.INCALL == newState
1330 && !isShowingInCallUi());
1331
1332 // Another exception - InCallActivity is in charge of disconnecting a call with no
1333 // valid accounts set. Bring the UI up if this is true for the current pending outgoing
1334 // call so that:
1335 // 1) The call can be disconnected correctly
1336 // 2) The UI comes up and correctly displays the error dialog.
1337 // TODO: Remove these special case conditions by making InCallPresenter a true state
1338 // machine. Telecom should also be the component responsible for disconnecting a call
1339 // with no valid accounts.
1340 showCallUi |=
1341 InCallState.PENDING_OUTGOING == newState
1342 && mainUiNotVisible
1343 && isCallWithNoValidAccounts(mCallList.getPendingOutgoingCall());
1344
1345 // The only time that we have an instance of mInCallActivity and it isn't started is
1346 // when it is being destroyed. In that case, lets avoid bringing up another instance of
1347 // the activity. When it is finally destroyed, we double check if we should bring it back
1348 // up so we aren't going to lose anything by avoiding a second startup here.
1349 boolean activityIsFinishing = mInCallActivity != null && !isActivityStarted();
1350 if (activityIsFinishing) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001351 LogUtil.i(
1352 "InCallPresenter.startOrFinishUi",
1353 "Undo the state change: " + newState + " -> " + mInCallState);
wangqicf61ca02017-08-31 15:32:55 -07001354 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001355 return mInCallState;
1356 }
1357
1358 // We're about the bring up the in-call UI for outgoing and incoming call. If we still have
1359 // dialogs up, we need to clear them out before showing in-call screen. This is necessary
1360 // to fix the bug that dialog will show up when data reaches limit even after makeing new
1361 // outgoing call after user ignore it by pressing home button.
1362 if ((newState == InCallState.INCOMING || newState == InCallState.PENDING_OUTGOING)
1363 && !showCallUi
1364 && isActivityStarted()) {
1365 mInCallActivity.dismissPendingDialogs();
1366 }
1367
1368 if (showCallUi || showAccountPicker) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001369 LogUtil.i("InCallPresenter.startOrFinishUi", "Start in call UI");
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001370 showInCall(false /* showDialpad */, !showAccountPicker /* newOutgoingCall */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001371 } else if (startIncomingCallSequence) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001372 LogUtil.i("InCallPresenter.startOrFinishUi", "Start Full Screen in call UI");
Eric Erfanianccca3152017-02-22 16:32:36 -08001373
wangqic8cf79e2017-10-17 09:21:00 -07001374 mStatusBarNotifier.updateNotification();
Eric Erfanianccca3152017-02-22 16:32:36 -08001375 } else if (newState == InCallState.NO_CALLS) {
1376 // The new state is the no calls state. Tear everything down.
1377 attemptFinishActivity();
1378 attemptCleanup();
1379 }
1380
wangqicf61ca02017-08-31 15:32:55 -07001381 Trace.endSection();
Eric Erfanianccca3152017-02-22 16:32:36 -08001382 return newState;
1383 }
1384
1385 /**
1386 * Sets the DisconnectCause for a call that was disconnected because it was missing a PhoneAccount
1387 * or PhoneAccounts to select from.
1388 */
1389 private void setDisconnectCauseForMissingAccounts(DialerCall call) {
1390
1391 Bundle extras = call.getIntentExtras();
1392 // Initialize the extras bundle to avoid NPE
1393 if (extras == null) {
1394 extras = new Bundle();
1395 }
1396
1397 final List<PhoneAccountHandle> phoneAccountHandles =
1398 extras.getParcelableArrayList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS);
1399
1400 if (phoneAccountHandles == null || phoneAccountHandles.isEmpty()) {
1401 String scheme = call.getHandle().getScheme();
1402 final String errorMsg =
1403 PhoneAccount.SCHEME_TEL.equals(scheme)
1404 ? mContext.getString(R.string.callFailed_simError)
1405 : mContext.getString(R.string.incall_error_supp_service_unknown);
1406 DisconnectCause disconnectCause =
1407 new DisconnectCause(DisconnectCause.ERROR, null, errorMsg, errorMsg);
1408 call.setDisconnectCause(disconnectCause);
1409 }
1410 }
1411
Eric Erfanianccca3152017-02-22 16:32:36 -08001412 /**
1413 * @return {@code true} if the InCallPresenter is ready to be torn down, {@code false} otherwise.
1414 * Calling classes should use this as an indication whether to interact with the
1415 * InCallPresenter or not.
1416 */
1417 public boolean isReadyForTearDown() {
1418 return mInCallActivity == null && !mServiceConnected && mInCallState == InCallState.NO_CALLS;
1419 }
1420
1421 /**
1422 * Checks to see if both the UI is gone and the service is disconnected. If so, tear it all down.
1423 */
1424 private void attemptCleanup() {
1425 if (isReadyForTearDown()) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001426 LogUtil.i("InCallPresenter.attemptCleanup", "Cleaning up");
Eric Erfanianccca3152017-02-22 16:32:36 -08001427
1428 cleanupSurfaces();
1429
Eric Erfanianccca3152017-02-22 16:32:36 -08001430 mIsChangingConfigurations = false;
1431
1432 // blow away stale contact info so that we get fresh data on
1433 // the next set of calls
1434 if (mContactInfoCache != null) {
1435 mContactInfoCache.clearCache();
1436 }
1437 mContactInfoCache = null;
1438
1439 if (mProximitySensor != null) {
1440 removeListener(mProximitySensor);
1441 mProximitySensor.tearDown();
1442 }
1443 mProximitySensor = null;
1444
1445 if (mStatusBarNotifier != null) {
1446 removeListener(mStatusBarNotifier);
Eric Erfaniand8046e52017-04-06 09:41:50 -07001447 EnrichedCallComponent.get(mContext)
1448 .getEnrichedCallManager()
1449 .unregisterStateChangedListener(mStatusBarNotifier);
Eric Erfanianccca3152017-02-22 16:32:36 -08001450 }
Eric Erfaniand8046e52017-04-06 09:41:50 -07001451
Eric Erfanianccca3152017-02-22 16:32:36 -08001452 if (mExternalCallNotifier != null && mExternalCallList != null) {
1453 mExternalCallList.removeExternalCallListener(mExternalCallNotifier);
1454 }
1455 mStatusBarNotifier = null;
1456
1457 if (mCallList != null) {
1458 mCallList.removeListener(this);
1459 mCallList.removeListener(mSpamCallListListener);
1460 }
1461 mCallList = null;
1462
1463 mContext = null;
1464 mInCallActivity = null;
1465 mManageConferenceActivity = null;
1466
1467 mListeners.clear();
1468 mIncomingCallListeners.clear();
1469 mDetailsListeners.clear();
1470 mCanAddCallListeners.clear();
1471 mOrientationListeners.clear();
1472 mInCallEventListeners.clear();
1473 mInCallUiListeners.clear();
twyen8efb4952017-10-06 16:35:54 -07001474 if (!mInCallUiLocks.isEmpty()) {
1475 LogUtil.e("InCallPresenter.attemptCleanup", "held in call locks: " + mInCallUiLocks);
1476 mInCallUiLocks.clear();
1477 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001478 LogUtil.d("InCallPresenter.attemptCleanup", "finished");
Eric Erfanianccca3152017-02-22 16:32:36 -08001479 }
1480 }
1481
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001482 public void showInCall(boolean showDialpad, boolean newOutgoingCall) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001483 LogUtil.i("InCallPresenter.showInCall", "Showing InCallActivity");
Eric Erfanianccca3152017-02-22 16:32:36 -08001484 mContext.startActivity(
1485 InCallActivity.getIntent(
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001486 mContext, showDialpad, newOutgoingCall, false /* forFullScreen */));
Eric Erfanianccca3152017-02-22 16:32:36 -08001487 }
1488
1489 public void onServiceBind() {
1490 mServiceBound = true;
1491 }
1492
1493 public void onServiceUnbind() {
1494 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(false, null);
1495 mServiceBound = false;
1496 }
1497
1498 public boolean isServiceBound() {
1499 return mServiceBound;
1500 }
1501
1502 public void maybeStartRevealAnimation(Intent intent) {
1503 if (intent == null || mInCallActivity != null) {
1504 return;
1505 }
1506 final Bundle extras = intent.getBundleExtra(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS);
1507 if (extras == null) {
1508 // Incoming call, just show the in-call UI directly.
1509 return;
1510 }
1511
1512 if (extras.containsKey(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS)) {
1513 // Account selection dialog will show up so don't show the animation.
1514 return;
1515 }
1516
1517 final PhoneAccountHandle accountHandle =
1518 intent.getParcelableExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
1519 final Point touchPoint = extras.getParcelable(TouchPointManager.TOUCH_POINT);
Eric Erfanianccca3152017-02-22 16:32:36 -08001520
1521 InCallPresenter.getInstance().setBoundAndWaitingForOutgoingCall(true, accountHandle);
1522
1523 final Intent activityIntent =
Eric Erfaniand5e47f62017-03-15 14:41:07 -07001524 InCallActivity.getIntent(mContext, false, true, false /* forFullScreen */);
Eric Erfanianccca3152017-02-22 16:32:36 -08001525 activityIntent.putExtra(TouchPointManager.TOUCH_POINT, touchPoint);
1526 mContext.startActivity(activityIntent);
1527 }
1528
1529 /**
1530 * Retrieves the current in-call camera manager instance, creating if necessary.
1531 *
1532 * @return The {@link InCallCameraManager}.
1533 */
1534 public InCallCameraManager getInCallCameraManager() {
1535 synchronized (this) {
1536 if (mInCallCameraManager == null) {
1537 mInCallCameraManager = new InCallCameraManager(mContext);
1538 }
1539
1540 return mInCallCameraManager;
1541 }
1542 }
1543
1544 /**
1545 * Notifies listeners of changes in orientation and notify calls of rotation angle change.
1546 *
1547 * @param orientation The screen orientation of the device (one of: {@link
1548 * InCallOrientationEventListener#SCREEN_ORIENTATION_0}, {@link
1549 * InCallOrientationEventListener#SCREEN_ORIENTATION_90}, {@link
1550 * InCallOrientationEventListener#SCREEN_ORIENTATION_180}, {@link
1551 * InCallOrientationEventListener#SCREEN_ORIENTATION_270}).
1552 */
1553 public void onDeviceOrientationChange(@ScreenOrientation int orientation) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001554 LogUtil.d(
1555 "InCallPresenter.onDeviceOrientationChange",
1556 "onDeviceOrientationChange: orientation= " + orientation);
Eric Erfanianccca3152017-02-22 16:32:36 -08001557
1558 if (mCallList != null) {
1559 mCallList.notifyCallsOfDeviceRotation(orientation);
1560 } else {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001561 LogUtil.w("InCallPresenter.onDeviceOrientationChange", "CallList is null.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001562 }
1563
1564 // Notify listeners of device orientation changed.
1565 for (InCallOrientationListener listener : mOrientationListeners) {
1566 listener.onDeviceOrientationChanged(orientation);
1567 }
1568 }
1569
1570 /**
1571 * Configures the in-call UI activity so it can change orientations or not. Enables the
1572 * orientation event listener if allowOrientationChange is true, disables it if false.
1573 *
1574 * @param allowOrientationChange {@code true} if the in-call UI can change between portrait and
1575 * landscape. {@code false} if the in-call UI should be locked in portrait.
1576 */
1577 public void setInCallAllowsOrientationChange(boolean allowOrientationChange) {
1578 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001579 LogUtil.e(
1580 "InCallPresenter.setInCallAllowsOrientationChange",
1581 "InCallActivity is null. Can't set requested orientation.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001582 return;
1583 }
1584 mInCallActivity.setAllowOrientationChange(allowOrientationChange);
1585 }
1586
1587 public void enableScreenTimeout(boolean enable) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001588 LogUtil.v("InCallPresenter.enableScreenTimeout", "enableScreenTimeout: value=" + enable);
1589 mScreenTimeoutEnabled = enable;
1590 applyScreenTimeout();
1591 }
1592
1593 private void applyScreenTimeout() {
Eric Erfanianccca3152017-02-22 16:32:36 -08001594 if (mInCallActivity == null) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001595 LogUtil.e("InCallPresenter.applyScreenTimeout", "InCallActivity is null.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001596 return;
1597 }
1598
1599 final Window window = mInCallActivity.getWindow();
Eric Erfanian2ca43182017-08-31 06:57:16 -07001600 if (mScreenTimeoutEnabled) {
Eric Erfanianccca3152017-02-22 16:32:36 -08001601 window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1602 } else {
1603 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1604 }
1605 }
1606
1607 /**
1608 * Hides or shows the conference manager fragment.
1609 *
1610 * @param show {@code true} if the conference manager should be shown, {@code false} if it should
1611 * be hidden.
1612 */
1613 public void showConferenceCallManager(boolean show) {
1614 if (mInCallActivity != null) {
1615 mInCallActivity.showConferenceFragment(show);
1616 }
1617 if (!show && mManageConferenceActivity != null) {
1618 mManageConferenceActivity.finish();
1619 }
1620 }
1621
1622 /**
1623 * Determines if the dialpad is visible.
1624 *
1625 * @return {@code true} if the dialpad is visible, {@code false} otherwise.
1626 */
1627 public boolean isDialpadVisible() {
1628 if (mInCallActivity == null) {
1629 return false;
1630 }
1631 return mInCallActivity.isDialpadVisible();
1632 }
1633
1634 public ThemeColorManager getThemeColorManager() {
1635 return mThemeColorManager;
1636 }
1637
wangqi8d662ca2017-10-26 11:27:19 -07001638 @VisibleForTesting
1639 public void setThemeColorManager(ThemeColorManager themeColorManager) {
1640 mThemeColorManager = themeColorManager;
1641 }
1642
Eric Erfanianccca3152017-02-22 16:32:36 -08001643 /** Called when the foreground call changes. */
1644 public void onForegroundCallChanged(DialerCall newForegroundCall) {
1645 mThemeColorManager.onForegroundCallChanged(mContext, newForegroundCall);
1646 if (mInCallActivity != null) {
1647 mInCallActivity.onForegroundCallChanged(newForegroundCall);
1648 }
1649 }
1650
1651 public InCallActivity getActivity() {
1652 return mInCallActivity;
1653 }
1654
1655 /** Called when the UI begins, and starts the callstate callbacks if necessary. */
1656 public void setActivity(InCallActivity inCallActivity) {
1657 if (inCallActivity == null) {
1658 throw new IllegalArgumentException("registerActivity cannot be called with null");
1659 }
1660 if (mInCallActivity != null && mInCallActivity != inCallActivity) {
Eric Erfanian2ca43182017-08-31 06:57:16 -07001661 LogUtil.w(
1662 "InCallPresenter.setActivity", "Setting a second activity before destroying the first.");
Eric Erfanianccca3152017-02-22 16:32:36 -08001663 }
1664 updateActivity(inCallActivity);
1665 }
1666
1667 ExternalCallNotifier getExternalCallNotifier() {
1668 return mExternalCallNotifier;
1669 }
1670
1671 VideoSurfaceTexture getLocalVideoSurfaceTexture() {
1672 if (mLocalVideoSurfaceTexture == null) {
roldenburg12b50c62017-09-01 14:41:19 -07001673 boolean isPixel2017 = false;
1674 if (mContext != null) {
1675 isPixel2017 = mContext.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE);
1676 }
1677 mLocalVideoSurfaceTexture = VideoSurfaceBindings.createLocalVideoSurfaceTexture(isPixel2017);
Eric Erfanianccca3152017-02-22 16:32:36 -08001678 }
1679 return mLocalVideoSurfaceTexture;
1680 }
1681
1682 VideoSurfaceTexture getRemoteVideoSurfaceTexture() {
1683 if (mRemoteVideoSurfaceTexture == null) {
roldenburg12b50c62017-09-01 14:41:19 -07001684 boolean isPixel2017 = false;
1685 if (mContext != null) {
1686 isPixel2017 = mContext.getPackageManager().hasSystemFeature(PIXEL2017_SYSTEM_FEATURE);
1687 }
Eric Erfanian2ca43182017-08-31 06:57:16 -07001688 mRemoteVideoSurfaceTexture =
roldenburg12b50c62017-09-01 14:41:19 -07001689 VideoSurfaceBindings.createRemoteVideoSurfaceTexture(isPixel2017);
Eric Erfanianccca3152017-02-22 16:32:36 -08001690 }
1691 return mRemoteVideoSurfaceTexture;
1692 }
1693
1694 void cleanupSurfaces() {
1695 if (mRemoteVideoSurfaceTexture != null) {
1696 mRemoteVideoSurfaceTexture.setDoneWithSurface();
1697 mRemoteVideoSurfaceTexture = null;
1698 }
1699 if (mLocalVideoSurfaceTexture != null) {
1700 mLocalVideoSurfaceTexture.setDoneWithSurface();
1701 mLocalVideoSurfaceTexture = null;
1702 }
1703 }
1704
yueg77cb8e52017-10-27 16:42:51 -07001705 @Override
1706 public void onAudioStateChanged(CallAudioState audioState) {
1707 if (mStatusBarNotifier != null) {
1708 mStatusBarNotifier.updateNotification();
1709 }
1710 }
1711
Eric Erfanianccca3152017-02-22 16:32:36 -08001712 /** All the main states of InCallActivity. */
1713 public enum InCallState {
1714 // InCall Screen is off and there are no calls
1715 NO_CALLS,
1716
1717 // Incoming-call screen is up
1718 INCOMING,
1719
1720 // In-call experience is showing
1721 INCALL,
1722
1723 // Waiting for user input before placing outgoing call
1724 WAITING_FOR_ACCOUNT,
1725
1726 // UI is starting up but no call has been initiated yet.
1727 // The UI is waiting for Telecom to respond.
1728 PENDING_OUTGOING,
1729
1730 // User is dialing out
1731 OUTGOING;
1732
1733 public boolean isIncoming() {
1734 return (this == INCOMING);
1735 }
1736
1737 public boolean isConnectingOrConnected() {
1738 return (this == INCOMING || this == OUTGOING || this == INCALL);
1739 }
1740 }
1741
1742 /** Interface implemented by classes that need to know about the InCall State. */
1743 public interface InCallStateListener {
1744
1745 // TODO: Enhance state to contain the call objects instead of passing CallList
1746 void onStateChange(InCallState oldState, InCallState newState, CallList callList);
1747 }
1748
1749 public interface IncomingCallListener {
1750
1751 void onIncomingCall(InCallState oldState, InCallState newState, DialerCall call);
1752 }
1753
1754 public interface CanAddCallListener {
1755
1756 void onCanAddCallChanged(boolean canAddCall);
1757 }
1758
1759 public interface InCallDetailsListener {
1760
1761 void onDetailsChanged(DialerCall call, android.telecom.Call.Details details);
1762 }
1763
1764 public interface InCallOrientationListener {
1765
1766 void onDeviceOrientationChanged(@ScreenOrientation int orientation);
1767 }
1768
1769 /**
1770 * Interface implemented by classes that need to know about events which occur within the In-Call
1771 * UI. Used as a means of communicating between fragments that make up the UI.
1772 */
1773 public interface InCallEventListener {
1774
1775 void onFullscreenModeChanged(boolean isFullscreenMode);
1776 }
1777
1778 public interface InCallUiListener {
1779
1780 void onUiShowing(boolean showing);
1781 }
twyen8efb4952017-10-06 16:35:54 -07001782
1783 private class InCallUiLockImpl implements InCallUiLock {
1784 private final String tag;
1785
1786 private InCallUiLockImpl(String tag) {
1787 this.tag = tag;
1788 }
1789
1790 @MainThread
1791 @Override
1792 public void release() {
1793 Assert.isMainThread();
1794 releaseInCallUiLock(InCallUiLockImpl.this);
1795 }
1796
1797 @Override
1798 public String toString() {
1799 return "InCallUiLock[" + tag + "]";
1800 }
1801 }
1802
1803 @MainThread
1804 public InCallUiLock acquireInCallUiLock(String tag) {
1805 Assert.isMainThread();
1806 InCallUiLock lock = new InCallUiLockImpl(tag);
1807 mInCallUiLocks.add(lock);
1808 return lock;
1809 }
1810
1811 @MainThread
1812 private void releaseInCallUiLock(InCallUiLock lock) {
1813 Assert.isMainThread();
1814 LogUtil.i("InCallPresenter.releaseInCallUiLock", "releasing %s", lock);
1815 mInCallUiLocks.remove(lock);
1816 if (mInCallUiLocks.isEmpty()) {
1817 LogUtil.i("InCallPresenter.releaseInCallUiLock", "all locks released");
1818 if (mInCallState == InCallState.NO_CALLS) {
1819 LogUtil.i("InCallPresenter.releaseInCallUiLock", "no more calls, finishing UI");
1820 attemptFinishActivity();
1821 attemptCleanup();
1822 }
1823 }
1824 }
1825
1826 @MainThread
1827 public boolean isInCallUiLocked() {
1828 Assert.isMainThread();
1829 if (mInCallUiLocks.isEmpty()) {
1830 return false;
1831 }
1832 for (InCallUiLock lock : mInCallUiLocks) {
1833 LogUtil.i("InCallPresenter.isInCallUiLocked", "still locked by %s", lock);
1834 }
1835 return true;
1836 }
1837
1838 private final Set<InCallUiLock> mInCallUiLocks = new ArraySet<>();
Eric Erfanianccca3152017-02-22 16:32:36 -08001839}