blob: c7226753f0ad327936be3844602d022401e3a0ef [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 static com.android.contacts.common.compat.CallCompat.Details.PROPERTY_ENTERPRISE_CALL;
20import static com.android.incallui.NotificationBroadcastReceiver.ACTION_ACCEPT_VIDEO_UPGRADE_REQUEST;
21import static com.android.incallui.NotificationBroadcastReceiver.ACTION_ANSWER_VIDEO_INCOMING_CALL;
22import static com.android.incallui.NotificationBroadcastReceiver.ACTION_ANSWER_VOICE_INCOMING_CALL;
23import static com.android.incallui.NotificationBroadcastReceiver.ACTION_DECLINE_INCOMING_CALL;
24import static com.android.incallui.NotificationBroadcastReceiver.ACTION_DECLINE_VIDEO_UPGRADE_REQUEST;
25import static com.android.incallui.NotificationBroadcastReceiver.ACTION_HANG_UP_ONGOING_CALL;
26
27import android.app.ActivityManager;
28import android.app.Notification;
29import android.app.NotificationManager;
30import android.app.PendingIntent;
31import android.content.Context;
32import android.content.Intent;
33import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
35import android.graphics.drawable.BitmapDrawable;
36import android.graphics.drawable.Drawable;
37import android.media.AudioAttributes;
38import android.net.Uri;
39import android.os.Build.VERSION;
40import android.os.Build.VERSION_CODES;
41import android.support.annotation.ColorRes;
42import android.support.annotation.NonNull;
43import android.support.annotation.Nullable;
44import android.support.annotation.StringRes;
45import android.support.annotation.VisibleForTesting;
46import android.telecom.Call.Details;
47import android.telecom.PhoneAccount;
48import android.telecom.TelecomManager;
49import android.text.BidiFormatter;
50import android.text.Spannable;
51import android.text.SpannableString;
52import android.text.TextDirectionHeuristics;
53import android.text.TextUtils;
54import android.text.style.ForegroundColorSpan;
55import com.android.contacts.common.ContactsUtils;
56import com.android.contacts.common.ContactsUtils.UserType;
57import com.android.contacts.common.preference.ContactsPreferences;
58import com.android.contacts.common.util.BitmapUtil;
59import com.android.contacts.common.util.ContactDisplayUtils;
60import com.android.dialer.common.LogUtil;
61import com.android.dialer.util.DrawableConverter;
62import com.android.incallui.ContactInfoCache.ContactCacheEntry;
63import com.android.incallui.ContactInfoCache.ContactInfoCacheCallback;
64import com.android.incallui.InCallPresenter.InCallState;
65import com.android.incallui.async.PausableExecutorImpl;
66import com.android.incallui.call.CallList;
67import com.android.incallui.call.DialerCall;
68import com.android.incallui.call.DialerCall.SessionModificationState;
69import com.android.incallui.call.DialerCallListener;
70import com.android.incallui.ringtone.DialerRingtoneManager;
71import com.android.incallui.ringtone.InCallTonePlayer;
72import com.android.incallui.ringtone.ToneGeneratorFactory;
73import java.util.Objects;
74
75/** This class adds Notifications to the status bar for the in-call experience. */
76public class StatusBarNotifier implements InCallPresenter.InCallStateListener {
77
78 // Notification types
79 // Indicates that no notification is currently showing.
80 private static final int NOTIFICATION_NONE = 0;
81 // Notification for an active call. This is non-interruptive, but cannot be dismissed.
82 private static final int NOTIFICATION_IN_CALL = 1;
83 // Notification for incoming calls. This is interruptive and will show up as a HUN.
84 private static final int NOTIFICATION_INCOMING_CALL = 2;
85
86 private static final int PENDING_INTENT_REQUEST_CODE_NON_FULL_SCREEN = 0;
87 private static final int PENDING_INTENT_REQUEST_CODE_FULL_SCREEN = 1;
88
89 private static final long[] VIBRATE_PATTERN = new long[] {0, 1000, 1000};
90
91 private final Context mContext;
92 private final ContactInfoCache mContactInfoCache;
93 private final NotificationManager mNotificationManager;
94 private final DialerRingtoneManager mDialerRingtoneManager;
95 @Nullable private ContactsPreferences mContactsPreferences;
96 private int mCurrentNotification = NOTIFICATION_NONE;
97 private int mCallState = DialerCall.State.INVALID;
98 private int mSavedIcon = 0;
99 private String mSavedContent = null;
100 private Bitmap mSavedLargeIcon;
101 private String mSavedContentTitle;
102 private Uri mRingtone;
103 private StatusBarCallListener mStatusBarCallListener;
104
105 public StatusBarNotifier(@NonNull Context context, @NonNull ContactInfoCache contactInfoCache) {
106 Objects.requireNonNull(context);
107 mContext = context;
108 mContactsPreferences = ContactsPreferencesFactory.newContactsPreferences(mContext);
109 mContactInfoCache = contactInfoCache;
110 mNotificationManager = context.getSystemService(NotificationManager.class);
111 mDialerRingtoneManager =
112 new DialerRingtoneManager(
113 new InCallTonePlayer(new ToneGeneratorFactory(), new PausableExecutorImpl()),
114 CallList.getInstance());
115 mCurrentNotification = NOTIFICATION_NONE;
116 }
117
118 /**
119 * Should only be called from a irrecoverable state where it is necessary to dismiss all
120 * notifications.
121 */
122 static void clearAllCallNotifications(Context backupContext) {
123 Log.i(
124 StatusBarNotifier.class.getSimpleName(),
125 "Something terrible happened. Clear all InCall notifications");
126
127 NotificationManager notificationManager =
128 backupContext.getSystemService(NotificationManager.class);
129 notificationManager.cancel(NOTIFICATION_IN_CALL);
130 notificationManager.cancel(NOTIFICATION_INCOMING_CALL);
131 }
132
133 private static int getWorkStringFromPersonalString(int resId) {
134 if (resId == R.string.notification_ongoing_call) {
135 return R.string.notification_ongoing_work_call;
136 } else if (resId == R.string.notification_ongoing_call_wifi) {
137 return R.string.notification_ongoing_work_call_wifi;
138 } else if (resId == R.string.notification_incoming_call_wifi) {
139 return R.string.notification_incoming_work_call_wifi;
140 } else if (resId == R.string.notification_incoming_call) {
141 return R.string.notification_incoming_work_call;
142 } else {
143 return resId;
144 }
145 }
146
147 /**
148 * Returns PendingIntent for answering a phone call. This will typically be used from Notification
149 * context.
150 */
151 private static PendingIntent createNotificationPendingIntent(Context context, String action) {
152 final Intent intent = new Intent(action, null, context, NotificationBroadcastReceiver.class);
153 return PendingIntent.getBroadcast(context, 0, intent, 0);
154 }
155
156 /** Creates notifications according to the state we receive from {@link InCallPresenter}. */
157 @Override
158 public void onStateChange(InCallState oldState, InCallState newState, CallList callList) {
159 Log.d(this, "onStateChange");
160 updateNotification(callList);
161 }
162
163 /**
164 * Updates the phone app's status bar notification *and* launches the incoming call UI in response
165 * to a new incoming call.
166 *
167 * <p>If an incoming call is ringing (or call-waiting), the notification will also include a
168 * "fullScreenIntent" that will cause the InCallScreen to be launched, unless the current
169 * foreground activity is marked as "immersive".
170 *
171 * <p>(This is the mechanism that actually brings up the incoming call UI when we receive a "new
172 * ringing connection" event from the telephony layer.)
173 *
174 * <p>Also note that this method is safe to call even if the phone isn't actually ringing (or,
175 * more likely, if an incoming call *was* ringing briefly but then disconnected). In that case,
176 * we'll simply update or cancel the in-call notification based on the current phone state.
177 *
178 * @see #updateInCallNotification(CallList)
179 */
180 public void updateNotification(CallList callList) {
181 updateInCallNotification(callList);
182 }
183
184 /**
185 * Take down the in-call notification.
186 *
187 * @see #updateInCallNotification(CallList)
188 */
189 private void cancelNotification() {
190 if (mStatusBarCallListener != null) {
191 setStatusBarCallListener(null);
192 }
193 if (mCurrentNotification != NOTIFICATION_NONE) {
194 Log.d(this, "cancelInCall()...");
195 mNotificationManager.cancel(mCurrentNotification);
196 }
197 mCurrentNotification = NOTIFICATION_NONE;
198 }
199
200 /**
201 * Helper method for updateInCallNotification() and updateNotification(): Update the phone app's
202 * status bar notification based on the current telephony state, or cancels the notification if
203 * the phone is totally idle.
204 */
205 private void updateInCallNotification(CallList callList) {
206 Log.d(this, "updateInCallNotification...");
207
208 final DialerCall call = getCallToShow(callList);
209
210 if (call != null) {
211 showNotification(callList, call);
212 } else {
213 cancelNotification();
214 }
215 }
216
217 private void showNotification(final CallList callList, final DialerCall call) {
218 final boolean isIncoming =
219 (call.getState() == DialerCall.State.INCOMING
220 || call.getState() == DialerCall.State.CALL_WAITING);
221 setStatusBarCallListener(new StatusBarCallListener(call));
222
223 // we make a call to the contact info cache to query for supplemental data to what the
224 // call provides. This includes the contact name and photo.
225 // This callback will always get called immediately and synchronously with whatever data
226 // it has available, and may make a subsequent call later (same thread) if it had to
227 // call into the contacts provider for more data.
228 mContactInfoCache.findInfo(
229 call,
230 isIncoming,
231 new ContactInfoCacheCallback() {
232 @Override
233 public void onContactInfoComplete(String callId, ContactCacheEntry entry) {
234 DialerCall call = callList.getCallById(callId);
235 if (call != null) {
236 call.getLogState().contactLookupResult = entry.contactLookupResult;
237 buildAndSendNotification(callList, call, entry);
238 }
239 }
240
241 @Override
242 public void onImageLoadComplete(String callId, ContactCacheEntry entry) {
243 DialerCall call = callList.getCallById(callId);
244 if (call != null) {
245 buildAndSendNotification(callList, call, entry);
246 }
247 }
248 });
249 }
250
251 /** Sets up the main Ui for the notification */
252 private void buildAndSendNotification(
253 CallList callList, DialerCall originalCall, ContactCacheEntry contactInfo) {
254 // This can get called to update an existing notification after contact information has come
255 // back. However, it can happen much later. Before we continue, we need to make sure that
256 // the call being passed in is still the one we want to show in the notification.
257 final DialerCall call = getCallToShow(callList);
258 if (call == null || !call.getId().equals(originalCall.getId())) {
259 return;
260 }
261
262 final int callState = call.getState();
263
264 // Check if data has changed; if nothing is different, don't issue another notification.
265 final int iconResId = getIconToDisplay(call);
266 Bitmap largeIcon = getLargeIconToDisplay(contactInfo, call);
267 final String content = getContentString(call, contactInfo.userType);
268 final String contentTitle = getContentTitle(contactInfo, call);
269
270 final boolean isVideoUpgradeRequest =
271 call.getSessionModificationState()
272 == DialerCall.SESSION_MODIFICATION_STATE_RECEIVED_UPGRADE_TO_VIDEO_REQUEST;
273 final int notificationType;
274 if (callState == DialerCall.State.INCOMING
275 || callState == DialerCall.State.CALL_WAITING
276 || isVideoUpgradeRequest) {
277 notificationType = NOTIFICATION_INCOMING_CALL;
278 } else {
279 notificationType = NOTIFICATION_IN_CALL;
280 }
281
282 if (!checkForChangeAndSaveData(
283 iconResId,
284 content,
285 largeIcon,
286 contentTitle,
287 callState,
288 notificationType,
289 contactInfo.contactRingtoneUri)) {
290 return;
291 }
292
293 if (largeIcon != null) {
294 largeIcon = getRoundedIcon(largeIcon);
295 }
296
297 // This builder is used for the notification shown when the device is locked and the user
298 // has set their notification settings to 'hide sensitive content'
299 // {@see Notification.Builder#setPublicVersion}.
300 Notification.Builder publicBuilder = new Notification.Builder(mContext);
301 publicBuilder
302 .setSmallIcon(iconResId)
303 .setColor(mContext.getResources().getColor(R.color.dialer_theme_color))
304 // Hide work call state for the lock screen notification
305 .setContentTitle(getContentString(call, ContactsUtils.USER_TYPE_CURRENT));
306 setNotificationWhen(call, callState, publicBuilder);
307
308 // Builder for the notification shown when the device is unlocked or the user has set their
309 // notification settings to 'show all notification content'.
310 final Notification.Builder builder = getNotificationBuilder();
311 builder.setPublicVersion(publicBuilder.build());
312
313 // Set up the main intent to send the user to the in-call screen
314 builder.setContentIntent(
315 createLaunchPendingIntent(false /* isFullScreen */, call.isVideoCall()));
316
317 // Set the intent as a full screen intent as well if a call is incoming
318 if (notificationType == NOTIFICATION_INCOMING_CALL) {
319 if (!InCallPresenter.getInstance().isActivityStarted()) {
320 configureFullScreenIntent(
321 builder,
322 createLaunchPendingIntent(true /* isFullScreen */, call.isVideoCall()),
323 callList,
324 call);
325 } else {
326 // If the incall screen is already up, we don't want to show HUN but regular notification
327 // should still be shown. In order to do that the previous one with full screen intent
328 // needs to be cancelled.
329 LogUtil.d(
330 "StatusBarNotifier.buildAndSendNotification",
331 "cancel previous incoming call notification");
332 mNotificationManager.cancel(NOTIFICATION_INCOMING_CALL);
333 }
334 // Set the notification category for incoming calls
335 builder.setCategory(Notification.CATEGORY_CALL);
336 }
337
338 // Set the content
339 builder.setContentText(content);
340 builder.setSmallIcon(iconResId);
341 builder.setContentTitle(contentTitle);
342 builder.setLargeIcon(largeIcon);
343 builder.setColor(mContext.getResources().getColor(R.color.dialer_theme_color));
344
345 if (isVideoUpgradeRequest) {
346 builder.setUsesChronometer(false);
347 addDismissUpgradeRequestAction(builder);
348 addAcceptUpgradeRequestAction(builder);
349 } else {
350 createIncomingCallNotification(call, callState, builder);
351 }
352
353 addPersonReference(builder, contactInfo, call);
354
355 // Fire off the notification
356 Notification notification = builder.build();
357
358 if (mDialerRingtoneManager.shouldPlayRingtone(callState, contactInfo.contactRingtoneUri)) {
359 notification.flags |= Notification.FLAG_INSISTENT;
360 notification.sound = contactInfo.contactRingtoneUri;
361 AudioAttributes.Builder audioAttributes = new AudioAttributes.Builder();
362 audioAttributes.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC);
363 audioAttributes.setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE);
364 notification.audioAttributes = audioAttributes.build();
365 if (mDialerRingtoneManager.shouldVibrate(mContext.getContentResolver())) {
366 notification.vibrate = VIBRATE_PATTERN;
367 }
368 }
369 if (mDialerRingtoneManager.shouldPlayCallWaitingTone(callState)) {
370 Log.v(this, "Playing call waiting tone");
371 mDialerRingtoneManager.playCallWaitingTone();
372 }
373 if (mCurrentNotification != notificationType && mCurrentNotification != NOTIFICATION_NONE) {
374 Log.i(this, "Previous notification already showing - cancelling " + mCurrentNotification);
375 mNotificationManager.cancel(mCurrentNotification);
376 }
377
378 Log.i(this, "Displaying notification for " + notificationType);
379 try {
380 mNotificationManager.notify(notificationType, notification);
381 } catch (RuntimeException e) {
382 // TODO(b/34744003): Move the memory stats into silent feedback PSD.
383 ActivityManager activityManager = mContext.getSystemService(ActivityManager.class);
384 ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
385 activityManager.getMemoryInfo(memoryInfo);
386 throw new RuntimeException(
387 String.format(
388 "Error displaying notification with photo type: %d (low memory? %b, availMem: %d)",
389 contactInfo.photoType, memoryInfo.lowMemory, memoryInfo.availMem),
390 e);
391 }
392 call.getLatencyReport().onNotificationShown();
393 mCurrentNotification = notificationType;
394 }
395
396 private void createIncomingCallNotification(
397 DialerCall call, int state, Notification.Builder builder) {
398 setNotificationWhen(call, state, builder);
399
400 // Add hang up option for any active calls (active | onhold), outgoing calls (dialing).
401 if (state == DialerCall.State.ACTIVE
402 || state == DialerCall.State.ONHOLD
403 || DialerCall.State.isDialing(state)) {
404 addHangupAction(builder);
405 } else if (state == DialerCall.State.INCOMING || state == DialerCall.State.CALL_WAITING) {
406 addDismissAction(builder);
407 if (call.isVideoCall()) {
408 addVideoCallAction(builder);
409 } else {
410 addAnswerAction(builder);
411 }
412 }
413 }
414
415 /**
416 * Sets the notification's when section as needed. For active calls, this is explicitly set as the
417 * duration of the call. For all other states, the notification will automatically show the time
418 * at which the notification was created.
419 */
420 private void setNotificationWhen(DialerCall call, int state, Notification.Builder builder) {
421 if (state == DialerCall.State.ACTIVE) {
422 builder.setUsesChronometer(true);
423 builder.setWhen(call.getConnectTimeMillis());
424 } else {
425 builder.setUsesChronometer(false);
426 }
427 }
428
429 /**
430 * Checks the new notification data and compares it against any notification that we are already
431 * displaying. If the data is exactly the same, we return false so that we do not issue a new
432 * notification for the exact same data.
433 */
434 private boolean checkForChangeAndSaveData(
435 int icon,
436 String content,
437 Bitmap largeIcon,
438 String contentTitle,
439 int state,
440 int notificationType,
441 Uri ringtone) {
442
443 // The two are different:
444 // if new title is not null, it should be different from saved version OR
445 // if new title is null, the saved version should not be null
446 final boolean contentTitleChanged =
447 (contentTitle != null && !contentTitle.equals(mSavedContentTitle))
448 || (contentTitle == null && mSavedContentTitle != null);
449
450 // any change means we are definitely updating
451 boolean retval =
452 (mSavedIcon != icon)
453 || !Objects.equals(mSavedContent, content)
454 || (mCallState != state)
455 || (mSavedLargeIcon != largeIcon)
456 || contentTitleChanged
457 || !Objects.equals(mRingtone, ringtone);
458
459 // If we aren't showing a notification right now or the notification type is changing,
460 // definitely do an update.
461 if (mCurrentNotification != notificationType) {
462 if (mCurrentNotification == NOTIFICATION_NONE) {
463 Log.d(this, "Showing notification for first time.");
464 }
465 retval = true;
466 }
467
468 mSavedIcon = icon;
469 mSavedContent = content;
470 mCallState = state;
471 mSavedLargeIcon = largeIcon;
472 mSavedContentTitle = contentTitle;
473 mRingtone = ringtone;
474
475 if (retval) {
476 Log.d(this, "Data changed. Showing notification");
477 }
478
479 return retval;
480 }
481
482 /** Returns the main string to use in the notification. */
483 @VisibleForTesting
484 @Nullable
485 String getContentTitle(ContactCacheEntry contactInfo, DialerCall call) {
486 if (call.isConferenceCall() && !call.hasProperty(Details.PROPERTY_GENERIC_CONFERENCE)) {
487 return mContext.getResources().getString(R.string.conference_call_name);
488 }
489
490 String preferredName =
491 ContactDisplayUtils.getPreferredDisplayName(
492 contactInfo.namePrimary, contactInfo.nameAlternative, mContactsPreferences);
493 if (TextUtils.isEmpty(preferredName)) {
494 return TextUtils.isEmpty(contactInfo.number)
495 ? null
496 : BidiFormatter.getInstance()
497 .unicodeWrap(contactInfo.number, TextDirectionHeuristics.LTR);
498 }
499 return preferredName;
500 }
501
502 private void addPersonReference(
503 Notification.Builder builder, ContactCacheEntry contactInfo, DialerCall call) {
504 // Query {@link Contacts#CONTENT_LOOKUP_URI} directly with work lookup key is not allowed.
505 // So, do not pass {@link Contacts#CONTENT_LOOKUP_URI} to NotificationManager to avoid
506 // NotificationManager using it.
507 if (contactInfo.lookupUri != null && contactInfo.userType != ContactsUtils.USER_TYPE_WORK) {
508 builder.addPerson(contactInfo.lookupUri.toString());
509 } else if (!TextUtils.isEmpty(call.getNumber())) {
510 builder.addPerson(Uri.fromParts(PhoneAccount.SCHEME_TEL, call.getNumber(), null).toString());
511 }
512 }
513
514 /** Gets a large icon from the contact info object to display in the notification. */
515 private Bitmap getLargeIconToDisplay(ContactCacheEntry contactInfo, DialerCall call) {
516 Bitmap largeIcon = null;
517 if (call.isConferenceCall() && !call.hasProperty(Details.PROPERTY_GENERIC_CONFERENCE)) {
518 largeIcon = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.img_conference);
519 }
520 if (contactInfo.photo != null && (contactInfo.photo instanceof BitmapDrawable)) {
521 largeIcon = ((BitmapDrawable) contactInfo.photo).getBitmap();
522 }
523 if (call.isSpam()) {
524 Drawable drawable = mContext.getResources().getDrawable(R.drawable.blocked_contact);
525 largeIcon = DrawableConverter.drawableToBitmap(drawable);
526 }
527 return largeIcon;
528 }
529
530 private Bitmap getRoundedIcon(Bitmap bitmap) {
531 if (bitmap == null) {
532 return null;
533 }
534 final int height =
535 (int) mContext.getResources().getDimension(android.R.dimen.notification_large_icon_height);
536 final int width =
537 (int) mContext.getResources().getDimension(android.R.dimen.notification_large_icon_width);
538 return BitmapUtil.getRoundedBitmap(bitmap, width, height);
539 }
540
541 /**
542 * Returns the appropriate icon res Id to display based on the call for which we want to display
543 * information.
544 */
545 private int getIconToDisplay(DialerCall call) {
546 // Even if both lines are in use, we only show a single item in
547 // the expanded Notifications UI. It's labeled "Ongoing call"
548 // (or "On hold" if there's only one call, and it's on hold.)
549 // Also, we don't have room to display caller-id info from two
550 // different calls. So if both lines are in use, display info
551 // from the foreground call. And if there's a ringing call,
552 // display that regardless of the state of the other calls.
553 if (call.getState() == DialerCall.State.ONHOLD) {
554 return R.drawable.ic_phone_paused_white_24dp;
555 } else if (call.getSessionModificationState()
556 == DialerCall.SESSION_MODIFICATION_STATE_RECEIVED_UPGRADE_TO_VIDEO_REQUEST) {
557 return R.drawable.ic_videocam;
558 }
559 return R.anim.on_going_call;
560 }
561
562 /** Returns the message to use with the notification. */
563 private String getContentString(DialerCall call, @UserType long userType) {
564 boolean isIncomingOrWaiting =
565 call.getState() == DialerCall.State.INCOMING
566 || call.getState() == DialerCall.State.CALL_WAITING;
567
568 if (isIncomingOrWaiting
569 && call.getNumberPresentation() == TelecomManager.PRESENTATION_ALLOWED) {
570
571 if (!TextUtils.isEmpty(call.getChildNumber())) {
572 return mContext.getString(R.string.child_number, call.getChildNumber());
573 } else if (!TextUtils.isEmpty(call.getCallSubject()) && call.isCallSubjectSupported()) {
574 return call.getCallSubject();
575 }
576 }
577
578 int resId = R.string.notification_ongoing_call;
579 if (call.hasProperty(Details.PROPERTY_WIFI)) {
580 resId = R.string.notification_ongoing_call_wifi;
581 }
582
583 if (isIncomingOrWaiting) {
584 if (call.hasProperty(Details.PROPERTY_WIFI)) {
585 resId = R.string.notification_incoming_call_wifi;
586 } else {
587 if (call.isSpam()) {
588 resId = R.string.notification_incoming_spam_call;
589 } else {
590 resId = R.string.notification_incoming_call;
591 }
592 }
593 } else if (call.getState() == DialerCall.State.ONHOLD) {
594 resId = R.string.notification_on_hold;
595 } else if (DialerCall.State.isDialing(call.getState())) {
596 resId = R.string.notification_dialing;
597 } else if (call.getSessionModificationState()
598 == DialerCall.SESSION_MODIFICATION_STATE_RECEIVED_UPGRADE_TO_VIDEO_REQUEST) {
599 resId = R.string.notification_requesting_video_call;
600 }
601
602 // Is the call placed through work connection service.
603 boolean isWorkCall = call.hasProperty(PROPERTY_ENTERPRISE_CALL);
604 if (userType == ContactsUtils.USER_TYPE_WORK || isWorkCall) {
605 resId = getWorkStringFromPersonalString(resId);
606 }
607
608 return mContext.getString(resId);
609 }
610
611 /** Gets the most relevant call to display in the notification. */
612 private DialerCall getCallToShow(CallList callList) {
613 if (callList == null) {
614 return null;
615 }
616 DialerCall call = callList.getIncomingCall();
617 if (call == null) {
618 call = callList.getOutgoingCall();
619 }
620 if (call == null) {
621 call = callList.getVideoUpgradeRequestCall();
622 }
623 if (call == null) {
624 call = callList.getActiveOrBackgroundCall();
625 }
626 return call;
627 }
628
629 private Spannable getActionText(@StringRes int stringRes, @ColorRes int colorRes) {
630 Spannable spannable = new SpannableString(mContext.getText(stringRes));
631 if (VERSION.SDK_INT >= VERSION_CODES.N_MR1) {
632 // This will only work for cases where the Notification.Builder has a fullscreen intent set
633 // Notification.Builder that does not have a full screen intent will take the color of the
634 // app and the following leads to a no-op.
635 spannable.setSpan(
636 new ForegroundColorSpan(mContext.getColor(colorRes)), 0, spannable.length(), 0);
637 }
638 return spannable;
639 }
640
641 private void addAnswerAction(Notification.Builder builder) {
642 Log.d(this, "Will show \"answer\" action in the incoming call Notification");
643 PendingIntent answerVoicePendingIntent =
644 createNotificationPendingIntent(mContext, ACTION_ANSWER_VOICE_INCOMING_CALL);
645 builder.addAction(
646 R.anim.on_going_call,
647 getActionText(R.string.notification_action_answer, R.color.notification_action_accept),
648 answerVoicePendingIntent);
649 }
650
651 private void addDismissAction(Notification.Builder builder) {
652 Log.d(this, "Will show \"decline\" action in the incoming call Notification");
653 PendingIntent declinePendingIntent =
654 createNotificationPendingIntent(mContext, ACTION_DECLINE_INCOMING_CALL);
655 builder.addAction(
656 R.drawable.ic_close_dk,
657 getActionText(R.string.notification_action_dismiss, R.color.notification_action_dismiss),
658 declinePendingIntent);
659 }
660
661 private void addHangupAction(Notification.Builder builder) {
662 Log.d(this, "Will show \"hang-up\" action in the ongoing active call Notification");
663 PendingIntent hangupPendingIntent =
664 createNotificationPendingIntent(mContext, ACTION_HANG_UP_ONGOING_CALL);
665 builder.addAction(
666 R.drawable.ic_call_end_white_24dp,
667 getActionText(R.string.notification_action_end_call, R.color.notification_action_end_call),
668 hangupPendingIntent);
669 }
670
671 private void addVideoCallAction(Notification.Builder builder) {
672 Log.i(this, "Will show \"video\" action in the incoming call Notification");
673 PendingIntent answerVideoPendingIntent =
674 createNotificationPendingIntent(mContext, ACTION_ANSWER_VIDEO_INCOMING_CALL);
675 builder.addAction(
676 R.drawable.ic_videocam,
677 getActionText(
678 R.string.notification_action_answer_video, R.color.notification_action_answer_video),
679 answerVideoPendingIntent);
680 }
681
682 private void addAcceptUpgradeRequestAction(Notification.Builder builder) {
683 Log.i(this, "Will show \"accept upgrade\" action in the incoming call Notification");
684 PendingIntent acceptVideoPendingIntent =
685 createNotificationPendingIntent(mContext, ACTION_ACCEPT_VIDEO_UPGRADE_REQUEST);
686 builder.addAction(
687 R.drawable.ic_videocam,
688 getActionText(R.string.notification_action_accept, R.color.notification_action_accept),
689 acceptVideoPendingIntent);
690 }
691
692 private void addDismissUpgradeRequestAction(Notification.Builder builder) {
693 Log.i(this, "Will show \"dismiss upgrade\" action in the incoming call Notification");
694 PendingIntent declineVideoPendingIntent =
695 createNotificationPendingIntent(mContext, ACTION_DECLINE_VIDEO_UPGRADE_REQUEST);
696 builder.addAction(
697 R.drawable.ic_videocam,
698 getActionText(R.string.notification_action_dismiss, R.color.notification_action_dismiss),
699 declineVideoPendingIntent);
700 }
701
702 /** Adds fullscreen intent to the builder. */
703 private void configureFullScreenIntent(
704 Notification.Builder builder, PendingIntent intent, CallList callList, DialerCall call) {
705 // Ok, we actually want to launch the incoming call
706 // UI at this point (in addition to simply posting a notification
707 // to the status bar). Setting fullScreenIntent will cause
708 // the InCallScreen to be launched immediately *unless* the
709 // current foreground activity is marked as "immersive".
710 Log.d(this, "- Setting fullScreenIntent: " + intent);
711 builder.setFullScreenIntent(intent, true);
712
713 // Ugly hack alert:
714 //
715 // The NotificationManager has the (undocumented) behavior
716 // that it will *ignore* the fullScreenIntent field if you
717 // post a new Notification that matches the ID of one that's
718 // already active. Unfortunately this is exactly what happens
719 // when you get an incoming call-waiting call: the
720 // "ongoing call" notification is already visible, so the
721 // InCallScreen won't get launched in this case!
722 // (The result: if you bail out of the in-call UI while on a
723 // call and then get a call-waiting call, the incoming call UI
724 // won't come up automatically.)
725 //
726 // The workaround is to just notice this exact case (this is a
727 // call-waiting call *and* the InCallScreen is not in the
728 // foreground) and manually cancel the in-call notification
729 // before (re)posting it.
730 //
731 // TODO: there should be a cleaner way of avoiding this
732 // problem (see discussion in bug 3184149.)
733
734 // If a call is onhold during an incoming call, the call actually comes in as
735 // INCOMING. For that case *and* traditional call-waiting, we want to
736 // cancel the notification.
737 boolean isCallWaiting =
738 (call.getState() == DialerCall.State.CALL_WAITING
739 || (call.getState() == DialerCall.State.INCOMING
740 && callList.getBackgroundCall() != null));
741
742 if (isCallWaiting) {
743 Log.i(this, "updateInCallNotification: call-waiting! force relaunch...");
744 // Cancel the IN_CALL_NOTIFICATION immediately before
745 // (re)posting it; this seems to force the
746 // NotificationManager to launch the fullScreenIntent.
747 mNotificationManager.cancel(NOTIFICATION_IN_CALL);
748 }
749 }
750
751 private Notification.Builder getNotificationBuilder() {
752 final Notification.Builder builder = new Notification.Builder(mContext);
753 builder.setOngoing(true);
754
755 // Make the notification prioritized over the other normal notifications.
756 builder.setPriority(Notification.PRIORITY_HIGH);
757
758 return builder;
759 }
760
761 private PendingIntent createLaunchPendingIntent(boolean isFullScreen, boolean isVideoCall) {
762 Intent intent =
763 InCallActivity.getIntent(
764 mContext,
765 false /* showDialpad */,
766 false /* newOutgoingCall */,
767 isVideoCall,
768 isFullScreen);
769
770 int requestCode = PENDING_INTENT_REQUEST_CODE_NON_FULL_SCREEN;
771 if (isFullScreen) {
772 // Use a unique request code so that the pending intent isn't clobbered by the
773 // non-full screen pending intent.
774 requestCode = PENDING_INTENT_REQUEST_CODE_FULL_SCREEN;
775 }
776
777 // PendingIntent that can be used to launch the InCallActivity. The
778 // system fires off this intent if the user pulls down the windowshade
779 // and clicks the notification's expanded view. It's also used to
780 // launch the InCallActivity immediately when when there's an incoming
781 // call (see the "fullScreenIntent" field below).
782 return PendingIntent.getActivity(mContext, requestCode, intent, 0);
783 }
784
785 private void setStatusBarCallListener(StatusBarCallListener listener) {
786 if (mStatusBarCallListener != null) {
787 mStatusBarCallListener.cleanup();
788 }
789 mStatusBarCallListener = listener;
790 }
791
792 private class StatusBarCallListener implements DialerCallListener {
793
794 private DialerCall mDialerCall;
795
796 StatusBarCallListener(DialerCall dialerCall) {
797 mDialerCall = dialerCall;
798 mDialerCall.addListener(this);
799 }
800
801 void cleanup() {
802 mDialerCall.removeListener(this);
803 }
804
805 @Override
806 public void onDialerCallDisconnect() {}
807
808 @Override
809 public void onDialerCallUpdate() {
810 if (CallList.getInstance().getIncomingCall() == null) {
811 mDialerRingtoneManager.stopCallWaitingTone();
812 }
813 }
814
815 @Override
816 public void onDialerCallChildNumberChange() {}
817
818 @Override
819 public void onDialerCallLastForwardedNumberChange() {}
820
821 @Override
822 public void onDialerCallUpgradeToVideo() {}
823
824 @Override
825 public void onWiFiToLteHandover() {}
826
827 @Override
828 public void onHandoverToWifiFailure() {}
829
830 /**
831 * Responds to changes in the session modification state for the call by dismissing the status
832 * bar notification as required.
833 */
834 @Override
835 public void onDialerCallSessionModificationStateChange(@SessionModificationState int state) {
836 if (state == DialerCall.SESSION_MODIFICATION_STATE_NO_REQUEST) {
837 cleanup();
838 updateNotification(CallList.getInstance());
839 }
840 }
841 }
842}