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