NotificationService.java

  1package eu.siacs.conversations.services;
  2
  3import android.app.Notification;
  4import android.app.PendingIntent;
  5import android.content.Intent;
  6import android.content.SharedPreferences;
  7import android.graphics.Bitmap;
  8import android.net.Uri;
  9import android.os.Build;
 10import android.os.SystemClock;
 11import android.support.v4.app.NotificationCompat;
 12import android.support.v4.app.NotificationCompat.BigPictureStyle;
 13import android.support.v4.app.NotificationCompat.Builder;
 14import android.support.v4.app.NotificationManagerCompat;
 15import android.support.v4.app.RemoteInput;
 16import android.text.Html;
 17import android.util.DisplayMetrics;
 18import android.util.Log;
 19
 20import java.io.FileNotFoundException;
 21import java.util.ArrayList;
 22import java.util.Calendar;
 23import java.util.LinkedHashMap;
 24import java.util.List;
 25import java.util.Map;
 26import java.util.regex.Matcher;
 27import java.util.regex.Pattern;
 28
 29import eu.siacs.conversations.Config;
 30import eu.siacs.conversations.R;
 31import eu.siacs.conversations.entities.Account;
 32import eu.siacs.conversations.entities.Contact;
 33import eu.siacs.conversations.entities.Conversation;
 34import eu.siacs.conversations.entities.Message;
 35import eu.siacs.conversations.ui.ConversationActivity;
 36import eu.siacs.conversations.ui.ManageAccountActivity;
 37import eu.siacs.conversations.ui.TimePreference;
 38import eu.siacs.conversations.utils.GeoHelper;
 39import eu.siacs.conversations.utils.UIHelper;
 40
 41public class NotificationService {
 42
 43	private static final String CONVERSATIONS_GROUP = "eu.siacs.conversations";
 44	private final XmppConnectionService mXmppConnectionService;
 45
 46	private final LinkedHashMap<String, ArrayList<Message>> notifications = new LinkedHashMap<>();
 47
 48	public static final int NOTIFICATION_ID = 0x2342;
 49	public static final int FOREGROUND_NOTIFICATION_ID = 0x8899;
 50	public static final int ERROR_NOTIFICATION_ID = 0x5678;
 51
 52	private Conversation mOpenConversation;
 53	private boolean mIsInForeground;
 54	private long mLastNotification;
 55
 56	public NotificationService(final XmppConnectionService service) {
 57		this.mXmppConnectionService = service;
 58	}
 59
 60	public boolean notify(final Message message) {
 61		return (message.getStatus() == Message.STATUS_RECEIVED)
 62				&& notificationsEnabled()
 63				&& !message.getConversation().isMuted()
 64				&& (message.getConversation().alwaysNotify() || wasHighlightedOrPrivate(message)
 65		);
 66	}
 67
 68	public boolean notificationsEnabled() {
 69		return mXmppConnectionService.getPreferences().getBoolean("show_notification", true);
 70	}
 71
 72	public boolean isQuietHours() {
 73		if (!mXmppConnectionService.getPreferences().getBoolean("enable_quiet_hours", false)) {
 74			return false;
 75		}
 76		final long startTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_start", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
 77		final long endTime = mXmppConnectionService.getPreferences().getLong("quiet_hours_end", TimePreference.DEFAULT_VALUE) % Config.MILLISECONDS_IN_DAY;
 78		final long nowTime = Calendar.getInstance().getTimeInMillis() % Config.MILLISECONDS_IN_DAY;
 79
 80		if (endTime < startTime) {
 81			return nowTime > startTime || nowTime < endTime;
 82		} else {
 83			return nowTime > startTime && nowTime < endTime;
 84		}
 85	}
 86
 87	public void pushFromBacklog(final Message message) {
 88		if (notify(message)) {
 89			synchronized (notifications) {
 90				pushToStack(message);
 91			}
 92		}
 93	}
 94
 95	public void pushFromDirectReply(final Message message) {
 96		synchronized (notifications) {
 97			pushToStack(message);
 98			updateNotification(false);
 99		}
100	}
101
102	public void finishBacklog(boolean notify) {
103		synchronized (notifications) {
104			mXmppConnectionService.updateUnreadCountBadge();
105			updateNotification(notify);
106		}
107	}
108
109	private void pushToStack(final Message message) {
110		final String conversationUuid = message.getConversationUuid();
111		if (notifications.containsKey(conversationUuid)) {
112			notifications.get(conversationUuid).add(message);
113		} else {
114			final ArrayList<Message> mList = new ArrayList<>();
115			mList.add(message);
116			notifications.put(conversationUuid, mList);
117		}
118	}
119
120	public void push(final Message message) {
121		mXmppConnectionService.updateUnreadCountBadge();
122		if (!notify(message)) {
123			Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().toBareJid()+": suppressing notification because turned off");
124			return;
125		}
126		final boolean isScreenOn = mXmppConnectionService.isInteractive();
127		if (this.mIsInForeground && isScreenOn && this.mOpenConversation == message.getConversation()) {
128			Log.d(Config.LOGTAG,message.getConversation().getAccount().getJid().toBareJid()+": suppressing notification because conversation is open");
129			return;
130		}
131		synchronized (notifications) {
132			pushToStack(message);
133			final Account account = message.getConversation().getAccount();
134			final boolean doNotify = (!(this.mIsInForeground && this.mOpenConversation == null) || !isScreenOn)
135					&& !account.inGracePeriod()
136					&& !this.inMiniGracePeriod(account);
137			updateNotification(doNotify);
138		}
139	}
140
141	public void clear() {
142		synchronized (notifications) {
143			for(ArrayList<Message> messages : notifications.values()) {
144				markAsReadIfHasDirectReply(messages);
145			}
146			notifications.clear();
147			updateNotification(false);
148		}
149	}
150
151	public void clear(final Conversation conversation) {
152		synchronized (notifications) {
153			markAsReadIfHasDirectReply(conversation);
154			notifications.remove(conversation.getUuid());
155			final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
156			notificationManager.cancel(conversation.getUuid(), NOTIFICATION_ID);
157			updateNotification(false);
158		}
159	}
160
161	private void markAsReadIfHasDirectReply(final Conversation conversation) {
162		markAsReadIfHasDirectReply(notifications.get(conversation.getUuid()));
163	}
164
165	private void markAsReadIfHasDirectReply(final ArrayList<Message> messages) {
166		if (messages != null && messages.size() > 0) {
167			Message last = messages.get(messages.size() - 1);
168			if (last.getStatus() != Message.STATUS_RECEIVED) {
169				mXmppConnectionService.markRead(last.getConversation(), false);
170			}
171		}
172	}
173
174	private void setNotificationColor(final Builder mBuilder) {
175		mBuilder.setColor(mXmppConnectionService.getResources().getColor(R.color.primary500));
176	}
177
178	public void updateNotification(final boolean notify) {
179		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
180		final SharedPreferences preferences = mXmppConnectionService.getPreferences();
181
182		if (notifications.size() == 0) {
183			notificationManager.cancel(NOTIFICATION_ID);
184		} else {
185			if (notify) {
186				this.markLastNotification();
187			}
188			final Builder mBuilder;
189			if (notifications.size() == 1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
190				mBuilder = buildSingleConversations(notifications.values().iterator().next());
191				modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
192				notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
193			} else {
194				mBuilder = buildMultipleConversation();
195				modifyForSoundVibrationAndLight(mBuilder, notify, preferences);
196				notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
197				for(Map.Entry<String,ArrayList<Message>> entry : notifications.entrySet()) {
198					Builder singleBuilder = buildSingleConversations(entry.getValue());
199					singleBuilder.setGroup(CONVERSATIONS_GROUP);
200					modifyForSoundVibrationAndLight(singleBuilder,notify,preferences);
201					notificationManager.notify(entry.getKey(), NOTIFICATION_ID ,singleBuilder.build());
202				}
203			}
204		}
205	}
206
207
208	private void modifyForSoundVibrationAndLight(Builder mBuilder, boolean notify, SharedPreferences preferences) {
209		final String ringtone = preferences.getString("notification_ringtone", null);
210		final boolean vibrate = preferences.getBoolean("vibrate_on_notification", true);
211		final boolean led = preferences.getBoolean("led", true);
212		if (notify && !isQuietHours()) {
213			if (vibrate) {
214				final int dat = 70;
215				final long[] pattern = {0, 3 * dat, dat, dat};
216				mBuilder.setVibrate(pattern);
217			}
218			if (ringtone != null) {
219				mBuilder.setSound(Uri.parse(ringtone));
220			}
221		}
222		if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
223			mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
224		}
225		setNotificationColor(mBuilder);
226		mBuilder.setDefaults(0);
227		if (led) {
228			mBuilder.setLights(0xff00FF00, 2000, 3000);
229		}
230	}
231
232	private Builder buildMultipleConversation() {
233		final Builder mBuilder = new NotificationCompat.Builder(
234				mXmppConnectionService);
235		final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
236		style.setBigContentTitle(notifications.size()
237				+ " "
238				+ mXmppConnectionService
239				.getString(R.string.unread_conversations));
240		final StringBuilder names = new StringBuilder();
241		Conversation conversation = null;
242		for (final ArrayList<Message> messages : notifications.values()) {
243			if (messages.size() > 0) {
244				conversation = messages.get(0).getConversation();
245				final String name = conversation.getName();
246				if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
247					int count = messages.size();
248					style.addLine(Html.fromHtml("<b>"+name+"</b>: "+mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count)));
249				} else {
250					style.addLine(Html.fromHtml("<b>" + name + "</b>: "
251							+ UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first));
252				}
253				names.append(name);
254				names.append(", ");
255			}
256		}
257		if (names.length() >= 2) {
258			names.delete(names.length() - 2, names.length());
259		}
260		mBuilder.setContentTitle(notifications.size()
261				+ " "
262				+ mXmppConnectionService
263				.getString(R.string.unread_conversations));
264		mBuilder.setContentText(names.toString());
265		mBuilder.setStyle(style);
266		if (conversation != null) {
267			mBuilder.setContentIntent(createContentIntent(conversation));
268		}
269		mBuilder.setGroupSummary(true);
270		mBuilder.setGroup(CONVERSATIONS_GROUP);
271		mBuilder.setDeleteIntent(createDeleteIntent(null));
272		mBuilder.setSmallIcon(R.drawable.ic_notification);
273		return mBuilder;
274	}
275
276	private Builder buildSingleConversations(final ArrayList<Message> messages) {
277		final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
278		if (messages.size() >= 1) {
279			final Conversation conversation = messages.get(0).getConversation();
280			mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
281					.get(conversation, getPixel(64)));
282			mBuilder.setContentTitle(conversation.getName());
283			if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
284				int count = messages.size();
285				mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
286			} else {
287				Message message;
288				if ((message = getImage(messages)) != null) {
289					modifyForImage(mBuilder, message, messages);
290				} else {
291					modifyForTextOnly(mBuilder, messages);
292				}
293				RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
294				NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
295				NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
296				mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
297				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
298					mBuilder.addAction(replyAction);
299				}
300				if ((message = getFirstDownloadableMessage(messages)) != null) {
301					mBuilder.addAction(
302							Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
303									R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download,
304							mXmppConnectionService.getResources().getString(R.string.download_x_file,
305									UIHelper.getFileDescriptionString(mXmppConnectionService, message)),
306							createDownloadIntent(message)
307					);
308				}
309				if ((message = getFirstLocationMessage(messages)) != null) {
310					mBuilder.addAction(R.drawable.ic_room_white_24dp,
311							mXmppConnectionService.getString(R.string.show_location),
312							createShowLocationIntent(message));
313				}
314			}
315			if (conversation.getMode() == Conversation.MODE_SINGLE) {
316				Contact contact = conversation.getContact();
317				Uri systemAccount = contact.getSystemAccount();
318				if (systemAccount != null) {
319					mBuilder.addPerson(systemAccount.toString());
320				}
321			}
322			mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
323			mBuilder.setSmallIcon(R.drawable.ic_notification);
324			mBuilder.setDeleteIntent(createDeleteIntent(conversation));
325			mBuilder.setContentIntent(createContentIntent(conversation));
326		}
327		return mBuilder;
328	}
329
330	private void modifyForImage(final Builder builder, final Message message,
331								final ArrayList<Message> messages) {
332		try {
333			final Bitmap bitmap = mXmppConnectionService.getFileBackend()
334					.getThumbnail(message, getPixel(288), false);
335			final ArrayList<Message> tmp = new ArrayList<>();
336			for (final Message msg : messages) {
337				if (msg.getType() == Message.TYPE_TEXT
338						&& msg.getTransferable() == null) {
339					tmp.add(msg);
340				}
341			}
342			final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
343			bigPictureStyle.bigPicture(bitmap);
344			if (tmp.size() > 0) {
345				CharSequence text = getMergedBodies(tmp);
346				bigPictureStyle.setSummaryText(text);
347				builder.setContentText(text);
348			} else {
349				builder.setContentText(mXmppConnectionService.getString(
350						R.string.received_x_file,
351						UIHelper.getFileDescriptionString(mXmppConnectionService, message)));
352			}
353			builder.setStyle(bigPictureStyle);
354		} catch (final FileNotFoundException e) {
355			modifyForTextOnly(builder, messages);
356		}
357	}
358
359	private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
360		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
361			NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(mXmppConnectionService.getString(R.string.me));
362			Conversation conversation = messages.get(0).getConversation();
363			if (conversation.getMode() == Conversation.MODE_MULTI) {
364				messagingStyle.setConversationTitle(conversation.getName());
365			}
366			for (Message message : messages) {
367				String sender = message.getStatus() == Message.STATUS_RECEIVED ? UIHelper.getMessageDisplayName(message) : null;
368				messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService,message).first, message.getTimeSent(), sender);
369			}
370			builder.setStyle(messagingStyle);
371		} else {
372			builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
373			builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get((messages.size()-1))).first);
374		}
375	}
376
377	private Message getImage(final Iterable<Message> messages) {
378		Message image = null;
379		for (final Message message : messages) {
380			if (message.getStatus() != Message.STATUS_RECEIVED) {
381				return null;
382			}
383			if (message.getType() != Message.TYPE_TEXT
384					&& message.getTransferable() == null
385					&& message.getEncryption() != Message.ENCRYPTION_PGP
386					&& message.getFileParams().height > 0) {
387				image = message;
388			}
389		}
390		return image;
391	}
392
393	private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
394		for (final Message message : messages) {
395			if (message.getTransferable() != null
396					&& (message.getType() == Message.TYPE_FILE
397							|| message.getType() == Message.TYPE_IMAGE
398							|| message.treatAsDownloadable() != Message.Decision.NEVER)) {
399				return message;
400			}
401		}
402		return null;
403	}
404
405	private Message getFirstLocationMessage(final Iterable<Message> messages) {
406		for (final Message message : messages) {
407			if (GeoHelper.isGeoUri(message.getBody())) {
408				return message;
409			}
410		}
411		return null;
412	}
413
414	private CharSequence getMergedBodies(final ArrayList<Message> messages) {
415		final StringBuilder text = new StringBuilder();
416		for (int i = 0; i < messages.size(); ++i) {
417			text.append(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(i)).first);
418			if (i != messages.size() - 1) {
419				text.append("\n");
420			}
421		}
422		return text.toString();
423	}
424
425	private PendingIntent createShowLocationIntent(final Message message) {
426		Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
427		for (Intent intent : intents) {
428			if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
429				return PendingIntent.getActivity(mXmppConnectionService, 18, intent, PendingIntent.FLAG_UPDATE_CURRENT);
430			}
431		}
432		return createOpenConversationsIntent();
433	}
434
435	private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
436		final Intent viewConversationIntent = new Intent(mXmppConnectionService,ConversationActivity.class);
437		viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
438		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
439		if (downloadMessageUuid != null) {
440			viewConversationIntent.putExtra(ConversationActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
441			return PendingIntent.getActivity(mXmppConnectionService,
442					conversationUuid.hashCode() % 389782,
443					viewConversationIntent,
444					PendingIntent.FLAG_UPDATE_CURRENT);
445		} else {
446			return PendingIntent.getActivity(mXmppConnectionService,
447					conversationUuid.hashCode() % 936236,
448					viewConversationIntent,
449					PendingIntent.FLAG_UPDATE_CURRENT);
450		}
451	}
452
453	private PendingIntent createDownloadIntent(final Message message) {
454		return createContentIntent(message.getConversationUuid(), message.getUuid());
455	}
456
457	private PendingIntent createContentIntent(final Conversation conversation) {
458		return createContentIntent(conversation.getUuid(), null);
459	}
460
461	private PendingIntent createDeleteIntent(Conversation conversation) {
462		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
463		intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
464		if (conversation != null) {
465			intent.putExtra("uuid", conversation.getUuid());
466			return PendingIntent.getService(mXmppConnectionService, conversation.getUuid().hashCode() % 247527, intent, 0);
467		}
468		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
469	}
470
471	private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
472		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
473		intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
474		intent.putExtra("uuid",conversation.getUuid());
475		intent.putExtra("dismiss_notification",dismissAfterReply);
476		int id =  conversation.getUuid().hashCode() % (dismissAfterReply ? 402359 : 426583);
477		return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
478	}
479
480	private PendingIntent createDisableForeground() {
481		final Intent intent = new Intent(mXmppConnectionService,
482				XmppConnectionService.class);
483		intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
484		return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
485	}
486
487	private PendingIntent createTryAgainIntent() {
488		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
489		intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
490		return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
491	}
492
493	private PendingIntent createDismissErrorIntent() {
494		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
495		intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
496		return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
497	}
498
499	private boolean wasHighlightedOrPrivate(final Message message) {
500		final String nick = message.getConversation().getMucOptions().getActualNick();
501		final Pattern highlight = generateNickHighlightPattern(nick);
502		if (message.getBody() == null || nick == null) {
503			return false;
504		}
505		final Matcher m = highlight.matcher(message.getBody());
506		return (m.find() || message.getType() == Message.TYPE_PRIVATE);
507	}
508
509	private static Pattern generateNickHighlightPattern(final String nick) {
510		// We expect a word boundary, i.e. space or start of string, followed by
511		// the
512		// nick (matched in case-insensitive manner), followed by optional
513		// punctuation (for example "bob: i disagree" or "how are you alice?"),
514		// followed by another word boundary.
515		return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
516				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
517	}
518
519	public void setOpenConversation(final Conversation conversation) {
520		this.mOpenConversation = conversation;
521	}
522
523	public void setIsInForeground(final boolean foreground) {
524		this.mIsInForeground = foreground;
525	}
526
527	private int getPixel(final int dp) {
528		final DisplayMetrics metrics = mXmppConnectionService.getResources()
529				.getDisplayMetrics();
530		return ((int) (dp * metrics.density));
531	}
532
533	private void markLastNotification() {
534		this.mLastNotification = SystemClock.elapsedRealtime();
535	}
536
537	private boolean inMiniGracePeriod(final Account account) {
538		final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
539				: Config.MINI_GRACE_PERIOD * 2;
540		return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
541	}
542
543	public Notification createForegroundNotification() {
544		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
545
546		mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
547		if (Config.SHOW_CONNECTED_ACCOUNTS) {
548			List<Account> accounts = mXmppConnectionService.getAccounts();
549			int enabled = 0;
550			int connected = 0;
551			for (Account account : accounts) {
552				if (account.isOnlineAndConnected()) {
553					connected++;
554					enabled++;
555				} else if (!account.isOptionSet(Account.OPTION_DISABLED)) {
556					enabled++;
557				}
558			}
559			mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
560		} else {
561			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
562		}
563		mBuilder.setContentIntent(createOpenConversationsIntent());
564		mBuilder.setWhen(0);
565		mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN);
566		mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
567		if (Config.SHOW_DISABLE_FOREGROUND) {
568			final int cancelIcon;
569			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
570				mBuilder.setCategory(Notification.CATEGORY_SERVICE);
571				cancelIcon = R.drawable.ic_cancel_white_24dp;
572			} else {
573				cancelIcon = R.drawable.ic_action_cancel;
574			}
575			mBuilder.addAction(cancelIcon,
576					mXmppConnectionService.getString(R.string.disable_foreground_service),
577					createDisableForeground());
578		}
579		return mBuilder.build();
580	}
581
582	private PendingIntent createOpenConversationsIntent() {
583		return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationActivity.class), 0);
584	}
585
586	public void updateErrorNotification() {
587		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
588		final List<Account> errors = new ArrayList<>();
589		for (final Account account : mXmppConnectionService.getAccounts()) {
590			if (account.hasErrorStatus() && account.showErrorNotification()) {
591				errors.add(account);
592			}
593		}
594		if (mXmppConnectionService.getPreferences().getBoolean("keep_foreground_service", false)) {
595			notificationManager.notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
596		}
597		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
598		if (errors.size() == 0) {
599			notificationManager.cancel(ERROR_NOTIFICATION_ID);
600			return;
601		} else if (errors.size() == 1) {
602			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
603			mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
604		} else {
605			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
606			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
607		}
608		mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
609				mXmppConnectionService.getString(R.string.try_again),
610				createTryAgainIntent());
611		mBuilder.setDeleteIntent(createDismissErrorIntent());
612		mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
613		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
614			mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
615		} else {
616			mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
617		}
618		mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
619				145,
620				new Intent(mXmppConnectionService,ManageAccountActivity.class),
621				PendingIntent.FLAG_UPDATE_CURRENT));
622		notificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
623	}
624}