NotificationService.java

   1package eu.siacs.conversations.services;
   2
   3import android.app.Notification;
   4import android.app.NotificationChannel;
   5import android.app.NotificationChannelGroup;
   6import android.app.NotificationManager;
   7import android.app.PendingIntent;
   8import android.content.Context;
   9import android.content.Intent;
  10import android.content.SharedPreferences;
  11import android.content.res.Resources;
  12import android.graphics.Bitmap;
  13import android.graphics.Typeface;
  14import android.graphics.drawable.Icon;
  15import android.media.AudioAttributes;
  16import android.media.RingtoneManager;
  17import android.net.Uri;
  18import android.os.Build;
  19import android.os.SystemClock;
  20import android.preference.PreferenceManager;
  21import android.support.annotation.RequiresApi;
  22import android.support.v4.app.NotificationCompat;
  23import android.support.v4.app.NotificationCompat.BigPictureStyle;
  24import android.support.v4.app.NotificationCompat.Builder;
  25import android.support.v4.app.NotificationManagerCompat;
  26import android.support.v4.app.NotificationCompat.CarExtender.UnreadConversation;
  27import android.support.v4.app.Person;
  28import android.support.v4.app.RemoteInput;
  29import android.support.v4.content.ContextCompat;
  30import android.support.v4.graphics.drawable.IconCompat;
  31import android.text.SpannableString;
  32import android.text.style.StyleSpan;
  33import android.util.DisplayMetrics;
  34import android.util.Log;
  35import android.util.Pair;
  36
  37import java.io.File;
  38import java.io.IOException;
  39import java.util.ArrayList;
  40import java.util.Calendar;
  41import java.util.Collections;
  42import java.util.HashMap;
  43import java.util.Iterator;
  44import java.util.LinkedHashMap;
  45import java.util.List;
  46import java.util.Map;
  47import java.util.concurrent.atomic.AtomicInteger;
  48import java.util.regex.Matcher;
  49import java.util.regex.Pattern;
  50
  51import eu.siacs.conversations.Config;
  52import eu.siacs.conversations.R;
  53import eu.siacs.conversations.entities.Account;
  54import eu.siacs.conversations.entities.Contact;
  55import eu.siacs.conversations.entities.Conversation;
  56import eu.siacs.conversations.entities.Conversational;
  57import eu.siacs.conversations.entities.Message;
  58import eu.siacs.conversations.persistance.FileBackend;
  59import eu.siacs.conversations.ui.ConversationsActivity;
  60import eu.siacs.conversations.ui.EditAccountActivity;
  61import eu.siacs.conversations.ui.TimePreference;
  62import eu.siacs.conversations.utils.AccountUtils;
  63import eu.siacs.conversations.utils.Compatibility;
  64import eu.siacs.conversations.utils.GeoHelper;
  65import eu.siacs.conversations.utils.UIHelper;
  66import eu.siacs.conversations.xmpp.XmppConnection;
  67import rocks.xmpp.addr.Jid;
  68
  69public class NotificationService {
  70
  71    public static final Object CATCHUP_LOCK = new Object();
  72
  73    private static final int LED_COLOR = 0xff00ff00;
  74
  75    private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
  76    private static final int NOTIFICATION_ID_MULTIPLIER = 1024 * 1024;
  77    private static final int NOTIFICATION_ID = 2 * NOTIFICATION_ID_MULTIPLIER;
  78    static final int FOREGROUND_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 4;
  79    private static final int ERROR_NOTIFICATION_ID = NOTIFICATION_ID_MULTIPLIER * 6;
  80    private final XmppConnectionService mXmppConnectionService;
  81    private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
  82    private final HashMap<Conversation, AtomicInteger> mBacklogMessageCounter = new HashMap<>();
  83    private Conversation mOpenConversation;
  84    private boolean mIsInForeground;
  85    private long mLastNotification;
  86
  87    NotificationService(final XmppConnectionService service) {
  88        this.mXmppConnectionService = service;
  89    }
  90
  91    private static boolean displaySnoozeAction(List<Message> messages) {
  92        int numberOfMessagesWithoutReply = 0;
  93        for (Message message : messages) {
  94            if (message.getStatus() == Message.STATUS_RECEIVED) {
  95                ++numberOfMessagesWithoutReply;
  96            } else {
  97                return false;
  98            }
  99        }
 100        return numberOfMessagesWithoutReply >= 3;
 101    }
 102
 103    public static Pattern generateNickHighlightPattern(final String nick) {
 104        return Pattern.compile("(?<=(^|\\s))" + Pattern.quote(nick) + "(?=\\s|$|\\p{Punct})");
 105    }
 106
 107    @RequiresApi(api = Build.VERSION_CODES.O)
 108    void initializeChannels() {
 109        final Context c = mXmppConnectionService;
 110        final NotificationManager notificationManager = c.getSystemService(NotificationManager.class);
 111        if (notificationManager == null) {
 112            return;
 113        }
 114
 115        notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("status", c.getString(R.string.notification_group_status_information)));
 116        notificationManager.createNotificationChannelGroup(new NotificationChannelGroup("chats", c.getString(R.string.notification_group_messages)));
 117        final NotificationChannel foregroundServiceChannel = new NotificationChannel("foreground",
 118                c.getString(R.string.foreground_service_channel_name),
 119                NotificationManager.IMPORTANCE_MIN);
 120        foregroundServiceChannel.setDescription(c.getString(R.string.foreground_service_channel_description));
 121        foregroundServiceChannel.setShowBadge(false);
 122        foregroundServiceChannel.setGroup("status");
 123        notificationManager.createNotificationChannel(foregroundServiceChannel);
 124        final NotificationChannel errorChannel = new NotificationChannel("error",
 125                c.getString(R.string.error_channel_name),
 126                NotificationManager.IMPORTANCE_LOW);
 127        errorChannel.setDescription(c.getString(R.string.error_channel_description));
 128        errorChannel.setShowBadge(false);
 129        errorChannel.setGroup("status");
 130        notificationManager.createNotificationChannel(errorChannel);
 131
 132        final NotificationChannel videoCompressionChannel = new NotificationChannel("compression",
 133                c.getString(R.string.video_compression_channel_name),
 134                NotificationManager.IMPORTANCE_LOW);
 135        videoCompressionChannel.setShowBadge(false);
 136        videoCompressionChannel.setGroup("status");
 137        notificationManager.createNotificationChannel(videoCompressionChannel);
 138
 139        final NotificationChannel exportChannel = new NotificationChannel("export",
 140                c.getString(R.string.export_channel_name),
 141                NotificationManager.IMPORTANCE_LOW);
 142        exportChannel.setShowBadge(false);
 143        exportChannel.setGroup("status");
 144        notificationManager.createNotificationChannel(exportChannel);
 145
 146        final NotificationChannel messagesChannel = new NotificationChannel("messages",
 147                c.getString(R.string.messages_channel_name),
 148                NotificationManager.IMPORTANCE_HIGH);
 149        messagesChannel.setShowBadge(true);
 150        messagesChannel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), new AudioAttributes.Builder()
 151                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
 152                .setUsage(AudioAttributes.USAGE_NOTIFICATION_COMMUNICATION_INSTANT)
 153                .build());
 154        messagesChannel.setLightColor(LED_COLOR);
 155        final int dat = 70;
 156        final long[] pattern = {0, 3 * dat, dat, dat};
 157        messagesChannel.setVibrationPattern(pattern);
 158        messagesChannel.enableVibration(true);
 159        messagesChannel.enableLights(true);
 160        messagesChannel.setGroup("chats");
 161        notificationManager.createNotificationChannel(messagesChannel);
 162        final NotificationChannel silentMessagesChannel = new NotificationChannel("silent_messages",
 163                c.getString(R.string.silent_messages_channel_name),
 164                NotificationManager.IMPORTANCE_LOW);
 165        silentMessagesChannel.setDescription(c.getString(R.string.silent_messages_channel_description));
 166        silentMessagesChannel.setShowBadge(true);
 167        silentMessagesChannel.setLightColor(LED_COLOR);
 168        silentMessagesChannel.enableLights(true);
 169        silentMessagesChannel.setGroup("chats");
 170        notificationManager.createNotificationChannel(silentMessagesChannel);
 171
 172        final NotificationChannel quietHoursChannel = new NotificationChannel("quiet_hours",
 173                c.getString(R.string.title_pref_quiet_hours),
 174                NotificationManager.IMPORTANCE_LOW);
 175        quietHoursChannel.setShowBadge(true);
 176        quietHoursChannel.setLightColor(LED_COLOR);
 177        quietHoursChannel.enableLights(true);
 178        quietHoursChannel.setGroup("chats");
 179        quietHoursChannel.enableVibration(false);
 180        quietHoursChannel.setSound(null, null);
 181
 182        notificationManager.createNotificationChannel(quietHoursChannel);
 183    }
 184
 185    public boolean notify(final Message message) {
 186        final Conversation conversation = (Conversation) message.getConversation();
 187        return message.getStatus() == Message.STATUS_RECEIVED
 188                && !conversation.isMuted()
 189                && (conversation.alwaysNotify() || wasHighlightedOrPrivate(message))
 190                && (!conversation.isWithStranger() || notificationsFromStrangers());
 191    }
 192
 193    private boolean notificationsFromStrangers() {
 194        return mXmppConnectionService.getBooleanPreference("notifications_from_strangers", R.bool.notifications_from_strangers);
 195    }
 196
 197    private boolean isQuietHours() {
 198        if (!mXmppConnectionService.getBooleanPreference("enable_quiet_hours", R.bool.enable_quiet_hours)) {
 199            return false;
 200        }
 201        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
 202        final long startTime = TimePreference.minutesToTimestamp(preferences.getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE));
 203        final long endTime = TimePreference.minutesToTimestamp(preferences.getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE));
 204        final long nowTime = Calendar.getInstance().getTimeInMillis();
 205
 206        if (endTime < startTime) {
 207            return nowTime > startTime || nowTime < endTime;
 208        } else {
 209            return nowTime > startTime && nowTime < endTime;
 210        }
 211    }
 212
 213    public void pushFromBacklog(final Message message) {
 214        if (notify(message)) {
 215            synchronized (notifications) {
 216                getBacklogMessageCounter((Conversation) message.getConversation()).incrementAndGet();
 217                pushToStack(message);
 218            }
 219        }
 220    }
 221
 222    private AtomicInteger getBacklogMessageCounter(Conversation conversation) {
 223        synchronized (mBacklogMessageCounter) {
 224            if (!mBacklogMessageCounter.containsKey(conversation)) {
 225                mBacklogMessageCounter.put(conversation, new AtomicInteger(0));
 226            }
 227            return mBacklogMessageCounter.get(conversation);
 228        }
 229    }
 230
 231    void pushFromDirectReply(final Message message) {
 232        synchronized (notifications) {
 233            pushToStack(message);
 234            updateNotification(false);
 235        }
 236    }
 237
 238    public void finishBacklog(boolean notify, Account account) {
 239        synchronized (notifications) {
 240            mXmppConnectionService.updateUnreadCountBadge();
 241            if (account == null || !notify) {
 242                updateNotification(notify);
 243            } else {
 244                final int count;
 245                final List<String> conversations;
 246                synchronized (this.mBacklogMessageCounter) {
 247                    conversations = getBacklogConversations(account);
 248                    count = getBacklogMessageCount(account);
 249                }
 250                updateNotification(count > 0, conversations);
 251            }
 252        }
 253    }
 254
 255    private List<String> getBacklogConversations(Account account) {
 256        final List<String> conversations = new ArrayList<>();
 257        for (Map.Entry<Conversation, AtomicInteger> entry : mBacklogMessageCounter.entrySet()) {
 258            if (entry.getKey().getAccount() == account) {
 259                conversations.add(entry.getKey().getUuid());
 260            }
 261        }
 262        return conversations;
 263    }
 264
 265    private int getBacklogMessageCount(Account account) {
 266        int count = 0;
 267        for (Iterator<Map.Entry<Conversation, AtomicInteger>> it = mBacklogMessageCounter.entrySet().iterator(); it.hasNext(); ) {
 268            Map.Entry<Conversation, AtomicInteger> entry = it.next();
 269            if (entry.getKey().getAccount() == account) {
 270                count += entry.getValue().get();
 271                it.remove();
 272            }
 273        }
 274        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": backlog message count=" + count);
 275        return count;
 276    }
 277
 278    void finishBacklog(boolean notify) {
 279        finishBacklog(notify, null);
 280    }
 281
 282    private void pushToStack(final Message message) {
 283        final String conversationUuid = message.getConversationUuid();
 284        if (notifications.containsKey(conversationUuid)) {
 285            notifications.get(conversationUuid).add(message);
 286        } else {
 287            final ArrayList<Message> mList = new ArrayList<>();
 288            mList.add(message);
 289            notifications.put(conversationUuid, mList);
 290        }
 291    }
 292
 293    public void push(final Message message) {
 294        synchronized (CATCHUP_LOCK) {
 295            final XmppConnection connection = message.getConversation().getAccount().getXmppConnection();
 296            if (connection != null && connection.isWaitingForSmCatchup()) {
 297                connection.incrementSmCatchupMessageCounter();
 298                pushFromBacklog(message);
 299            } else {
 300                pushNow(message);
 301            }
 302        }
 303    }
 304
 305    private void pushNow(final Message message) {
 306        mXmppConnectionService.updateUnreadCountBadge();
 307        if (!notify(message)) {
 308            Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because turned off");
 309            return;
 310        }
 311        final boolean isScreenOn = mXmppConnectionService.isInteractive();
 312        if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
 313            Log.d(Config.LOGTAG, message.getConversation().getAccount().getJid().asBareJid() + ": suppressing notification because conversation is open");
 314            return;
 315        }
 316        synchronized (notifications) {
 317            pushToStack(message);
 318            final Conversational conversation = message.getConversation();
 319            final Account account = conversation.getAccount();
 320            final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
 321                    && !account.inGracePeriod()
 322                    && !this.inMiniGracePeriod(account);
 323            updateNotification(doNotify, Collections.singletonList(conversation.getUuid()));
 324        }
 325    }
 326
 327    public void clear() {
 328        synchronized (notifications) {
 329            for (ArrayList<Message> messages : notifications.values()) {
 330                markAsReadIfHasDirectReply(messages);
 331            }
 332            notifications.clear();
 333            updateNotification(false);
 334        }
 335    }
 336
 337    public void clear(final Conversation conversation) {
 338        synchronized (this.mBacklogMessageCounter) {
 339            this.mBacklogMessageCounter.remove(conversation);
 340        }
 341        synchronized (notifications) {
 342            markAsReadIfHasDirectReply(conversation);
 343            if (notifications.remove(conversation.getUuid()) != null) {
 344                cancel(conversation.getUuid(), NOTIFICATION_ID);
 345                updateNotification(false, null, true);
 346            }
 347        }
 348    }
 349
 350    private void markAsReadIfHasDirectReply(final Conversation conversation) {
 351        markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
 352    }
 353
 354    private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
 355        if (messages != null && messages.size() > 0) {
 356            Message last = messages.get(messages.size() - 1);
 357            if (last.getStatus() != Message.STATUS_RECEIVED) {
 358                if (mXmppConnectionService.markRead((Conversation) last.getConversation(), false)) {
 359                    mXmppConnectionService.updateConversationUi();
 360                }
 361            }
 362        }
 363    }
 364
 365    private void setNotificationColor(final Builder mBuilder) {
 366        mBuilder.setColor(ContextCompat.getColor(mXmppConnectionService, R.color.green600));
 367    }
 368
 369    public void updateNotification(final boolean notify) {
 370        updateNotification(notify, null, false);
 371    }
 372
 373    private void updateNotification(final boolean notify, final List<String> conversations) {
 374        updateNotification(notify, conversations, false);
 375    }
 376
 377    private void updateNotification(final boolean notify, final List<String> conversations, final boolean summaryOnly) {
 378        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mXmppConnectionService);
 379
 380        final boolean quiteHours = isQuietHours();
 381
 382        final boolean notifyOnlyOneChild = notify && conversations != null && conversations.size() == 1; //if this check is changed to > 0 catchup messages will create one notification per conversation
 383
 384
 385        if (notifications.size() == 0) {
 386            cancel(NOTIFICATION_ID);
 387        } else {
 388            if (notify) {
 389                this.markLastNotification();
 390            }
 391            final Builder mBuilder;
 392            if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
 393                mBuilder = buildSingleConversations(notifications.values().iterator().next(), notify, quiteHours);
 394                modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
 395                notify(NOTIFICATION_ID, mBuilder.build());
 396            } else {
 397                mBuilder = buildMultipleConversation(notify, quiteHours);
 398                if (notifyOnlyOneChild) {
 399                    mBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN);
 400                }
 401                modifyForSoundVibrationAndLight(mBuilder, notify, quiteHours, preferences);
 402                if (!summaryOnly) {
 403                    for (Map.Entry<String, ArrayList<Message>> entry : notifications.entrySet()) {
 404                        String uuid = entry.getKey();
 405                        final boolean notifyThis = notifyOnlyOneChild ? conversations.contains(uuid) : notify;
 406                        Builder singleBuilder = buildSingleConversations(entry.getValue(), notifyThis, quiteHours);
 407                        if (!notifyOnlyOneChild) {
 408                            singleBuilder.setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY);
 409                        }
 410                        modifyForSoundVibrationAndLight(singleBuilder, notifyThis, quiteHours, preferences);
 411                        singleBuilder.setGroup(CONVERSATIONS_GROUP);
 412                        setNotificationColor(singleBuilder);
 413                        notify(entry.getKey(), NOTIFICATION_ID, singleBuilder.build());
 414                    }
 415                }
 416                notify(NOTIFICATION_ID, mBuilder.build());
 417            }
 418        }
 419    }
 420
 421    private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, boolean quietHours, SharedPreferences preferences) {
 422        final Resources resources = mXmppConnectionService.getResources();
 423        final String ringtone = preferences.getString("notification_ringtone", resources.getString(R.string.notification_ringtone));
 424        final boolean vibrate = preferences.getBoolean("vibrate_on_notification", resources.getBoolean(R.bool.vibrate_on_notification));
 425        final boolean led = preferences.getBoolean("led", resources.getBoolean(R.bool.led));
 426        final boolean headsup = preferences.getBoolean("notification_headsup", resources.getBoolean(R.bool.headsup_notifications));
 427        if (notify && !quietHours) {
 428            if (vibrate) {
 429                final int dat = 70;
 430                final long[] pattern = {0, 3 * dat, dat, dat};
 431                mBuilder.setVibrate(pattern);
 432            } else {
 433                mBuilder.setVibrate(new long[]{0});
 434            }
 435            Uri uri = Uri.parse(ringtone);
 436            try {
 437                mBuilder.setSound(fixRingtoneUri(uri));
 438            } catch (SecurityException e) {
 439                Log.d(Config.LOGTAG, "unable to use custom notification sound " + uri.toString());
 440            }
 441        }
 442        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 443            mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
 444        }
 445        mBuilder.setPriority(notify ? (headsup ? NotificationCompat.PRIORITY_HIGH : NotificationCompat.PRIORITY_DEFAULT) : NotificationCompat.PRIORITY_LOW);
 446        setNotificationColor(mBuilder);
 447        mBuilder.setDefaults(0);
 448        if (led) {
 449            mBuilder.setLights(LED_COLOR, 2000, 3000);
 450        }
 451    }
 452
 453    private Uri fixRingtoneUri(Uri uri) {
 454        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && "file".equals(uri.getScheme())) {
 455            return FileBackend.getUriForFile(mXmppConnectionService, new File(uri.getPath()));
 456        } else {
 457            return uri;
 458        }
 459    }
 460
 461    private Builder buildMultipleConversation(final boolean notify, final boolean quietHours) {
 462        final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
 463        final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
 464        style.setBigContentTitle(notifications.size()
 465                + " "
 466                + mXmppConnectionService
 467                .getString(R.string.unread_conversations));
 468        final StringBuilder names = new StringBuilder();
 469        Conversation conversation = null;
 470        for (final ArrayList<Message> messages : notifications.values()) {
 471            if (messages.size() > 0) {
 472                conversation = (Conversation) messages.get(0).getConversation();
 473                final String name = conversation.getName().toString();
 474                SpannableString styledString;
 475                if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
 476                    int count = messages.size();
 477                    styledString = new SpannableString(name + ": " + mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
 478                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 479                    style.addLine(styledString);
 480                } else {
 481                    styledString = new SpannableString(name + ": " + UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first);
 482                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 483                    style.addLine(styledString);
 484                }
 485                names.append(name);
 486                names.append(", ");
 487            }
 488        }
 489        if (names.length() >= 2) {
 490            names.delete(names.length() - 2, names.length());
 491        }
 492        mBuilder.setContentTitle(notifications.size()
 493                + " "
 494                + mXmppConnectionService
 495                .getString(R.string.unread_conversations));
 496        mBuilder.setContentText(names.toString());
 497        mBuilder.setStyle(style);
 498        if (conversation != null) {
 499            mBuilder.setContentIntent(createContentIntent(conversation));
 500        }
 501        mBuilder.setGroupSummary(true);
 502        mBuilder.setGroup(CONVERSATIONS_GROUP);
 503        mBuilder.setDeleteIntent(createDeleteIntent(null));
 504        mBuilder.setSmallIcon(R.drawable.ic_notification);
 505        return mBuilder;
 506    }
 507
 508    private Builder buildSingleConversations(final ArrayList<Message> messages, final boolean notify, final boolean quietHours) {
 509        final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService, quietHours ? "quiet_hours" : (notify ? "messages" : "silent_messages"));
 510        if (messages.size() >= 1) {
 511            final Conversation conversation = (Conversation) messages.get(0).getConversation();
 512            final UnreadConversation.Builder mUnreadBuilder = new UnreadConversation.Builder(conversation.getName().toString());
 513            mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
 514                    .get(conversation, AvatarService.getSystemUiAvatarSize(mXmppConnectionService)));
 515            mBuilder.setContentTitle(conversation.getName());
 516            if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
 517                int count = messages.size();
 518                mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
 519            } else {
 520                Message message;
 521                //TODO starting with Android 9 we might want to put images in MessageStyle
 522                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P && (message = getImage(messages)) != null) {
 523                    modifyForImage(mBuilder, mUnreadBuilder, message, messages);
 524                } else {
 525                    modifyForTextOnly(mBuilder, mUnreadBuilder, messages);
 526                }
 527                RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
 528                PendingIntent markAsReadPendingIntent = createReadPendingIntent(conversation);
 529                NotificationCompat.Action markReadAction = new NotificationCompat.Action.Builder(
 530                        R.drawable.ic_drafts_white_24dp,
 531                        mXmppConnectionService.getString(R.string.mark_as_read),
 532                        markAsReadPendingIntent).build();
 533                String replyLabel = mXmppConnectionService.getString(R.string.reply);
 534                NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(
 535                        R.drawable.ic_send_text_offline,
 536                        replyLabel,
 537                        createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
 538                NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_wear_reply,
 539                        replyLabel,
 540                        createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
 541                mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
 542                mUnreadBuilder.setReplyAction(createReplyIntent(conversation, true), remoteInput);
 543                mUnreadBuilder.setReadPendingIntent(markAsReadPendingIntent);
 544                mBuilder.extend(new NotificationCompat.CarExtender().setUnreadConversation(mUnreadBuilder.build()));
 545                int addedActionsCount = 1;
 546                mBuilder.addAction(markReadAction);
 547                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 548                    mBuilder.addAction(replyAction);
 549                    ++addedActionsCount;
 550                }
 551
 552                if (displaySnoozeAction(messages)) {
 553                    String label = mXmppConnectionService.getString(R.string.snooze);
 554                    PendingIntent pendingSnoozeIntent = createSnoozeIntent(conversation);
 555                    NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
 556                            R.drawable.ic_notifications_paused_white_24dp,
 557                            label,
 558                            pendingSnoozeIntent).build();
 559                    mBuilder.addAction(snoozeAction);
 560                    ++addedActionsCount;
 561                }
 562                if (addedActionsCount < 3) {
 563                    final Message firstLocationMessage = getFirstLocationMessage(messages);
 564                    if (firstLocationMessage != null) {
 565                        String label = mXmppConnectionService.getResources().getString(R.string.show_location);
 566                        PendingIntent pendingShowLocationIntent = createShowLocationIntent(firstLocationMessage);
 567                        NotificationCompat.Action locationAction = new NotificationCompat.Action.Builder(
 568                                R.drawable.ic_room_white_24dp,
 569                                label,
 570                                pendingShowLocationIntent).build();
 571                        mBuilder.addAction(locationAction);
 572                        ++addedActionsCount;
 573                    }
 574                }
 575                if (addedActionsCount < 3) {
 576                    Message firstDownloadableMessage = getFirstDownloadableMessage(messages);
 577                    if (firstDownloadableMessage != null) {
 578                        String label = mXmppConnectionService.getResources().getString(R.string.download_x_file, UIHelper.getFileDescriptionString(mXmppConnectionService, firstDownloadableMessage));
 579                        PendingIntent pendingDownloadIntent = createDownloadIntent(firstDownloadableMessage);
 580                        NotificationCompat.Action downloadAction = new NotificationCompat.Action.Builder(
 581                                R.drawable.ic_file_download_white_24dp,
 582                                label,
 583                                pendingDownloadIntent).build();
 584                        mBuilder.addAction(downloadAction);
 585                        ++addedActionsCount;
 586                    }
 587                }
 588            }
 589            if (conversation.getMode() == Conversation.MODE_SINGLE) {
 590                Contact contact = conversation.getContact();
 591                Uri systemAccount = contact.getSystemAccount();
 592                if (systemAccount != null) {
 593                    mBuilder.addPerson(systemAccount.toString());
 594                }
 595            }
 596            mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
 597            mBuilder.setSmallIcon(R.drawable.ic_notification);
 598            mBuilder.setDeleteIntent(createDeleteIntent(conversation));
 599            mBuilder.setContentIntent(createContentIntent(conversation));
 600        }
 601        return mBuilder;
 602    }
 603
 604    private void modifyForImage(final Builder builder, final UnreadConversation.Builder uBuilder,
 605                                final Message message, final ArrayList<Message> messages) {
 606        try {
 607            final Bitmap bitmap = mXmppConnectionService.getFileBackend().getThumbnail(message, getPixel(288), false);
 608            final ArrayList<Message> tmp = new ArrayList<>();
 609            for (final Message msg : messages) {
 610                if (msg.getType() == Message.TYPE_TEXT
 611                        && msg.getTransferable() == null) {
 612                    tmp.add(msg);
 613                }
 614            }
 615            final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
 616            bigPictureStyle.bigPicture(bitmap);
 617            if (tmp.size() > 0) {
 618                CharSequence text = getMergedBodies(tmp);
 619                bigPictureStyle.setSummaryText(text);
 620                builder.setContentText(text);
 621            } else {
 622                builder.setContentText(UIHelper.getFileDescriptionString(mXmppConnectionService, message));
 623            }
 624            builder.setStyle(bigPictureStyle);
 625        } catch (final IOException e) {
 626            modifyForTextOnly(builder, uBuilder, messages);
 627        }
 628    }
 629
 630    private Person getPerson(Message message) {
 631        final Contact contact = message.getContact();
 632        final Person.Builder builder = new Person.Builder();
 633        if (contact != null) {
 634            builder.setName(contact.getDisplayName());
 635            final Uri uri = contact.getSystemAccount();
 636            if (uri != null) {
 637                builder.setUri(uri.toString());
 638            }
 639        } else {
 640            builder.setName(UIHelper.getMessageDisplayName(message));
 641        }
 642        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
 643            builder.setIcon(IconCompat.createWithBitmap(mXmppConnectionService.getAvatarService().get(message, AvatarService.getSystemUiAvatarSize(mXmppConnectionService), false)));
 644        }
 645        return builder.build();
 646    }
 647
 648    private void modifyForTextOnly(final Builder builder, final UnreadConversation.Builder uBuilder, final ArrayList<Message> messages) {
 649        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 650            final Person me = new Person.Builder().setName(mXmppConnectionService.getString(R.string.me)).build();
 651            NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(me);
 652            final Conversation conversation = (Conversation) messages.get(0).getConversation();
 653            final boolean multiple = conversation.getMode() == Conversation.MODE_MULTI;
 654            if (multiple) {
 655                messagingStyle.setConversationTitle(conversation.getName());
 656            }
 657            for (Message message : messages) {
 658                final Person sender = message.getStatus() == Message.STATUS_RECEIVED ? getPerson(message) : null;
 659                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && isImageMessage(message)) {
 660                    final Uri dataUri = FileBackend.getMediaUri(mXmppConnectionService,mXmppConnectionService.getFileBackend().getFile(message));
 661                    NotificationCompat.MessagingStyle.Message imageMessage = new NotificationCompat.MessagingStyle.Message(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
 662                    if (dataUri != null) {
 663                        imageMessage.setData(message.getMimeType(), dataUri);
 664                    }
 665                    messagingStyle.addMessage(imageMessage);
 666                } else {
 667                    messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService, message).first, message.getTimeSent(), sender);
 668                }
 669            }
 670            messagingStyle.setGroupConversation(multiple);
 671            builder.setStyle(messagingStyle);
 672        } else {
 673            if (messages.get(0).getConversation().getMode() == Conversation.MODE_SINGLE) {
 674                builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
 675                builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(messages.size()-1)).first);
 676                builder.setNumber(messages.size());
 677            } else {
 678                final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
 679                SpannableString styledString;
 680                for (Message message : messages) {
 681                    final String name = UIHelper.getMessageDisplayName(message);
 682                    styledString = new SpannableString(name + ": " + message.getBody());
 683                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 684                    style.addLine(styledString);
 685                }
 686                builder.setStyle(style);
 687                int count = messages.size();
 688                if (count == 1) {
 689                    final String name = UIHelper.getMessageDisplayName(messages.get(0));
 690                    styledString = new SpannableString(name + ": " + messages.get(0).getBody());
 691                    styledString.setSpan(new StyleSpan(Typeface.BOLD), 0, name.length(), 0);
 692                    builder.setContentText(styledString);
 693                } else {
 694                    builder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages, count, count));
 695                }
 696            }
 697        }
 698        /** message preview for Android Auto **/
 699        for (Message message : messages) {
 700            Pair<CharSequence, Boolean> preview = UIHelper.getMessagePreview(mXmppConnectionService, message);
 701            // only show user written text
 702            if (!preview.second) {
 703                uBuilder.addMessage(preview.first.toString());
 704                uBuilder.setLatestTimestamp(message.getTimeSent());
 705            }
 706        }
 707    }
 708
 709    private Message getImage(final Iterable<Message> messages) {
 710        Message image = null;
 711        for (final Message message : messages) {
 712            if (message.getStatus() != Message.STATUS_RECEIVED) {
 713                return null;
 714            }
 715            if (isImageMessage(message)) {
 716                image = message;
 717            }
 718        }
 719        return image;
 720    }
 721
 722    private static boolean isImageMessage(Message message) {
 723        return message.getType() != Message.TYPE_TEXT
 724                && message.getTransferable() == null
 725                && message.getEncryption() != Message.ENCRYPTION_PGP
 726                && message.getFileParams().height > 0;
 727    }
 728
 729    private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
 730        for (final Message message : messages) {
 731            if (message.getTransferable() != null || (message.getType() == Message.TYPE_TEXT && message.treatAsDownloadable())) {
 732                return message;
 733            }
 734        }
 735        return null;
 736    }
 737
 738    private Message getFirstLocationMessage(final Iterable<Message> messages) {
 739        for (final Message message : messages) {
 740            if (message.isGeoUri()) {
 741                return message;
 742            }
 743        }
 744        return null;
 745    }
 746
 747    private CharSequence getMergedBodies(final ArrayList<Message> messages) {
 748        final StringBuilder text = new StringBuilder();
 749        for (Message message : messages) {
 750            if (text.length() != 0) {
 751                text.append("\n");
 752            }
 753            text.append(UIHelper.getMessagePreview(mXmppConnectionService, message).first);
 754        }
 755        return text.toString();
 756    }
 757
 758    private PendingIntent createShowLocationIntent(final Message message) {
 759        Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(mXmppConnectionService, message);
 760        for (Intent intent : intents) {
 761            if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
 762                return PendingIntent.getActivity(mXmppConnectionService, generateRequestCode(message.getConversation(), 18), intent, PendingIntent.FLAG_UPDATE_CURRENT);
 763            }
 764        }
 765        return createOpenConversationsIntent();
 766    }
 767
 768    private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
 769        final Intent viewConversationIntent = new Intent(mXmppConnectionService, ConversationsActivity.class);
 770        viewConversationIntent.setAction(ConversationsActivity.ACTION_VIEW_CONVERSATION);
 771        viewConversationIntent.putExtra(ConversationsActivity.EXTRA_CONVERSATION, conversationUuid);
 772        if (downloadMessageUuid != null) {
 773            viewConversationIntent.putExtra(ConversationsActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
 774            return PendingIntent.getActivity(mXmppConnectionService,
 775                    generateRequestCode(conversationUuid, 8),
 776                    viewConversationIntent,
 777                    PendingIntent.FLAG_UPDATE_CURRENT);
 778        } else {
 779            return PendingIntent.getActivity(mXmppConnectionService,
 780                    generateRequestCode(conversationUuid, 10),
 781                    viewConversationIntent,
 782                    PendingIntent.FLAG_UPDATE_CURRENT);
 783        }
 784    }
 785
 786    private int generateRequestCode(String uuid, int actionId) {
 787        return (actionId * NOTIFICATION_ID_MULTIPLIER) + (uuid.hashCode() % NOTIFICATION_ID_MULTIPLIER);
 788    }
 789
 790    private int generateRequestCode(Conversational conversation, int actionId) {
 791        return generateRequestCode(conversation.getUuid(), actionId);
 792    }
 793
 794    private PendingIntent createDownloadIntent(final Message message) {
 795        return createContentIntent(message.getConversationUuid(), message.getUuid());
 796    }
 797
 798    private PendingIntent createContentIntent(final Conversational conversation) {
 799        return createContentIntent(conversation.getUuid(), null);
 800    }
 801
 802    private PendingIntent createDeleteIntent(Conversation conversation) {
 803        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 804        intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
 805        if (conversation != null) {
 806            intent.putExtra("uuid", conversation.getUuid());
 807            return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 20), intent, 0);
 808        }
 809        return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
 810    }
 811
 812    private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
 813        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 814        intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
 815        intent.putExtra("uuid", conversation.getUuid());
 816        intent.putExtra("dismiss_notification", dismissAfterReply);
 817        final int id = generateRequestCode(conversation, dismissAfterReply ? 12 : 14);
 818        return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
 819    }
 820
 821    private PendingIntent createReadPendingIntent(Conversation conversation) {
 822        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 823        intent.setAction(XmppConnectionService.ACTION_MARK_AS_READ);
 824        intent.putExtra("uuid", conversation.getUuid());
 825        intent.setPackage(mXmppConnectionService.getPackageName());
 826        return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 16), intent, PendingIntent.FLAG_UPDATE_CURRENT);
 827    }
 828
 829    private PendingIntent createSnoozeIntent(Conversation conversation) {
 830        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 831        intent.setAction(XmppConnectionService.ACTION_SNOOZE);
 832        intent.putExtra("uuid", conversation.getUuid());
 833        intent.setPackage(mXmppConnectionService.getPackageName());
 834        return PendingIntent.getService(mXmppConnectionService, generateRequestCode(conversation, 22), intent, PendingIntent.FLAG_UPDATE_CURRENT);
 835    }
 836
 837    private PendingIntent createTryAgainIntent() {
 838        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 839        intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
 840        return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
 841    }
 842
 843    private PendingIntent createDismissErrorIntent() {
 844        final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
 845        intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
 846        return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
 847    }
 848
 849    private boolean wasHighlightedOrPrivate(final Message message) {
 850        if (message.getConversation() instanceof Conversation) {
 851            Conversation conversation = (Conversation) message.getConversation();
 852            final String nick = conversation.getMucOptions().getActualNick();
 853            final Pattern highlight = generateNickHighlightPattern(nick);
 854            if (message.getBody() == null || nick == null) {
 855                return false;
 856            }
 857            final Matcher m = highlight.matcher(message.getBody());
 858            return (m.find() || message.getType() == Message.TYPE_PRIVATE);
 859        } else {
 860            return false;
 861        }
 862    }
 863
 864    public void setOpenConversation(final Conversation conversation) {
 865        this.mOpenConversation = conversation;
 866    }
 867
 868    public void setIsInForeground(final boolean foreground) {
 869        this.mIsInForeground = foreground;
 870    }
 871
 872    private int getPixel(final int dp) {
 873        final DisplayMetrics metrics = mXmppConnectionService.getResources()
 874                .getDisplayMetrics();
 875        return ((int) (dp * metrics.density));
 876    }
 877
 878    private void markLastNotification() {
 879        this.mLastNotification = SystemClock.elapsedRealtime();
 880    }
 881
 882    private boolean inMiniGracePeriod(final Account account) {
 883        final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
 884                : Config.MINI_GRACE_PERIOD * 2;
 885        return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
 886    }
 887
 888    Notification createForegroundNotification() {
 889        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
 890        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.app_name));
 891        if (Compatibility.runsAndTargetsTwentySix(mXmppConnectionService) || Config.SHOW_CONNECTED_ACCOUNTS) {
 892            List<Account> accounts = mXmppConnectionService.getAccounts();
 893            int enabled = 0;
 894            int connected = 0;
 895            for (Account account : accounts) {
 896                if (account.isOnlineAndConnected()) {
 897                    connected++;
 898                    enabled++;
 899                } else if (account.isEnabled()) {
 900                    enabled++;
 901                }
 902            }
 903            mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
 904        } else {
 905            mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
 906        }
 907        mBuilder.setContentIntent(createOpenConversationsIntent());
 908        mBuilder.setWhen(0);
 909        mBuilder.setPriority(Notification.PRIORITY_MIN);
 910        mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
 911
 912        if (Compatibility.runsTwentySix()) {
 913            mBuilder.setChannelId("foreground");
 914        }
 915
 916
 917        return mBuilder.build();
 918    }
 919
 920    private PendingIntent createOpenConversationsIntent() {
 921        return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationsActivity.class), 0);
 922    }
 923
 924    void updateErrorNotification() {
 925        if (Config.SUPPRESS_ERROR_NOTIFICATION) {
 926            cancel(ERROR_NOTIFICATION_ID);
 927            return;
 928        }
 929        final boolean showAllErrors = QuickConversationsService.isConversations();
 930        final List<Account> errors = new ArrayList<>();
 931        for (final Account account : mXmppConnectionService.getAccounts()) {
 932            if (account.hasErrorStatus() && account.showErrorNotification() && (showAllErrors || account.getLastErrorStatus() == Account.State.UNAUTHORIZED)) {
 933                errors.add(account);
 934            }
 935        }
 936        if (mXmppConnectionService.foregroundNotificationNeedsUpdatingWhenErrorStateChanges()) {
 937            notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
 938        }
 939        final Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
 940        if (errors.size() == 0) {
 941            cancel(ERROR_NOTIFICATION_ID);
 942            return;
 943        } else if (errors.size() == 1) {
 944            mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
 945            mBuilder.setContentText(errors.get(0).getJid().asBareJid().toString());
 946        } else {
 947            mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
 948            mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
 949        }
 950        mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
 951                mXmppConnectionService.getString(R.string.try_again),
 952                createTryAgainIntent());
 953        mBuilder.setDeleteIntent(createDismissErrorIntent());
 954        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 955            mBuilder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
 956            mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
 957        } else {
 958            mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
 959        }
 960        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
 961            mBuilder.setLocalOnly(true);
 962        }
 963        mBuilder.setPriority(Notification.PRIORITY_LOW);
 964        final Intent intent;
 965        if (AccountUtils.MANAGE_ACCOUNT_ACTIVITY != null) {
 966            intent = new Intent(mXmppConnectionService, AccountUtils.MANAGE_ACCOUNT_ACTIVITY);
 967        } else {
 968            intent = new Intent(mXmppConnectionService, EditAccountActivity.class);
 969            intent.putExtra("jid", errors.get(0).getJid().asBareJid().toEscapedString());
 970            intent.putExtra(EditAccountActivity.EXTRA_OPENED_FROM_NOTIFICATION, true);
 971        }
 972        mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService, 145, intent, PendingIntent.FLAG_UPDATE_CURRENT));
 973        if (Compatibility.runsTwentySix()) {
 974            mBuilder.setChannelId("error");
 975        }
 976        notify(ERROR_NOTIFICATION_ID, mBuilder.build());
 977    }
 978
 979    void updateFileAddingNotification(int current, Message message) {
 980        Notification.Builder mBuilder = new Notification.Builder(mXmppConnectionService);
 981        mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.transcoding_video));
 982        mBuilder.setProgress(100, current, false);
 983        mBuilder.setSmallIcon(R.drawable.ic_hourglass_empty_white_24dp);
 984        mBuilder.setContentIntent(createContentIntent(message.getConversation()));
 985        mBuilder.setOngoing(true);
 986        if (Compatibility.runsTwentySix()) {
 987            mBuilder.setChannelId("compression");
 988        }
 989        Notification notification = mBuilder.build();
 990        notify(FOREGROUND_NOTIFICATION_ID, notification);
 991    }
 992
 993    void dismissForcedForegroundNotification() {
 994        cancel(FOREGROUND_NOTIFICATION_ID);
 995    }
 996
 997    private void notify(String tag, int id, Notification notification) {
 998        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
 999        try {
1000            notificationManager.notify(tag, id, notification);
1001        } catch (RuntimeException e) {
1002            Log.d(Config.LOGTAG, "unable to make notification", e);
1003        }
1004    }
1005
1006    private void notify(int id, Notification notification) {
1007        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1008        try {
1009            notificationManager.notify(id, notification);
1010        } catch (RuntimeException e) {
1011            Log.d(Config.LOGTAG, "unable to make notification", e);
1012        }
1013    }
1014
1015    private void cancel(int id) {
1016        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1017        try {
1018            notificationManager.cancel(id);
1019        } catch (RuntimeException e) {
1020            Log.d(Config.LOGTAG, "unable to cancel notification", e);
1021        }
1022    }
1023
1024    private void cancel(String tag, int id) {
1025        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
1026        try {
1027            notificationManager.cancel(tag, id);
1028        } catch (RuntimeException e) {
1029            Log.d(Config.LOGTAG, "unable to cancel notification", e);
1030        }
1031    }
1032}