From 032cbc25e903e1f2bd064a1919becfc566f83554 Mon Sep 17 00:00:00 2001 From: Valere Date: Tue, 22 Jan 2019 09:20:47 +0100 Subject: [PATCH] Cleaning and refactoring --- CHANGES.rst | 1 + .../fcm/VectorFirebaseMessagingService.kt | 4 +- vector/src/main/AndroidManifest.xml | 2 +- vector/src/main/java/im/vector/Matrix.java | 2 +- .../NotificationDrawerManager.kt | 31 +- .../vector/notifications/NotificationUtils.kt | 14 +- ...er.kt => NotificationBroadcastReceiver.kt} | 32 +- .../vector/services/EventStreamService.java | 383 +----------------- 8 files changed, 62 insertions(+), 407 deletions(-) rename vector/src/main/java/im/vector/receiver/{ReplyNotificationBroadcastReceiver.kt => NotificationBroadcastReceiver.kt} (88%) diff --git a/CHANGES.rst b/CHANGES.rst index 3e2949a2e4..ce1c51d67d 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -41,6 +41,7 @@ Improvements: - Better wording in notification for video call (#1421) - Improve widget banner (#2129) - Icon for Oreo (#2169) + - Notification reliability and Messaging Style. - Notification settings re-organization, added bing rule troubleshoot - Kotlin Code Improvement in VectorSettingsPreferencesFragment.kt - Remove redundant !! , Replace it with null safe operators in VectorSettingsPreferencesFragment.kt diff --git a/vector/src/app/java/im/vector/push/fcm/VectorFirebaseMessagingService.kt b/vector/src/app/java/im/vector/push/fcm/VectorFirebaseMessagingService.kt index d93fee86af..bbb04c7508 100755 --- a/vector/src/app/java/im/vector/push/fcm/VectorFirebaseMessagingService.kt +++ b/vector/src/app/java/im/vector/push/fcm/VectorFirebaseMessagingService.kt @@ -1,7 +1,5 @@ /** - * Copyright 2015 Google Inc. All Rights Reserved. - * Copyright 2017 Vector Creations Ltd - * Copyright 2018 New Vector Ltd + * Copyright 2019 New Vector Ltd * * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/vector/src/main/AndroidManifest.xml b/vector/src/main/AndroidManifest.xml index 93d556f03b..e965c467a7 100755 --- a/vector/src/main/AndroidManifest.xml +++ b/vector/src/main/AndroidManifest.xml @@ -487,7 +487,7 @@ diff --git a/vector/src/main/java/im/vector/Matrix.java b/vector/src/main/java/im/vector/Matrix.java index 12bca7e683..cf71433f01 100755 --- a/vector/src/main/java/im/vector/Matrix.java +++ b/vector/src/main/java/im/vector/Matrix.java @@ -171,7 +171,7 @@ public void onLiveEventsChunkProcessed(String fromToken, String toToken) { mRefreshUnreadCounter = false; Log.d(LOG_TAG, "onLiveEventsChunkProcessed "); - EventStreamService.checkDisplayedNotifications(); + //EventStreamService.checkDisplayedNotifications(); } }; diff --git a/vector/src/main/java/im/vector/notifications/NotificationDrawerManager.kt b/vector/src/main/java/im/vector/notifications/NotificationDrawerManager.kt index cdf37a1451..45fb5fe3b7 100644 --- a/vector/src/main/java/im/vector/notifications/NotificationDrawerManager.kt +++ b/vector/src/main/java/im/vector/notifications/NotificationDrawerManager.kt @@ -61,12 +61,11 @@ class NotificationDrawerManager(val context: Context) { private var currentRoomId: String? = null - /* - * Should be called as soon as a new event is ready to be displayed. - * The notification corresponding to this event will not be displayed until - * #refreshNotificationDrawer() is called. - * Events might be grouped and there might not be one notification per event! - * + /** + Should be called as soon as a new event is ready to be displayed. + The notification corresponding to this event will not be displayed until + #refreshNotificationDrawer() is called. + Events might be grouped and there might not be one notification per event! */ fun onNotifiableEventReceived(notifiableEvent: NotifiableEvent, userId: String, userDisplayName: String?) { //If we support multi session, event list should be per userId @@ -98,8 +97,8 @@ class NotificationDrawerManager(val context: Context) { } } - /* - * Clear all known events and refresh the notification drawer + /** + Clear all known events and refresh the notification drawer */ fun clearAllEvents() { synchronized(this) { @@ -108,9 +107,7 @@ class NotificationDrawerManager(val context: Context) { refreshNotificationDrawer(null) } - /* - * Clear all known message events for this room and refresh the notification drawer - */ + /** Clear all known message events for this room and refresh the notification drawer */ fun clearMessageEventOfRoom(roomId: String?) { if (roomId != null) { eventList.removeAll { e -> @@ -125,8 +122,8 @@ class NotificationDrawerManager(val context: Context) { } /** - * Should be called when the application is currently opened and showing timeline for the given roomId. - * Used to ignore events related to that room (no need to display notification) and clean any existing notification on this room. + Should be called when the application is currently opened and showing timeline for the given roomId. + Used to ignore events related to that room (no need to display notification) and clean any existing notification on this room. */ fun setCurrentRoom(roomId: String?) { var hasChanged = false @@ -173,7 +170,7 @@ class NotificationDrawerManager(val context: Context) { roomIdToEventMap[roomId] = roomEvents } - if (shouldIgnoreMessageEventInRoom(roomId)|| outdatedDetector?.isMessageOutdated(event) == true) { + if (shouldIgnoreMessageEventInRoom(roomId) || outdatedDetector?.isMessageOutdated(event) == true) { //forget this event eventIterator.remove() } else { @@ -233,7 +230,8 @@ class NotificationDrawerManager(val context: Context) { } try { - val summaryLine = context.resources.getQuantityString(R.plurals.notification_compat_summary_line_for_room, events.size, roomName, events.size) + val summaryLine = context.resources.getQuantityString( + R.plurals.notification_compat_summary_line_for_room, events.size, roomName, events.size) summaryInboxStyle.addLine(summaryLine) } catch (e: Throwable) { //String not found or bad format @@ -303,7 +301,8 @@ class NotificationDrawerManager(val context: Context) { // turn the screen on for 3 seconds if (Matrix.getInstance(VectorApp.getInstance())!!.pushManager.isScreenTurnedOn) { val pm = VectorApp.getInstance().getSystemService(Context.POWER_SERVICE) as PowerManager - val wl = pm.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or PowerManager.ACQUIRE_CAUSES_WAKEUP, "riot:manageNotificationSound") + val wl = pm.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or PowerManager.ACQUIRE_CAUSES_WAKEUP, + "riot:manageNotificationSound") wl.acquire(3000) wl.release() } diff --git a/vector/src/main/java/im/vector/notifications/NotificationUtils.kt b/vector/src/main/java/im/vector/notifications/NotificationUtils.kt index 5259f460a1..36f51333c5 100755 --- a/vector/src/main/java/im/vector/notifications/NotificationUtils.kt +++ b/vector/src/main/java/im/vector/notifications/NotificationUtils.kt @@ -42,7 +42,7 @@ import im.vector.activity.JoinRoomActivity import im.vector.activity.LockScreenActivity import im.vector.activity.VectorHomeActivity import im.vector.activity.VectorRoomActivity -import im.vector.receiver.ReplyNotificationBroadcastReceiver +import im.vector.receiver.NotificationBroadcastReceiver import im.vector.ui.themes.ThemeUtils import im.vector.util.PreferencesManager import im.vector.util.startNotificationChannelSettingsIntent @@ -757,7 +757,7 @@ object NotificationUtils { if (!roomInfo.hasSmartReplyError) { buildQuickReplyIntent(context, roomInfo.roomId, senderDisplayNameForReplyCompat)?.let { replyPendingIntent -> var replyLabel: String = context.getString(R.string.action_quick_reply) - var remoteInput: RemoteInput = RemoteInput.Builder(ReplyNotificationBroadcastReceiver.KEY_TEXT_REPLY).run { + var remoteInput: RemoteInput = RemoteInput.Builder(NotificationBroadcastReceiver.KEY_TEXT_REPLY).run { setLabel(replyLabel) build() } @@ -778,8 +778,8 @@ object NotificationUtils { setLargeIcon(largeIcon) } - val intent = Intent(context, ReplyNotificationBroadcastReceiver::class.java) - intent.putExtra(ReplyNotificationBroadcastReceiver.KEY_ROOM_ID, roomInfo.roomId) + val intent = Intent(context, NotificationBroadcastReceiver::class.java) + intent.putExtra(NotificationBroadcastReceiver.KEY_ROOM_ID, roomInfo.roomId) intent.action = DISMISS_ROOM_NOTIF_ACTION val pendingIntent = PendingIntent.getBroadcast(context.applicationContext, System.currentTimeMillis().toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT) @@ -898,9 +898,9 @@ object NotificationUtils { private fun buildQuickReplyIntent(context: Context, roomId: String, senderName: String?): PendingIntent? { val intent: Intent if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - intent = Intent(context, ReplyNotificationBroadcastReceiver::class.java) + intent = Intent(context, NotificationBroadcastReceiver::class.java) intent.action = "${SMART_REPLY_ACTION}_$roomId" - intent.putExtra(ReplyNotificationBroadcastReceiver.KEY_ROOM_ID, roomId) + intent.putExtra(NotificationBroadcastReceiver.KEY_ROOM_ID, roomId) return PendingIntent.getBroadcast(context, System.currentTimeMillis().toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT) } else { @@ -954,7 +954,7 @@ object NotificationUtils { } private fun getDismissSummaryPendingIntent(context: Context): PendingIntent { - val intent = Intent(context, ReplyNotificationBroadcastReceiver::class.java) + val intent = Intent(context, NotificationBroadcastReceiver::class.java) intent.action = DISMISS_SUMMARY_ACTION intent.data = Uri.parse("foobar://deleteSummary") val pendingIntent = PendingIntent.getBroadcast(context.applicationContext, diff --git a/vector/src/main/java/im/vector/receiver/ReplyNotificationBroadcastReceiver.kt b/vector/src/main/java/im/vector/receiver/NotificationBroadcastReceiver.kt similarity index 88% rename from vector/src/main/java/im/vector/receiver/ReplyNotificationBroadcastReceiver.kt rename to vector/src/main/java/im/vector/receiver/NotificationBroadcastReceiver.kt index 8ae25120d1..fe35bc0043 100644 --- a/vector/src/main/java/im/vector/receiver/ReplyNotificationBroadcastReceiver.kt +++ b/vector/src/main/java/im/vector/receiver/NotificationBroadcastReceiver.kt @@ -1,11 +1,14 @@ -/* - * Copyright 2016 OpenMarket Ltd +/** + * Copyright 2019 New Vector Ltd + * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,6 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package im.vector.receiver import android.content.BroadcastReceiver @@ -34,7 +38,7 @@ import org.matrix.androidsdk.rest.model.MatrixError import org.matrix.androidsdk.rest.model.message.Message import org.matrix.androidsdk.util.Log -class ReplyNotificationBroadcastReceiver : BroadcastReceiver() { +class NotificationBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent == null || context == null) return @@ -42,7 +46,7 @@ class ReplyNotificationBroadcastReceiver : BroadcastReceiver() { val action = intent.action if (action != null) { if (action.startsWith(NotificationUtils.SMART_REPLY_ACTION)) { - handleSmartReply(intent,context) + handleSmartReply(intent, context) } else if (action == NotificationUtils.DISMISS_ROOM_NOTIF_ACTION) { intent.getStringExtra(KEY_ROOM_ID)?.let { VectorApp.getInstance().notificationDrawerManager.clearMessageEventOfRoom(it) @@ -86,12 +90,13 @@ class ReplyNotificationBroadcastReceiver : BroadcastReceiver() { false, System.currentTimeMillis(), session.myUser?.displayname - ?: "Me", + ?: "", message, roomId, room.getRoomDisplayName(context)) notifiableMessageEvent.outGoingMessage = true - VectorApp.getInstance().notificationDrawerManager.onNotifiableEventReceived(notifiableMessageEvent, session.myUserId, session.myUser.displayname) + VectorApp.getInstance().notificationDrawerManager.onNotifiableEventReceived( + notifiableMessageEvent, session.myUserId, session.myUser.displayname) VectorApp.getInstance().notificationDrawerManager.refreshNotificationDrawer(null) } @@ -123,14 +128,15 @@ class ReplyNotificationBroadcastReceiver : BroadcastReceiver() { false, System.currentTimeMillis(), session.myUser?.displayname - ?: "Me", + ?: "", message, roomId, room.getRoomDisplayName(context)) notifiableMessageEvent.outGoingMessage = true notifiableMessageEvent.outGoingMessageFailed = true - VectorApp.getInstance().notificationDrawerManager.onNotifiableEventReceived(notifiableMessageEvent, session.myUserId, session.myUser.displayname) + VectorApp.getInstance().notificationDrawerManager.onNotifiableEventReceived( + notifiableMessageEvent, session.myUserId, session.myUser.displayname) VectorApp.getInstance().notificationDrawerManager.refreshNotificationDrawer(null) } }) @@ -148,10 +154,10 @@ class ReplyNotificationBroadcastReceiver : BroadcastReceiver() { } companion object { - val KEY_ROOM_ID = "roomID" - val KEY_TEXT_REPLY = "key_text_reply" - val EXTRA_MATRIX_ID = "EXTRA_MATRIX_ID" + const val KEY_ROOM_ID = "roomID" + const val KEY_TEXT_REPLY = "key_text_reply" + const val EXTRA_MATRIX_ID = "EXTRA_MATRIX_ID" - val LOG_TAG = ReplyNotificationBroadcastReceiver::class.java.name + val LOG_TAG = NotificationBroadcastReceiver::class.java.name } } \ No newline at end of file diff --git a/vector/src/main/java/im/vector/services/EventStreamService.java b/vector/src/main/java/im/vector/services/EventStreamService.java index 99115bafc9..22caf81b3f 100755 --- a/vector/src/main/java/im/vector/services/EventStreamService.java +++ b/vector/src/main/java/im/vector/services/EventStreamService.java @@ -26,7 +26,6 @@ import android.content.Intent; import android.os.Build; import android.os.Handler; -import android.os.HandlerThread; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; @@ -51,10 +50,8 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.HashSet; import java.util.List; import java.util.Random; -import java.util.Set; import im.vector.Matrix; import im.vector.R; @@ -129,11 +126,6 @@ private enum ForegroundNotificationState { */ private static ForegroundNotificationState mForegroundNotificationState = ForegroundNotificationState.NONE; - /** - * Default bing rule - */ - private static final BingRule mDefaultBingRule = new BingRule("ruleKind", "aPattern", true, true, false); - /** * Managed sessions */ @@ -149,20 +141,6 @@ private enum ForegroundNotificationState { */ private StreamAction mServiceState = StreamAction.IDLE; - /** - * store the notifications description - */ -// private final LinkedHashMap mPendingNotifications = new LinkedHashMap<>(); -// private Map> mNotifiedEventsByRoomId = null; - private static HandlerThread mNotificationHandlerThread = null; - private static android.os.Handler mNotificationsHandler = null; - - // get the text to display when the background sync is disabled - private static final List mBackgroundNotificationStrings = new ArrayList<>(); - private static final Set mBackgroundNotificationEventIds = new HashSet<>(); - private static String mLastBackgroundNotificationRoomId = null; - private static int mLastBackgroundNotificationUnreadCount = 0; - /** * call in progress (foreground notification) */ @@ -206,14 +184,7 @@ public static EventStreamService getInstance() { private final BingRulesManager.onBingRulesUpdateListener mBingRulesUpdatesListener = new BingRulesManager.onBingRulesUpdateListener() { @Override public void onBingRulesUpdate() { - getNotificationsHandler().post(new Runnable() { - @Override - public void run() { - Log.d(LOG_TAG, "## on bing rules update"); -// mNotifiedEventsByRoomId = null; -// refreshMessagesNotification(); - } - }); + } }; @@ -467,7 +438,11 @@ private void autoRestart() { Intent restartServiceIntent = new Intent(getApplicationContext(), getClass()); restartServiceIntent.setPackage(getPackageName()); restartServiceIntent.putExtra(EXTRA_AUTO_RESTART_ACTION, EXTRA_AUTO_RESTART_ACTION); - PendingIntent restartPendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT); + PendingIntent restartPendingIntent = PendingIntent.getService( + getApplicationContext(), + 1, + restartServiceIntent, + PendingIntent.FLAG_ONE_SHOT); AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); myAlarmService.set( @@ -577,18 +552,7 @@ private void monitorSession(final MXSession session) { session.getDataHandler().addListener(new MXEventListener() { @Override public void onInitialSyncComplete(String toToken) { - session.getDataHandler().getStore().post(new Runnable() { - @Override - public void run() { - (new Handler(getMainLooper())).post(new Runnable() { - @Override - public void run() { - refreshForegroundNotification(); - } - }); - } - }); - + session.getDataHandler().getStore().post(() -> (new Handler(getMainLooper())).post(() -> refreshForegroundNotification())); } }); @@ -638,13 +602,9 @@ public void onStoreCorrupted(String accountId, String description) { public void onStoreOOM(final String accountId, final String description) { Handler uiHandler = new Handler(getMainLooper()); - uiHandler.post(new Runnable() { - @Override - public void run() { - Toast.makeText(getApplicationContext(), accountId + " : " + description, Toast.LENGTH_LONG).show(); - - Matrix.getInstance(getApplicationContext()).reloadSessions(getApplicationContext()); - } + uiHandler.post(() -> { + Toast.makeText(getApplicationContext(), accountId + " : " + description, Toast.LENGTH_LONG).show(); + Matrix.getInstance(getApplicationContext()).reloadSessions(getApplicationContext()); }); } }); @@ -874,7 +834,8 @@ public void refreshForegroundNotification() { boolean isInitialSyncInProgress = !session.getDataHandler().isInitialSyncComplete() || isStopped() || (mServiceState == StreamAction.CATCHUP); if (isInitialSyncInProgress) { - Log.i(LOG_TAG, "## refreshForegroundNotification : put the service in foreground because of an initial sync " + mForegroundNotificationState); + Log.i(LOG_TAG, + "## refreshForegroundNotification : put the service in foreground because of an initial sync " + mForegroundNotificationState); setForegroundNotificationState(ForegroundNotificationState.INITIAL_SYNCING, null); } else if (shouldDisplayListenForEventsNotification()) { Log.i(LOG_TAG, "## refreshForegroundNotification : put the service in foreground because of FCM registration"); @@ -985,133 +946,6 @@ private void prepareCallNotification(Event event, BingRule bingRule) { } } - /** - * Prepare a notification for the expected event. - * - * @param event the event - * @param bingRule the bing rule - */ -// private void prepareNotification(Event event, BingRule bingRule) { -// -// MXSession session = Matrix.getMXSession(getApplicationContext(), event.getMatrixId()); -// -// // invalid session ? -// // should never happen. -// // But it could be triggered because of multi accounts management. -// // The dedicated account is removing but some pushes are still received. -// if ((null == session) || !session.isAlive()) { -// Log.i(LOG_TAG, "prepareNotification : don't bing - no session"); -// return; -// } -// -// -//// if (mPendingNotifications.containsKey(event.eventId)) { -//// Log.i(LOG_TAG, "prepareNotification : don't bing - the event was already binged"); -//// return; -//// } -// -// if (!mPushManager.areDeviceNotificationsAllowed()) { -// Log.i(LOG_TAG, "prepareNotification : the push has been disable on this device"); -// return; -// } -// -// if (event.isCallEvent()) { -// prepareCallNotification(event, bingRule); -// return; -// } -// -// final String roomId = event.roomId; -// -// // Just don't bing for the room the user's currently in -// if (!VectorApp.isAppInBackground() && (roomId != null) && event.roomId.equals(ViewedRoomTracker.getInstance().getViewedRoomId())) { -// Log.i(LOG_TAG, "prepareNotification : don't bing because it is the currently opened room"); -// return; -// } -// -// // FIXME: Support event contents with no body -// if (!event.getContent().getAsJsonObject().has("body")) { -// // only the membership events are supported -// if (!Event.EVENT_TYPE_STATE_ROOM_MEMBER.equals(event.getType()) && !event.isCallEvent()) { -// Log.i(LOG_TAG, "onBingEvent : don't bing - no body and not a call event"); -// return; -// } -// } -// -// -// -// Room room = session.getDataHandler().getRoom(roomId); -// -// // invalid room ? -// if (null == room) { -// Log.i(LOG_TAG, "prepareNotification : don't bing - the room does not exist"); -// return; -// } -// -// // define a bing rule if it is not provided -// if (null == bingRule) { -// bingRule = mDefaultBingRule; -// } -// -// addPendingEvent(event, bingRule, session); -// } - -// private void addPendingEvent(Event event, BingRule bingRule, MXSession session) { -// Boolean isNoisy = false; -// if (!bingRule.isEnabled || bingRule.shouldNotNotify()) { -// //off -// return; -// } else if (bingRule.getNotificationSound() == null) { -// //silent -// } else { -// //noisy -// isNoisy = true; -// } -// IMXStore store = session.getDataHandler().getStore(); -// Room room = store.getRoom(event.roomId); -// -// // test if the message has not been read -// if ((null != room) /*&& !room.isEventRead(event.roomId)*/) { -// String body = null; -// -// if (null != event) { -// // test if the message is displayable -// EventDisplay eventDisplay = new RiotEventDisplay(getApplicationContext()); -// eventDisplay.setPrependMessagesWithAuthor(false); -// -// CharSequence textualDisplay = eventDisplay.getTextualDisplay(event, room.getState()); -// -// // reported by GA -// if (null != textualDisplay) { -// body = textualDisplay.toString(); -// String roomDisplayName = room.getRoomDisplayName(this); -// Notification notification = NotificationUtils.INSTANCE.buildNotificationForNonCallEvent(this, roomDisplayName, body, isNoisy); -// //Temporary -// -// NotificationManagerCompat.from(this) -// .notify( new Random().nextInt(), notification); -// } -// } -// -// -// } else { -// //nop -// } -// //mPendingNotifications.put(event.eventId, new NotifiedEvent(event.roomId, event.eventId, bingRule, event.getOriginServerTs())); -// } - - /** - * Cancel the push notifications for a dedicated roomId. - * If the roomId is null, cancel all the push notification. - * - * @param accountId the account id - */ - public static void onMessagesNotificationDismiss(String accountId) { - Log.d(LOG_TAG, "onMessagesNotificationDismiss " + accountId); - if (null != mActiveEventStreamService) { - // mActiveEventStreamService.refreshMessagesNotification(); - } - } - /** * Cancel the push notifications for a dedicated roomId. * If the roomId is null, cancel all the push notification. @@ -1122,205 +956,20 @@ public static void onMessagesNotificationDismiss(String accountId) { public static void cancelNotificationsForRoomId(String accountId, String roomId) { Log.d(LOG_TAG, "cancelNotificationsForRoomId " + accountId + " - " + roomId); if (null != mActiveEventStreamService) { - // mActiveEventStreamService.cancelNotifications(roomId); + VectorApp.getInstance().getNotificationDrawerManager().clearMessageEventOfRoom(roomId); } } - /** - * Provide the notifications handler - * - * @return the notifications handler. - */ - private android.os.Handler getNotificationsHandler() { - if (null == mNotificationHandlerThread) { - try { - mNotificationHandlerThread = new HandlerThread("NotificationsService_" + System.currentTimeMillis(), Thread.MIN_PRIORITY); - mNotificationHandlerThread.start(); - } catch (Exception e) { - Log.e(LOG_TAG, "## getNotificationsHandler failed : " + e.getMessage(), e); - } - } - - if (null == mNotificationsHandler) { - try { - mNotificationsHandler = new android.os.Handler(mNotificationHandlerThread.getLooper()); - } catch (Exception e) { - Log.e(LOG_TAG, "## getNotificationsHandler failed : " + e.getMessage(), e); - } - } - - // never returns a null handler - if (null == mNotificationsHandler) { - return new android.os.Handler(getMainLooper()); - } else { - return mNotificationsHandler; - } - } - - /** - * Clear any displayed notification. - */ -// private void clearNotification() { -// NotificationUtils.INSTANCE.cancelAllNotifications(this); -// -// getNotificationsHandler().post(new Runnable() { -// @Override -// public void run() { -// // reset the identifiers -// if (null != mPendingNotifications) { -// mPendingNotifications.clear(); -// } -// -// if (null != mNotifiedEventsByRoomId) { -// mNotifiedEventsByRoomId.clear(); -// } -// -// RoomsNotifications.deleteCachedRoomNotifications(VectorApp.getInstance()); -// } -// }); -// } - /** * Remove any pending notification. * It should be called when the application is logged out. */ public static void removeNotification() { if (null != mActiveEventStreamService) { - //TODO - //mActiveEventStreamService.clearNotification(); + VectorApp.getInstance().getNotificationDrawerManager().clearAllEvents(); } } - /** - * Check if a notification must be cleared because the linked event has been read, deleted ... - */ - public static void checkDisplayedNotifications() { - //TODO -// if (null != mActiveEventStreamService) { -// mActiveEventStreamService.getNotificationsHandler().post(new Runnable() { -// @Override -// public void run() { -// if (mActiveEventStreamService != null) { -// mActiveEventStreamService.refreshMessagesNotification(); -// } -// } -// }); -// } - } - - /** - * Cancel notifications for a dedicated room. - * - * @param roomId the room Id - */ -// private void cancelNotifications(final String roomId) { -// getNotificationsHandler().post(new Runnable() { -// @Override -// public void run() { -// if ((null != mNotifiedEventsByRoomId) && ((null == roomId) || mNotifiedEventsByRoomId.containsKey(roomId))) { -// mNotifiedEventsByRoomId = null; -// refreshMessagesNotification(); -// } -// } -// }); -// } - - /** - * Try to trigger a notification when the event stream is not created. - * - * @param context the context - * @param event the notified event - * @param roomName the room name - * @param senderDisplayName the sender display name - * @param unreadMessagesCount the unread messages count - */ -// @Deprecated -// public static void onStaticNotifiedEvent(Context context, -// @Nullable Event event, -// String roomName, -// String senderDisplayName, -// int unreadMessagesCount) { -// if (null != event && !mBackgroundNotificationEventIds.contains(event.eventId)) { -// mBackgroundNotificationEventIds.add(event.eventId); -// String header = (TextUtils.isEmpty(roomName) ? "" : roomName + ": "); -// String text; -// -// if (null == event.content) { -// // Check whether the room id is available and a room name has been retrieved -// if (null != event.roomId && !TextUtils.isEmpty(header)) { -// // Check whether the previous notification (if any) was from the same room -// if (null != mLastBackgroundNotificationRoomId && mLastBackgroundNotificationRoomId.equals(event.roomId)) { -// // Remove the last notified line to replace it -// mBackgroundNotificationStrings.remove(0); -// } else { -// // Reset the current count -// mLastBackgroundNotificationUnreadCount = 0; -// mLastBackgroundNotificationRoomId = event.roomId; -// } -// mLastBackgroundNotificationUnreadCount++; -// } else { -// // Reset the current notification string, only one notification will be displayed. -// mBackgroundNotificationStrings.clear(); -// // Reset the unread count by considering the size of the event ids array. -// mLastBackgroundNotificationUnreadCount = mBackgroundNotificationEventIds.size(); -// } -// text = context.getResources().getQuantityString(R.plurals.room_new_messages_notification, -// mLastBackgroundNotificationUnreadCount, mLastBackgroundNotificationUnreadCount); -// } else { -// // Add the potential sender name in the header -// String senderName = (TextUtils.isEmpty(senderDisplayName) ? event.sender : senderDisplayName); -// if (!TextUtils.isEmpty(senderName) && !senderName.equalsIgnoreCase(roomName)) { -// header += senderName + " "; -// } -// -// if (event.isEncrypted()) { -// text = context.getString(R.string.encrypted_message); -// } else { -// EventDisplay eventDisplay = new RiotEventDisplay(context); -// eventDisplay.setPrependMessagesWithAuthor(false); -// text = eventDisplay.getTextualDisplay(event, null).toString(); -// } -// } -// -// if (!TextUtils.isEmpty(text)) { -// SpannableString notifiedLine = new SpannableString(header + text); -// notifiedLine.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, header.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); -// -// mBackgroundNotificationStrings.add(0, notifiedLine); -// displayMessagesNotificationStatic(context, mBackgroundNotificationStrings, new BingRule(null, null, true, true, true)); -// } -// } else if (0 == unreadMessagesCount) { -// mBackgroundNotificationStrings.clear(); -// mLastBackgroundNotificationUnreadCount = 0; -// mLastBackgroundNotificationRoomId = null; -// displayMessagesNotificationStatic(context, null, null); -// } -// } - - /** - * Display a list of messages in the messages notification, when the EventStreamService is not started. - * - * @param messages the messages list, null will hide the messages notification. - * @param rule the bing rule to use - */ -// @Deprecated -// private static void displayMessagesNotificationStatic(Context context, List messages, BingRule rule) { -// if (!Matrix.getInstance(context).getPushManager().areDeviceNotificationsAllowed() -// || null == messages -// || messages.isEmpty()) { -// NotificationUtils.INSTANCE.cancelNotificationMessage(context); -// RoomsNotifications.deleteCachedRoomNotifications(VectorApp.getInstance()); -// } else { -// Notification notification = NotificationUtils.INSTANCE.buildMessagesListNotification(context, messages, rule); -// -// if (null != notification) { -// NotificationUtils.INSTANCE.showNotificationMessage(context, notification); -// } else { -// NotificationUtils.INSTANCE.cancelNotificationMessage(context); -// } -// } -// } - //================================================================================ // Call notification management //================================================================================ @@ -1361,7 +1010,9 @@ else if (null == CallsManager.getSharedInstance().getActiveCall()) { if (Matrix.getInstance(VectorApp.getInstance()).getPushManager().isScreenTurnedOn()) { try { PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); - PowerManager.WakeLock wl = pm.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | PowerManager.ACQUIRE_CAUSES_WAKEUP, "riot:MXEventListener"); + PowerManager.WakeLock wl = pm.newWakeLock( + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | PowerManager.ACQUIRE_CAUSES_WAKEUP, + "riot:MXEventListener"); wl.acquire(3000); wl.release(); } catch (RuntimeException re) {