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