Push Notifications and Widgets
Overview
This doc owns the Android push, local notification, notification settings/action receivers, popup reply UI, and homescreen widget code under:
- TMessagesProj/…/*Push*.java, GcmPushListenerService.java, *Notification*.java, Notifications*.java, PopupReplyReceiver.java, AutoMessage*.java, OpenChatReceiver.java, ShareBroadcastReceiver.java, ScreenReceiver.java, KeepAliveJob.java
- TMessagesProj/…/ChatsWidget*.java, ContactsWidget*.java, FeedWidget*.java
- TMessagesProj/…/PopupNotificationActivity.java, Notifications*.java, ProfileNotificationsActivity.java, *Widget*.java
- TMessagesProj/…/*widget*.xml and TMessagesProj/…/shortcuts.xml
The Android component routing for this area is declared in TMessagesProj/…/AndroidManifest.xml: FCM enters through .GcmPushListenerService, notification actions through the covered receivers, OpenChatReceiver is exported as an activity shim for conversation shortcuts, PopupNotificationActivity is a singleTask popup reply activity, NotificationImageProvider exposes notification media previews, and only the chats/contacts widget providers and services are active. FeedWidgetProvider and FeedWidgetService are covered source files, but their manifest entries are commented out, so feed widgets are not currently reachable from Android.
Push receipt starts in TMessagesProj/…/GcmPushListenerService.java. onMessageReceived logs Firebase data and passes the base64 payload field p, push type PUSH_TYPE_FIREBASE, and sent time into PushListenerController.processRemoteMessage; onNewToken initializes the app on the UI thread and calls PushListenerController.sendRegistrationToServer. TMessagesProj/…/PushListenerController.java stores refreshed push tokens in SharedConfig, updates ConnectionsManager.setRegId, marks every activated UserConfig account as needing push registration, and asks each account MessagesController.registerForPush to upload the token.
PushListenerController.processRemoteMessage is the encrypted-push decoder and lightweight update synthesizer. It initializes the app, runs the work on Utilities.stageQueue, base64-decodes and AES-IGE decrypts the payload using SharedConfig.pushAuthKey, verifies auth-key id and message key, parses JSON, routes the push to the matching account by user_id, and then switches on loc_key. Non-message pushes update local state directly: DC_UPDATE applies a data-center address via ConnectionsManager, MESSAGE_ANNOUNCEMENT creates a TL_updateServiceNotification and sends it through MessagesController.processUpdates, SESSION_REVOKE clears account config and logs out, and GEO_LIVE_PENDING notifies LocationController. Read/delete/reaction pushes build update structures and call MessagesController.processUpdateArray, NotificationsController.removeDeletedMessagesFromNotifications, MessagesController.deleteMessagesByPush, or MessagesController.checkUnreadReactions.
Message pushes are converted into synthetic TL_message objects inside PushListenerController.java. The custom JSON identifies dialogId, topicId, channel/chat/user/encrypted ids, msg_id or random_id, scheduled/silent/mention/edit flags, and channel/supergroup context. The loc_key and loc_args table maps the server localization key to a localized display string using LocaleController; reaction keys are rendered by getReactedText. The synthetic MessageObject is marked as FCM/local channel/reaction as needed, forum pushes populate reply_to.reply_to_top_id, and the result is handed to NotificationsController.getInstance(account).processNewMessages(..., isFcm=true, countDownLatch). PushListenerController waits on that latch before returning to the Firebase service so notification state is updated before the service can be killed.
TMessagesProj/…/NotificationsController.java is the per-account notification state machine. processNewMessages runs on notificationsQueue, filters silent service/topic/imported messages, de-duplicates by message id or FCM random id, persists FCM synthetic messages through MessagesStorage.putPushMessage, suppresses notifications for the open dialog when the screen is on, honors mention overrides, per-dialog/topic notify2_ settings, global private/group/channel settings, and popup settings, then appends to pushMessages, pushMessagesDict, fcmRandomMessagesDict, pushDialogs, and delayedPushMessages. It updates unread/badge counts through setBadge(getTotalAllUnreadCount()) and posts NotificationCenter.pushMessagesUpdated, notificationsCountUpdated, and dialogsUnreadCounterChanged as notifications are added or removed.
Notification construction happens in NotificationsController.showOrUpdateNotification. It skips inactive accounts, empty push queues, hidden non-selected accounts when SharedConfig.showNotificationsForAllAccounts is false, and messages older than dismissDate. It derives the display name and preview text from MessageObject, hides content while the passcode is active, applies smart notifications, in-app suppression, dialog/topic custom settings from NotificationsSettingsFacade, and global sound/vibrate/LED/importance settings. Android O+ notification channels are created or migrated by validateChannelId, ensureGroupsCreated, and related channel helpers; the generated channel ids are stored in notification shared preferences and include account/type/dialog identity. The summary notification uses NotificationDismissReceiver for delete intent and LaunchActivity for the content intent, and showExtraNotifications builds per-dialog MessagingStyle notifications with mark-as-read, reply, bot callback, media preview, wearable bridge, shortcut, and bubble metadata.
Action handling is split across small receivers. NotificationDismissReceiver.java records dismissDate or dismissDate<dialogId> so NotificationsController will ignore older pushes. AutoMessageHeardReceiver.java handles the mark-as-read action by loading missing users/chats from MessagesStorage if necessary, then calling MessagesController.markDialogAsRead and markReactionsAsRead. AutoMessageReplyReceiver.java extracts RemoteInput text under NotificationsController.EXTRA_VOICE_REPLY, sends it with SendMessagesHelper.sendMessage, and marks the dialog read. PopupReplyReceiver.java opens NotificationsController.forceShowPopupForReply, which fills popupReplyMessages and launches PopupNotificationActivity. NotificationCallbackReceiver.java sends bot callback button data via SendMessagesHelper.sendNotificationCallback. OpenChatReceiver.java validates a com.tmessages.openchat... action plus chat/user/encrypted extras before forwarding to LaunchActivity; notification shortcuts and widget rows rely on those same extras. ShareBroadcastReceiver.java only opens an Android share chooser for a data URL.
TMessagesProj/…/PopupNotificationActivity.java displays NotificationsController.popupMessages and popupReplyMessages in a lock-screen-style reply UI. It registers for per-account UI/message/contact events plus global pushMessagesUpdated, creates chat input resources, holds a wake lock, shows avatars/media/audio state, and sends replies through the normal chat input/send path. NotificationsController decides when to start it based on popup preferences, screen state, passcode state, and reply action requests.
Background notification services include NotificationsService.java, NotificationRepeat.java, KeepAliveJob.java, ScreenReceiver.java, and NotificationsDisabledReceiver.java. NotificationsService initializes the app, optionally starts an AyuGram foreground keep-alive notification on Android O+ using channel ayugram_push, returns START_STICKY, and broadcasts org.telegram.start from onDestroy when global pushService remains enabled. NotificationRepeat invokes NotificationsController.repeatNotificationMaybe, which re-shows notifications during daytime or reschedules repeat alarms. KeepAliveJob is a bounded JobIntentService gate using a CountDownLatch and 60-second timeout. ScreenReceiver updates ApplicationLoader.isScreenOn, pauses/resumes ConnectionsManager, and posts NotificationCenter.screenStateChanged. NotificationsDisabledReceiver listens for Android notification channel block changes, maps the channel id back to global or per-dialog prefs, updates notify2_/global mute keys, and pushes the change to the server.
Notification media and badges are separate helpers. NotificationImageProvider.java exposes content://<applicationId>.notification_image_provider/msg_media_raw/<account>/<filename> for in-flight notification image previews. It waits up to three seconds for NotificationCenter.fileLoaded before falling back or failing, and rejects internal file URIs. NotificationBadge.java implements launcher-specific badge writers for ADW, Apex, Asus, Huawei, HTC, Nova, Samsung/Sony/Xiaomi/Oppo/Vivo/Zuk, plus a default broadcast path; NotificationsController calls into it when badge settings allow badge updates. AnimationNotificationsLocker.java is unrelated to system notifications despite the name: it suppresses NotificationCenter delivery while UI animations are in progress.
Settings surfaces write the shared preference keys consumed by NotificationsController. TMessagesProj/…/NotificationsSettingsActivity.java is the global notifications page: it loads exception lists from MessagesStorage, edits private/group/channel defaults, in-app sound/vibrate/preview/priority, calls, contact-joined and pinned-message events, badge options, all-accounts delivery, push service, repeat notifications, and reset operations. TMessagesProj/…/NotificationsCustomSettingsActivity.java manages exception lists and type-level custom defaults. TMessagesProj/…/ProfileNotificationsActivity.java edits one dialog/topic: enable/mute, preview, sound, vibrate, smart notifications, priority, popup notification, call settings, LED/color, and custom reset. TMessagesProj/…/NotificationsSoundActivity.java selects local/system/uploaded notification tones and writes either global sound keys (GlobalSoundPath, GroupSoundPath, ChannelSoundPath, and document-id variants) or per-dialog/topic sound_path_/sound_document_id_ keys. Server-originated settings are reconciled in NotificationsSettingsFacade.java, which applies TLRPC.PeerNotifySettings to local prefs, MessagesStorage.setDialogFlags, ringtone data, and NotificationCenter.notificationsSettingsUpdated.
Homescreen widgets are backed by Android RemoteViewsService factories and the shortcut_widget shared preferences. ChatsWidgetProvider.java and ContactsWidgetProvider.java are manifest-registered app widget providers with metadata in res/…/chats_widget_info.xml and res/…/contacts_widget_info.xml; they size the widget layout from AppWidgetManager options, ensure a default account/type for new widgets, set LaunchActivity as the pending-intent template, and call notifyAppWidgetViewDataChanged. Their services (ChatsWidgetService.java, ContactsWidgetService.java) read selected dialog ids and latest dialog/message data via MessagesStorage.getWidgetDialogs, populate users/chats into MessagesController, render avatars, unread badges, message snippets, and edit rows, and add fill-in extras (userId, chatId, currentAccount) for LaunchActivity. EditWidgetActivity.java is the shared configuration/editor for chats and contacts widgets: it loads current selection with MessagesStorage.getWidgetDialogIds, lets users reorder/select dialogs, writes MessagesStorage.putWidgetDialogs, records account/type in shortcut_widget, then calls the provider update method. ChatsWidgetConfigActivity.java and ContactsWidgetConfigActivity.java are the Android configuration entry points that host EditWidgetActivity after passcode checks.
The feed widget path is present but disabled. FeedWidgetConfigActivity.java lets a user choose one channel, writes shortcut_widget account/dialog id, and calls FeedWidgetProvider.updateWidget; FeedWidgetProvider.java and FeedWidgetService.java render a feed list by loading messages through MessagesController.loadMessages, waiting for NotificationCenter.messagesDidLoad, and granting launcher packages URI access for thumbnails. Because its manifest receiver/service and config activity are commented out in AndroidManifest.xml, changes here do not affect shipped widgets unless routing is re-enabled.
Coupling
- If the encrypted push payload schema changes on the server, update PushListenerController.java in lockstep: it assumes
pcontains an auth-key-id/message-key/AES-IGE encrypted JSON body, and it manually readsloc_key,custom,user_id, dialog ids, topic ids, message ids, andloc_args. A missing or renamed field often degrades into no notification rather than a compile-time failure. - If a new push
loc_keyis added server-side, add the corresponding case and localized string handling in PushListenerController.java; otherwiseprocessRemoteMessagelogsunhandled loc_keyand noMessageObjectreachesNotificationsController.processNewMessages. - If notification preference keys are renamed, update all writers and readers together: NotificationsController.java, NotificationsSettingsFacade.java, NotificationsSettingsActivity.java, NotificationsCustomSettingsActivity.java, ProfileNotificationsActivity.java, and NotificationsSoundActivity.java share keys such as
notify2_,notifyuntil_,custom_,sound_path_,sound_document_id_,vibrate_,priority_,popup_,smart_*, badge keys, and global sound keys. - If dialog/topic key formatting changes, update
NotificationsController.getSharedPrefKey,NotificationsSettingsFacade,ProfileNotificationsActivity, notification-channel storage keys, and server sync calls together. Topic-aware preferences depend on thedialogId_topicIdstring format, while several Android channel paths still store by dialog id and must not silently drop topic-specific state. - If notification actions change extras or request codes, update both the builders in NotificationsController.java and the receiver readers in AutoMessageHeardReceiver.java, AutoMessageReplyReceiver.java, NotificationDismissReceiver.java, NotificationCallbackReceiver.java, PopupReplyReceiver.java, and OpenChatReceiver.java. These receivers validate only a small set of extras and will no-op on missing
dialog_id,max_id,currentAccount,did,mid,messageDate, or chat/user ids. - If media preview URI behavior changes, verify both
NotificationsController.showExtraNotificationsand NotificationImageProvider.java. The notification builder may hand SystemUI a provider URI for a file that is still downloading; the provider waits onNotificationCenter.fileLoadedand rejects internal URIs. - If widget storage methods change, update ChatsWidgetProvider.java, ContactsWidgetProvider.java, ChatsWidgetService.java, ContactsWidgetService.java, FeedWidgetService.java, EditWidgetActivity.java, and FeedWidgetConfigActivity.java together. Providers rely on
shortcut_widgetfor account/type/deleted/dialog id and onMessagesStorage.getWidgetDialogs/putWidgetDialogsfor selected dialogs. - If re-enabling feed widgets in AndroidManifest.xml, also audit FeedWidgetService.java: it blocks
onDataSetChangedon aCountDownLatchthat is only released byNotificationCenter.messagesDidLoad, so load failures or missing callbacks can stall widget refresh.
Risks
- PushListenerController.java uses a static
CountDownLatchthat is initialized once and awaited byprocessRemoteMessagewhileNotificationsController.processNewMessagesreceives the same latch to count down. Because it is not recreated per push, changes around latch handling can cause later Firebase service calls to return before notification processing completes, or can block indefinitely if a path forgets to count down. - NotificationsDisabledReceiver.java ignores Android channel block events that arrive within one second of
NotificationsController.lastNotificationChannelCreateTime. If channel creation timing or migration changes inNotificationsController.validateChannelId, legitimate user block/unblock actions can be mistaken for creation noise and not synced to Telegram settings. - NotificationImageProvider.java serves files to SystemUI while downloads are racing. If
NotificationsController.showExtraNotificationschanges URI query parameters or file-loader names,openFilecan wait three seconds and then throwFileNotFoundException, leaving image/sticker previews blank in notifications. - FeedWidgetService.java waits without a timeout for
NotificationCenter.messagesDidLoadinonDataSetChanged. The feed widget is currently unreachable because its manifest entries are commented out, but if it is enabled, a failedMessagesController.loadMessagescallback can hang the widget host refresh. - ContactsWidgetService.java and ChatsWidgetService.java sometimes resolve avatar files through
FileLoader.getInstance(UserConfig.selectedAccount)instead of the widget'saccountInstance. Multi-account widgets can show missing or wrong avatars if selected account differs from the widget account.