Add support for Android 11 Conversation Bubbles.

This commit is contained in:
Alex Hart
2020-11-25 14:11:17 -04:00
committed by GitHub
parent 3aebadd90d
commit e1bf23251f
22 changed files with 518 additions and 70 deletions

View File

@@ -22,11 +22,10 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import androidx.core.app.NotificationManagerCompat;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies;
import org.thoughtcrime.securesms.database.MessageDatabase.MarkedMessageInfo;
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies;
import org.thoughtcrime.securesms.logging.Log;
import java.util.LinkedList;
@@ -53,7 +52,7 @@ public class AndroidAutoHeardReceiver extends BroadcastReceiver {
if (threadIds != null) {
int notificationId = intent.getIntExtra(NOTIFICATION_ID_EXTRA, -1);
NotificationManagerCompat.from(context).cancel(notificationId);
NotificationCancellationHelper.cancelLegacy(context, notificationId);
new AsyncTask<Void, Void, Void>() {
@Override

View File

@@ -66,7 +66,7 @@ import org.thoughtcrime.securesms.preferences.widgets.NotificationPrivacyPrefere
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.recipients.RecipientUtil;
import org.thoughtcrime.securesms.service.KeyCachingService;
import org.thoughtcrime.securesms.util.FeatureFlags;
import org.thoughtcrime.securesms.util.BubbleUtil;
import org.thoughtcrime.securesms.util.MediaUtil;
import org.thoughtcrime.securesms.util.MessageRecordUtil;
import org.thoughtcrime.securesms.util.ServiceUtil;
@@ -100,9 +100,9 @@ public class DefaultMessageNotifier implements MessageNotifier {
private static final String TAG = DefaultMessageNotifier.class.getSimpleName();
public static final String EXTRA_REMOTE_REPLY = "extra_remote_reply";
public static final String NOTIFICATION_GROUP = "messages";
private static final String EMOJI_REPLACEMENT_STRING = "__EMOJI__";
private static final String NOTIFICATION_GROUP = "messages";
private static final long MIN_AUDIBLE_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(2);
private static final long DESKTOP_ACTIVITY_PERIOD = TimeUnit.MINUTES.toMillis(1);
@@ -151,27 +151,6 @@ public class DefaultMessageNotifier implements MessageNotifier {
executor.cancel();
}
private static void cancelActiveNotifications(@NonNull Context context) {
NotificationManager notifications = ServiceUtil.getNotificationManager(context);
notifications.cancel(NotificationIds.MESSAGE_SUMMARY);
if (Build.VERSION.SDK_INT >= 23) {
try {
StatusBarNotification[] activeNotifications = notifications.getActiveNotifications();
for (StatusBarNotification activeNotification : activeNotifications) {
if (!CallNotificationBuilder.isWebRtcNotification(activeNotification.getId())) {
notifications.cancel(activeNotification.getId());
}
}
} catch (Throwable e) {
// XXX Appears to be a ROM bug, see #6043
Log.w(TAG, e);
notifications.cancelAll();
}
}
}
private static boolean isDisplayingSummaryNotification(@NonNull Context context) {
if (Build.VERSION.SDK_INT >= 23) {
try {
@@ -219,7 +198,7 @@ public class DefaultMessageNotifier implements MessageNotifier {
}
if (!validNotification) {
notifications.cancel(notification.getId());
NotificationCancellationHelper.cancel(context, notification.getId());
}
}
}
@@ -236,7 +215,7 @@ public class DefaultMessageNotifier implements MessageNotifier {
return;
}
updateNotification(context, -1, false, 0);
updateNotification(context, -1, false, 0, BubbleUtil.BubbleState.HIDDEN);
}
@Override
@@ -250,6 +229,11 @@ public class DefaultMessageNotifier implements MessageNotifier {
}
}
@Override
public void updateNotification(@NonNull Context context, long threadId, @NonNull BubbleUtil.BubbleState defaultBubbleState) {
updateNotification(context, threadId, false, 0, defaultBubbleState);
}
@Override
public void updateNotification(@NonNull Context context,
long threadId,
@@ -262,7 +246,7 @@ public class DefaultMessageNotifier implements MessageNotifier {
if (isVisible) {
sendInThreadNotification(context, recipient);
} else {
updateNotification(context, threadId, signal, 0);
updateNotification(context, threadId, signal, 0, BubbleUtil.BubbleState.HIDDEN);
}
}
}
@@ -283,9 +267,10 @@ public class DefaultMessageNotifier implements MessageNotifier {
@Override
public void updateNotification(@NonNull Context context,
long targetThread,
boolean signal,
int reminderCount)
long targetThread,
boolean signal,
int reminderCount,
@NonNull BubbleUtil.BubbleState defaultBubbleState)
{
boolean isReminder = reminderCount > 0;
Cursor telcoCursor = null;
@@ -298,7 +283,7 @@ public class DefaultMessageNotifier implements MessageNotifier {
if ((telcoCursor == null || telcoCursor.isAfterLast()) &&
(pushCursor == null || pushCursor.isAfterLast()))
{
cancelActiveNotifications(context);
NotificationCancellationHelper.cancelAllMessageNotifications(context);
updateBadge(context, 0);
clearReminder(context);
return;
@@ -322,14 +307,18 @@ public class DefaultMessageNotifier implements MessageNotifier {
new NotificationState(notificationState.getNotificationsForThread(threadId)),
signal && (threadId == targetThread),
true,
isReminder);
isReminder,
(threadId == targetThread) ? defaultBubbleState : BubbleUtil.BubbleState.HIDDEN);
}
}
}
sendMultipleThreadNotification(context, notificationState, signal && (Build.VERSION.SDK_INT < 23));
} else {
shouldScheduleReminder = sendSingleThreadNotification(context, notificationState, signal, false, isReminder);
long thread = notificationState.getNotifications().isEmpty() ? -1 : notificationState.getNotifications().get(0).getThreadId();
BubbleUtil.BubbleState bubbleState = thread == targetThread ? defaultBubbleState : BubbleUtil.BubbleState.HIDDEN;
shouldScheduleReminder = sendSingleThreadNotification(context, notificationState, signal, false, isReminder, bubbleState);
if (isDisplayingSummaryNotification(context)) {
sendMultipleThreadNotification(context, notificationState, false);
@@ -363,12 +352,13 @@ public class DefaultMessageNotifier implements MessageNotifier {
@NonNull NotificationState notificationState,
boolean signal,
boolean bundled,
boolean isReminder)
boolean isReminder,
@NonNull BubbleUtil.BubbleState defaultBubbleState)
{
Log.i(TAG, "sendSingleThreadNotification() signal: " + signal + " bundled: " + bundled);
if (notificationState.getNotifications().isEmpty()) {
if (!bundled) cancelActiveNotifications(context);
if (!bundled) NotificationCancellationHelper.cancelAllMessageNotifications(context);
Log.i(TAG, "[sendSingleThreadNotification] Empty notification state. Skipping.");
return false;
}
@@ -394,6 +384,7 @@ public class DefaultMessageNotifier implements MessageNotifier {
builder.setDeleteIntent(notificationState.getDeleteIntent(context));
builder.setOnlyAlertOnce(!shouldAlert);
builder.setSortKey(String.valueOf(Long.MAX_VALUE - notifications.get(0).getTimestamp()));
builder.setDefaultBubbleState(defaultBubbleState);
long timestamp = notifications.get(0).getTimestamp();
if (timestamp != 0) builder.setWhen(timestamp);
@@ -424,7 +415,7 @@ public class DefaultMessageNotifier implements MessageNotifier {
while(iterator.hasPrevious()) {
NotificationItem item = iterator.previous();
builder.addMessageBody(item.getRecipient(), item.getIndividualRecipient(), item.getText(), item.getTimestamp());
builder.addMessageBody(item.getRecipient(), item.getIndividualRecipient(), item.getText(), item.getTimestamp(), item.getSlideDeck());
}
if (signal) {
@@ -439,7 +430,6 @@ public class DefaultMessageNotifier implements MessageNotifier {
}
Notification notification = builder.build();
try {
NotificationManagerCompat.from(context).notify(notificationId, notification);
Log.i(TAG, "Posted notification.");

View File

@@ -7,7 +7,6 @@ import android.content.Intent;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationManagerCompat;
import com.annimon.stream.Collectors;
import com.annimon.stream.Stream;
@@ -44,7 +43,7 @@ public class MarkReadReceiver extends BroadcastReceiver {
final long[] threadIds = intent.getLongArrayExtra(THREAD_IDS_EXTRA);
if (threadIds != null) {
NotificationManagerCompat.from(context).cancel(intent.getIntExtra(NOTIFICATION_ID_EXTRA, -1));
NotificationCancellationHelper.cancelLegacy(context, intent.getIntExtra(NOTIFICATION_ID_EXTRA, -1));
new AsyncTask<Void, Void, Void>() {
@Override

View File

@@ -8,6 +8,7 @@ import androidx.annotation.NonNull;
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.util.BubbleUtil;
import org.thoughtcrime.securesms.util.concurrent.SignalExecutors;
public interface MessageNotifier {
@@ -19,8 +20,9 @@ public interface MessageNotifier {
void cancelDelayedNotifications();
void updateNotification(@NonNull Context context);
void updateNotification(@NonNull Context context, long threadId);
void updateNotification(@NonNull Context context, long threadId, @NonNull BubbleUtil.BubbleState defaultBubbleState);
void updateNotification(@NonNull Context context, long threadId, boolean signal);
void updateNotification(@NonNull Context context, long threadId, boolean signal, int reminderCount);
void updateNotification(@NonNull Context context, long threadId, boolean signal, int reminderCount, @NonNull BubbleUtil.BubbleState defaultBubbleState);
void clearReminder(@NonNull Context context);
@@ -30,7 +32,7 @@ public interface MessageNotifier {
public void onReceive(final Context context, final Intent intent) {
SignalExecutors.BOUNDED.execute(() -> {
int reminderCount = intent.getIntExtra("reminder_count", 0);
ApplicationDependencies.getMessageNotifier().updateNotification(context, -1, true, reminderCount + 1);
ApplicationDependencies.getMessageNotifier().updateNotification(context, -1, true, reminderCount + 1, BubbleUtil.BubbleState.HIDDEN);
});
}
}

View File

@@ -0,0 +1,159 @@
package org.thoughtcrime.securesms.notifications;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.service.notification.StatusBarNotification;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import com.annimon.stream.Stream;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies;
import org.thoughtcrime.securesms.logging.Log;
import org.thoughtcrime.securesms.recipients.RecipientId;
import org.thoughtcrime.securesms.util.BubbleUtil;
import org.thoughtcrime.securesms.util.ConversationUtil;
import org.thoughtcrime.securesms.util.ServiceUtil;
import java.util.Collection;
import java.util.Objects;
/**
* Consolidates Notification Cancellation logic to one class.
*
* Because Bubbles are tied to Notifications, and disappear when those Notificaitons are cancelled,
* we want to be very surgical about what notifications we dismiss and when. Behaviour on API levels
* previous to {@link org.thoughtcrime.securesms.util.ConversationUtil#CONVERSATION_SUPPORT_VERSION}
* is preserved.
*
*/
public final class NotificationCancellationHelper {
private static final String TAG = Log.tag(NotificationCancellationHelper.class);
private NotificationCancellationHelper() {}
/**
* Cancels all Message-Based notifications. Specifically, this is any notification that is not the
* summary notification assigned to the {@link DefaultMessageNotifier#NOTIFICATION_GROUP} group.
*
* We utilize our wrapped cancellation methods and a counter to make sure that we do not lose
* bubble notifications that do not have unread messages in them.
*/
static void cancelAllMessageNotifications(@NonNull Context context) {
if (Build.VERSION.SDK_INT >= 23) {
try {
NotificationManager notifications = ServiceUtil.getNotificationManager(context);
StatusBarNotification[] activeNotifications = notifications.getActiveNotifications();
int activeCount = 0;
for (StatusBarNotification activeNotification : activeNotifications) {
if (isSingleThreadNotification(activeNotification)) {
activeCount++;
if (cancel(context, activeNotification.getId())) {
activeCount--;
}
}
}
if (activeCount == 0) {
cancelLegacy(context, NotificationIds.MESSAGE_SUMMARY);
}
} catch (Throwable e) {
// XXX Appears to be a ROM bug, see #6043
Log.w(TAG, "Canceling all notifications.", e);
ServiceUtil.getNotificationManager(context).cancelAll();
}
} else {
cancelLegacy(context, NotificationIds.MESSAGE_SUMMARY);
}
}
/**
* @return whether this is a non-summary notification that is a member of the NOTIFICATION_GROUP group.
*/
@RequiresApi(23)
private static boolean isSingleThreadNotification(@NonNull StatusBarNotification statusBarNotification) {
return statusBarNotification.getId() != NotificationIds.MESSAGE_SUMMARY &&
Objects.equals(statusBarNotification.getNotification().getGroup(), DefaultMessageNotifier.NOTIFICATION_GROUP);
}
/**
* Attempts to cancel the given notification. If the notification is allowed to be displayed as a
* bubble, we do not cancel it.
*
* @return Whether or not the notification is considered cancelled.
*/
public static boolean cancel(@NonNull Context context, int notificationId) {
Log.d(TAG, "cancel() called with: notificationId = [" + notificationId + "]");
if (Build.VERSION.SDK_INT >= ConversationUtil.CONVERSATION_SUPPORT_VERSION) {
return cancelWithConversationSupport(context, notificationId);
} else {
cancelLegacy(context, notificationId);
return true;
}
}
/**
* Bypasses bubble check.
*/
public static void cancelLegacy(@NonNull Context context, int notificationId) {
Log.d(TAG, "cancelLegacy() called with: notificationId = [" + notificationId + "]");
ServiceUtil.getNotificationManager(context).cancel(notificationId);
}
/**
* Cancel method which first checks whether the notification in question is tied to a bubble that
* may or may not be displayed by the user.
*
* @return true if the notification was cancelled.
*/
@RequiresApi(ConversationUtil.CONVERSATION_SUPPORT_VERSION)
private static boolean cancelWithConversationSupport(@NonNull Context context, int notificationId) {
Log.d(TAG, "cancelWithConversationSupport() called with: notificationId = [" + notificationId + "]");
if (isCancellable(context, notificationId)) {
cancelLegacy(context, notificationId);
return true;
} else {
return false;
}
}
/**
* Checks whether the conversation for the given notification is allowed to be represented as a bubble.
*
* see {@link BubbleUtil#canBubble} for more information.
*/
@RequiresApi(ConversationUtil.CONVERSATION_SUPPORT_VERSION)
private static boolean isCancellable(@NonNull Context context, int notificationId) {
NotificationManager manager = ServiceUtil.getNotificationManager(context);
StatusBarNotification[] notifications = manager.getActiveNotifications();
Notification notification = Stream.of(notifications)
.filter(n -> n.getId() == notificationId)
.findFirst()
.map(StatusBarNotification::getNotification)
.orElse(null);
if (notification == null ||
notification.getShortcutId() == null ||
notification.getBubbleMetadata() == null) {
Log.d(TAG, "isCancellable: bubbles not available or notification does not exist");
return true;
}
RecipientId recipientId = RecipientId.from(notification.getShortcutId());
Long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(recipientId);
long focusedThreadId = ApplicationDependencies.getMessageNotifier().getVisibleThread();
if (Objects.equals(threadId, focusedThreadId)) {
Log.d(TAG, "isCancellable: user entered full screen thread.");
return true;
}
return !BubbleUtil.canBubble(context, recipientId, threadId);
}
}

View File

@@ -15,5 +15,4 @@ public final class NotificationIds {
public static int getNotificationIdForThread(long threadId) {
return THREAD + (int) threadId;
}
}

View File

@@ -7,6 +7,7 @@ import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.util.BubbleUtil;
import org.thoughtcrime.securesms.util.LeakyBucketLimiter;
import org.thoughtcrime.securesms.util.Util;
import org.thoughtcrime.securesms.util.concurrent.SignalExecutors;
@@ -65,14 +66,19 @@ public class OptimizedMessageNotifier implements MessageNotifier {
runOnLimiter(() -> wrapped.updateNotification(context, threadId));
}
@Override
public void updateNotification(@NonNull Context context, long threadId, @NonNull BubbleUtil.BubbleState defaultBubbleState) {
runOnLimiter(() -> wrapped.updateNotification(context, threadId, defaultBubbleState));
}
@Override
public void updateNotification(@NonNull Context context, long threadId, boolean signal) {
runOnLimiter(() -> wrapped.updateNotification(context, threadId, signal));
}
@Override
public void updateNotification(@NonNull Context context, long threadId, boolean signal, int reminderCount) {
runOnLimiter(() -> wrapped.updateNotification(context, threadId, signal, reminderCount));
public void updateNotification(@NonNull Context context, long threadId, boolean signal, int reminderCount, @NonNull BubbleUtil.BubbleState defaultBubbleState) {
runOnLimiter(() -> wrapped.updateNotification(context, threadId, signal, reminderCount, defaultBubbleState));
}
@Override

View File

@@ -27,6 +27,8 @@ import org.thoughtcrime.securesms.contacts.avatars.ContactColors;
import org.thoughtcrime.securesms.contacts.avatars.ContactPhoto;
import org.thoughtcrime.securesms.contacts.avatars.FallbackContactPhoto;
import org.thoughtcrime.securesms.contacts.avatars.GeneratedContactPhoto;
import org.thoughtcrime.securesms.conversation.ConversationIntents;
import org.thoughtcrime.securesms.database.DatabaseFactory;
import org.thoughtcrime.securesms.logging.Log;
import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader;
import org.thoughtcrime.securesms.mms.GlideApp;
@@ -36,6 +38,7 @@ import org.thoughtcrime.securesms.preferences.widgets.NotificationPrivacyPrefere
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.util.AvatarUtil;
import org.thoughtcrime.securesms.util.BitmapUtil;
import org.thoughtcrime.securesms.util.BubbleUtil;
import org.thoughtcrime.securesms.util.ConversationUtil;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
@@ -54,10 +57,11 @@ public class SingleRecipientNotificationBuilder extends AbstractNotificationBuil
private final List<NotificationCompat.MessagingStyle.Message> messages = new LinkedList<>();
private SlideDeck slideDeck;
private CharSequence contentTitle;
private CharSequence contentText;
private Recipient threadRecipient;
private SlideDeck slideDeck;
private CharSequence contentTitle;
private CharSequence contentText;
private Recipient threadRecipient;
private BubbleUtil.BubbleState defaultBubbleState;
public SingleRecipientNotificationBuilder(@NonNull Context context, @NonNull NotificationPrivacyPreference privacy)
{
@@ -229,7 +233,8 @@ public class SingleRecipientNotificationBuilder extends AbstractNotificationBuil
public void addMessageBody(@NonNull Recipient threadRecipient,
@NonNull Recipient individualRecipient,
@Nullable CharSequence messageBody,
long timestamp)
long timestamp,
@Nullable SlideDeck slideDeck)
{
SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
Person.Builder personBuilder = new Person.Builder()
@@ -257,7 +262,21 @@ public class SingleRecipientNotificationBuilder extends AbstractNotificationBuil
text = stringBuilder.append(context.getString(R.string.SingleRecipientNotificationBuilder_new_message));
}
messages.add(new NotificationCompat.MessagingStyle.Message(text, timestamp, personBuilder.build()));
Uri dataUri = null;
String mimeType = null;
if (slideDeck != null && slideDeck.getThumbnailSlide() != null) {
Slide thumbnail = slideDeck.getThumbnailSlide();
dataUri = thumbnail.getUri();
mimeType = thumbnail.getContentType();
}
messages.add(new NotificationCompat.MessagingStyle.Message(text, timestamp, personBuilder.build()).setData(mimeType, dataUri));
}
public void setDefaultBubbleState(@NonNull BubbleUtil.BubbleState bubbleState) {
this.defaultBubbleState = bubbleState;
}
@Override
@@ -270,13 +289,17 @@ public class SingleRecipientNotificationBuilder extends AbstractNotificationBuil
setLargeIcon(getNotificationPicture(largeIconUri.get(), LARGE_ICON_DIMEN));
}
if (messages.size() == 1 && bigPictureUri.isPresent()) {
if (messages.size() == 1 && bigPictureUri.isPresent() && Build.VERSION.SDK_INT < ConversationUtil.CONVERSATION_SUPPORT_VERSION) {
setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(getNotificationPicture(bigPictureUri.get(), BIG_PICTURE_DIMEN))
.setSummaryText(getBigText()));
} else {
if (Build.VERSION.SDK_INT >= 24) {
applyMessageStyle();
if (Build.VERSION.SDK_INT >= ConversationUtil.CONVERSATION_SUPPORT_VERSION) {
applyBubbleMetadata();
}
} else {
applyLegacy();
}
@@ -304,6 +327,19 @@ public class SingleRecipientNotificationBuilder extends AbstractNotificationBuil
setStyle(messagingStyle);
}
private void applyBubbleMetadata() {
long threadId = DatabaseFactory.getThreadDatabase(context).getThreadIdFor(threadRecipient);
PendingIntent intent = PendingIntent.getActivity(context, 0, ConversationIntents.createBubbleIntent(context, threadRecipient.getId(), threadId), 0);
NotificationCompat.BubbleMetadata bubbleMetadata = new NotificationCompat.BubbleMetadata.Builder()
.setAutoExpandBubble(defaultBubbleState == BubbleUtil.BubbleState.SHOWN)
.setDesiredHeight(600)
.setIcon(AvatarUtil.getIconCompatForShortcut(context, threadRecipient))
.setSuppressNotification(defaultBubbleState == BubbleUtil.BubbleState.SHOWN)
.setIntent(intent)
.build();
setBubbleMetadata(bubbleMetadata);
}
private void applyLegacy() {
setStyle(new NotificationCompat.BigTextStyle().bigText(getBigText()));
}