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