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