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			} else {
234				mBuilder.setVibrate(new long[]{0});
235			}
236			if (ringtone != null) {
237				mBuilder.setSound(Uri.parse(ringtone));
238			}
239		}
240		if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
241			mBuilder.setCategory(Notification.CATEGORY_MESSAGE);
242		}
243		setNotificationColor(mBuilder);
244		mBuilder.setDefaults(0);
245		if (led) {
246			mBuilder.setLights(0xff00FF00, 2000, 3000);
247		}
248	}
249
250	private Builder buildMultipleConversation() {
251		final Builder mBuilder = new NotificationCompat.Builder(
252				mXmppConnectionService);
253		final NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
254		style.setBigContentTitle(notifications.size()
255				+ " "
256				+ mXmppConnectionService
257				.getString(R.string.unread_conversations));
258		final StringBuilder names = new StringBuilder();
259		Conversation conversation = null;
260		for (final ArrayList<Message> messages : notifications.values()) {
261			if (messages.size() > 0) {
262				conversation = messages.get(0).getConversation();
263				final String name = conversation.getName();
264				if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
265					int count = messages.size();
266					style.addLine(Html.fromHtml("<b>"+name+"</b>: "+mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count)));
267				} else {
268					style.addLine(Html.fromHtml("<b>" + name + "</b>: "
269							+ UIHelper.getMessagePreview(mXmppConnectionService, messages.get(0)).first));
270				}
271				names.append(name);
272				names.append(", ");
273			}
274		}
275		if (names.length() >= 2) {
276			names.delete(names.length() - 2, names.length());
277		}
278		mBuilder.setContentTitle(notifications.size()
279				+ " "
280				+ mXmppConnectionService
281				.getString(R.string.unread_conversations));
282		mBuilder.setContentText(names.toString());
283		mBuilder.setStyle(style);
284		if (conversation != null) {
285			mBuilder.setContentIntent(createContentIntent(conversation));
286		}
287		mBuilder.setGroupSummary(true);
288		mBuilder.setGroup(CONVERSATIONS_GROUP);
289		mBuilder.setDeleteIntent(createDeleteIntent(null));
290		mBuilder.setSmallIcon(R.drawable.ic_notification);
291		return mBuilder;
292	}
293
294	private Builder buildSingleConversations(final ArrayList<Message> messages) {
295		final Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
296		if (messages.size() >= 1) {
297			final Conversation conversation = messages.get(0).getConversation();
298			mBuilder.setLargeIcon(mXmppConnectionService.getAvatarService()
299					.get(conversation, getPixel(64)));
300			mBuilder.setContentTitle(conversation.getName());
301			if (Config.HIDE_MESSAGE_TEXT_IN_NOTIFICATION) {
302				int count = messages.size();
303				mBuilder.setContentText(mXmppConnectionService.getResources().getQuantityString(R.plurals.x_messages,count,count));
304			} else {
305				Message message;
306				if ((message = getImage(messages)) != null) {
307					modifyForImage(mBuilder, message, messages);
308				} else {
309					modifyForTextOnly(mBuilder, messages);
310				}
311				RemoteInput remoteInput = new RemoteInput.Builder("text_reply").setLabel(UIHelper.getMessageHint(mXmppConnectionService, conversation)).build();
312				NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, false)).addRemoteInput(remoteInput).build();
313				NotificationCompat.Action wearReplyAction = new NotificationCompat.Action.Builder(R.drawable.ic_send_text_offline, "Reply", createReplyIntent(conversation, true)).addRemoteInput(remoteInput).build();
314				mBuilder.extend(new NotificationCompat.WearableExtender().addAction(wearReplyAction));
315				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
316					mBuilder.addAction(replyAction);
317				}
318				if ((message = getFirstDownloadableMessage(messages)) != null) {
319					mBuilder.addAction(
320							Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ?
321									R.drawable.ic_file_download_white_24dp : R.drawable.ic_action_download,
322							mXmppConnectionService.getResources().getString(R.string.download_x_file,
323									UIHelper.getFileDescriptionString(mXmppConnectionService, message)),
324							createDownloadIntent(message)
325					);
326				}
327				if ((message = getFirstLocationMessage(messages)) != null) {
328					mBuilder.addAction(R.drawable.ic_room_white_24dp,
329							mXmppConnectionService.getString(R.string.show_location),
330							createShowLocationIntent(message));
331				}
332			}
333			if (conversation.getMode() == Conversation.MODE_SINGLE) {
334				Contact contact = conversation.getContact();
335				Uri systemAccount = contact.getSystemAccount();
336				if (systemAccount != null) {
337					mBuilder.addPerson(systemAccount.toString());
338				}
339			}
340			mBuilder.setWhen(conversation.getLatestMessage().getTimeSent());
341			mBuilder.setSmallIcon(R.drawable.ic_notification);
342			mBuilder.setDeleteIntent(createDeleteIntent(conversation));
343			mBuilder.setContentIntent(createContentIntent(conversation));
344		}
345		return mBuilder;
346	}
347
348	private void modifyForImage(final Builder builder, final Message message,
349								final ArrayList<Message> messages) {
350		try {
351			final Bitmap bitmap = mXmppConnectionService.getFileBackend()
352					.getThumbnail(message, getPixel(288), false);
353			final ArrayList<Message> tmp = new ArrayList<>();
354			for (final Message msg : messages) {
355				if (msg.getType() == Message.TYPE_TEXT
356						&& msg.getTransferable() == null) {
357					tmp.add(msg);
358				}
359			}
360			final BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
361			bigPictureStyle.bigPicture(bitmap);
362			if (tmp.size() > 0) {
363				CharSequence text = getMergedBodies(tmp);
364				bigPictureStyle.setSummaryText(text);
365				builder.setContentText(text);
366			} else {
367				builder.setContentText(mXmppConnectionService.getString(
368						R.string.received_x_file,
369						UIHelper.getFileDescriptionString(mXmppConnectionService, message)));
370			}
371			builder.setStyle(bigPictureStyle);
372		} catch (final FileNotFoundException e) {
373			modifyForTextOnly(builder, messages);
374		}
375	}
376
377	private void modifyForTextOnly(final Builder builder, final ArrayList<Message> messages) {
378		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
379			NotificationCompat.MessagingStyle messagingStyle = new NotificationCompat.MessagingStyle(mXmppConnectionService.getString(R.string.me));
380			Conversation conversation = messages.get(0).getConversation();
381			if (conversation.getMode() == Conversation.MODE_MULTI) {
382				messagingStyle.setConversationTitle(conversation.getName());
383			}
384			for (Message message : messages) {
385				String sender = message.getStatus() == Message.STATUS_RECEIVED ? UIHelper.getMessageDisplayName(message) : null;
386				messagingStyle.addMessage(UIHelper.getMessagePreview(mXmppConnectionService,message).first, message.getTimeSent(), sender);
387			}
388			builder.setStyle(messagingStyle);
389		} else {
390			builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getMergedBodies(messages)));
391			builder.setContentText(UIHelper.getMessagePreview(mXmppConnectionService, messages.get((messages.size()-1))).first);
392		}
393	}
394
395	private Message getImage(final Iterable<Message> messages) {
396		Message image = null;
397		for (final Message message : messages) {
398			if (message.getStatus() != Message.STATUS_RECEIVED) {
399				return null;
400			}
401			if (message.getType() != Message.TYPE_TEXT
402					&& message.getTransferable() == null
403					&& message.getEncryption() != Message.ENCRYPTION_PGP
404					&& message.getFileParams().height > 0) {
405				image = message;
406			}
407		}
408		return image;
409	}
410
411	private Message getFirstDownloadableMessage(final Iterable<Message> messages) {
412		for (final Message message : messages) {
413			if (message.getTransferable() != null
414					&& (message.getType() == Message.TYPE_FILE
415							|| message.getType() == Message.TYPE_IMAGE
416							|| message.treatAsDownloadable() != Message.Decision.NEVER)) {
417				return message;
418			}
419		}
420		return null;
421	}
422
423	private Message getFirstLocationMessage(final Iterable<Message> messages) {
424		for (final Message message : messages) {
425			if (GeoHelper.isGeoUri(message.getBody())) {
426				return message;
427			}
428		}
429		return null;
430	}
431
432	private CharSequence getMergedBodies(final ArrayList<Message> messages) {
433		final StringBuilder text = new StringBuilder();
434		for (int i = 0; i < messages.size(); ++i) {
435			text.append(UIHelper.getMessagePreview(mXmppConnectionService, messages.get(i)).first);
436			if (i != messages.size() - 1) {
437				text.append("\n");
438			}
439		}
440		return text.toString();
441	}
442
443	private PendingIntent createShowLocationIntent(final Message message) {
444		Iterable<Intent> intents = GeoHelper.createGeoIntentsFromMessage(message);
445		for (Intent intent : intents) {
446			if (intent.resolveActivity(mXmppConnectionService.getPackageManager()) != null) {
447				return PendingIntent.getActivity(mXmppConnectionService, 18, intent, PendingIntent.FLAG_UPDATE_CURRENT);
448			}
449		}
450		return createOpenConversationsIntent();
451	}
452
453	private PendingIntent createContentIntent(final String conversationUuid, final String downloadMessageUuid) {
454		final Intent viewConversationIntent = new Intent(mXmppConnectionService,ConversationActivity.class);
455		viewConversationIntent.setAction(ConversationActivity.ACTION_VIEW_CONVERSATION);
456		viewConversationIntent.putExtra(ConversationActivity.CONVERSATION, conversationUuid);
457		if (downloadMessageUuid != null) {
458			viewConversationIntent.putExtra(ConversationActivity.EXTRA_DOWNLOAD_UUID, downloadMessageUuid);
459			return PendingIntent.getActivity(mXmppConnectionService,
460					conversationUuid.hashCode() % 389782,
461					viewConversationIntent,
462					PendingIntent.FLAG_UPDATE_CURRENT);
463		} else {
464			return PendingIntent.getActivity(mXmppConnectionService,
465					conversationUuid.hashCode() % 936236,
466					viewConversationIntent,
467					PendingIntent.FLAG_UPDATE_CURRENT);
468		}
469	}
470
471	private PendingIntent createDownloadIntent(final Message message) {
472		return createContentIntent(message.getConversationUuid(), message.getUuid());
473	}
474
475	private PendingIntent createContentIntent(final Conversation conversation) {
476		return createContentIntent(conversation.getUuid(), null);
477	}
478
479	private PendingIntent createDeleteIntent(Conversation conversation) {
480		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
481		intent.setAction(XmppConnectionService.ACTION_CLEAR_NOTIFICATION);
482		if (conversation != null) {
483			intent.putExtra("uuid", conversation.getUuid());
484			return PendingIntent.getService(mXmppConnectionService, conversation.getUuid().hashCode() % 247527, intent, 0);
485		}
486		return PendingIntent.getService(mXmppConnectionService, 0, intent, 0);
487	}
488
489	private PendingIntent createReplyIntent(Conversation conversation, boolean dismissAfterReply) {
490		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
491		intent.setAction(XmppConnectionService.ACTION_REPLY_TO_CONVERSATION);
492		intent.putExtra("uuid",conversation.getUuid());
493		intent.putExtra("dismiss_notification",dismissAfterReply);
494		int id =  conversation.getUuid().hashCode() % (dismissAfterReply ? 402359 : 426583);
495		return PendingIntent.getService(mXmppConnectionService, id, intent, 0);
496	}
497
498	private PendingIntent createDisableForeground() {
499		final Intent intent = new Intent(mXmppConnectionService,
500				XmppConnectionService.class);
501		intent.setAction(XmppConnectionService.ACTION_DISABLE_FOREGROUND);
502		return PendingIntent.getService(mXmppConnectionService, 34, intent, 0);
503	}
504
505	private PendingIntent createTryAgainIntent() {
506		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
507		intent.setAction(XmppConnectionService.ACTION_TRY_AGAIN);
508		return PendingIntent.getService(mXmppConnectionService, 45, intent, 0);
509	}
510
511	private PendingIntent createDismissErrorIntent() {
512		final Intent intent = new Intent(mXmppConnectionService, XmppConnectionService.class);
513		intent.setAction(XmppConnectionService.ACTION_DISMISS_ERROR_NOTIFICATIONS);
514		return PendingIntent.getService(mXmppConnectionService, 69, intent, 0);
515	}
516
517	private boolean wasHighlightedOrPrivate(final Message message) {
518		final String nick = message.getConversation().getMucOptions().getActualNick();
519		final Pattern highlight = generateNickHighlightPattern(nick);
520		if (message.getBody() == null || nick == null) {
521			return false;
522		}
523		final Matcher m = highlight.matcher(message.getBody());
524		return (m.find() || message.getType() == Message.TYPE_PRIVATE);
525	}
526
527	public static Pattern generateNickHighlightPattern(final String nick) {
528		// We expect a word boundary, i.e. space or start of string, followed by
529		// the
530		// nick (matched in case-insensitive manner), followed by optional
531		// punctuation (for example "bob: i disagree" or "how are you alice?"),
532		// followed by another word boundary.
533		return Pattern.compile("\\b" + Pattern.quote(nick) + "\\p{Punct}?\\b",
534				Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
535	}
536
537	public void setOpenConversation(final Conversation conversation) {
538		this.mOpenConversation = conversation;
539	}
540
541	public void setIsInForeground(final boolean foreground) {
542		this.mIsInForeground = foreground;
543	}
544
545	private int getPixel(final int dp) {
546		final DisplayMetrics metrics = mXmppConnectionService.getResources()
547				.getDisplayMetrics();
548		return ((int) (dp * metrics.density));
549	}
550
551	private void markLastNotification() {
552		this.mLastNotification = SystemClock.elapsedRealtime();
553	}
554
555	private boolean inMiniGracePeriod(final Account account) {
556		final int miniGrace = account.getStatus() == Account.State.ONLINE ? Config.MINI_GRACE_PERIOD
557				: Config.MINI_GRACE_PERIOD * 2;
558		return SystemClock.elapsedRealtime() < (this.mLastNotification + miniGrace);
559	}
560
561	public Notification createForegroundNotification() {
562		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
563
564		mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.conversations_foreground_service));
565		if (Config.SHOW_CONNECTED_ACCOUNTS) {
566			List<Account> accounts = mXmppConnectionService.getAccounts();
567			int enabled = 0;
568			int connected = 0;
569			for (Account account : accounts) {
570				if (account.isOnlineAndConnected()) {
571					connected++;
572					enabled++;
573				} else if (!account.isOptionSet(Account.OPTION_DISABLED)) {
574					enabled++;
575				}
576			}
577			mBuilder.setContentText(mXmppConnectionService.getString(R.string.connected_accounts, connected, enabled));
578		} else {
579			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_open_conversations));
580		}
581		mBuilder.setContentIntent(createOpenConversationsIntent());
582		mBuilder.setWhen(0);
583		mBuilder.setPriority(Config.SHOW_CONNECTED_ACCOUNTS ? NotificationCompat.PRIORITY_DEFAULT : NotificationCompat.PRIORITY_MIN);
584		mBuilder.setSmallIcon(R.drawable.ic_link_white_24dp);
585		if (Config.SHOW_DISABLE_FOREGROUND) {
586			final int cancelIcon;
587			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
588				mBuilder.setCategory(Notification.CATEGORY_SERVICE);
589				cancelIcon = R.drawable.ic_cancel_white_24dp;
590			} else {
591				cancelIcon = R.drawable.ic_action_cancel;
592			}
593			mBuilder.addAction(cancelIcon,
594					mXmppConnectionService.getString(R.string.disable_foreground_service),
595					createDisableForeground());
596		}
597		return mBuilder.build();
598	}
599
600	private PendingIntent createOpenConversationsIntent() {
601		return PendingIntent.getActivity(mXmppConnectionService, 0, new Intent(mXmppConnectionService, ConversationActivity.class), 0);
602	}
603
604	public void updateErrorNotification() {
605		final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
606		final List<Account> errors = new ArrayList<>();
607		for (final Account account : mXmppConnectionService.getAccounts()) {
608			if (account.hasErrorStatus() && account.showErrorNotification()) {
609				errors.add(account);
610			}
611		}
612		if (mXmppConnectionService.getPreferences().getBoolean(SettingsActivity.KEEP_FOREGROUND_SERVICE, false)) {
613			notificationManager.notify(FOREGROUND_NOTIFICATION_ID, createForegroundNotification());
614		}
615		final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mXmppConnectionService);
616		if (errors.size() == 0) {
617			notificationManager.cancel(ERROR_NOTIFICATION_ID);
618			return;
619		} else if (errors.size() == 1) {
620			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_account));
621			mBuilder.setContentText(errors.get(0).getJid().toBareJid().toString());
622		} else {
623			mBuilder.setContentTitle(mXmppConnectionService.getString(R.string.problem_connecting_to_accounts));
624			mBuilder.setContentText(mXmppConnectionService.getString(R.string.touch_to_fix));
625		}
626		mBuilder.addAction(R.drawable.ic_autorenew_white_24dp,
627				mXmppConnectionService.getString(R.string.try_again),
628				createTryAgainIntent());
629		mBuilder.setDeleteIntent(createDismissErrorIntent());
630		mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
631		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
632			mBuilder.setSmallIcon(R.drawable.ic_warning_white_24dp);
633		} else {
634			mBuilder.setSmallIcon(R.drawable.ic_stat_alert_warning);
635		}
636		mBuilder.setContentIntent(PendingIntent.getActivity(mXmppConnectionService,
637				145,
638				new Intent(mXmppConnectionService,ManageAccountActivity.class),
639				PendingIntent.FLAG_UPDATE_CURRENT));
640		notificationManager.notify(ERROR_NOTIFICATION_ID, mBuilder.build());
641	}
642}