Skip to content

How to display messages when app is running in the foreground?

Alexander Boldyrev edited this page Oct 30, 2024 · 3 revisions

Using built-in Mirror push notification feature

Mobile Messaging SDK has a built-in logic to display Mirror push notifications with a minimum development effort, more details here: Mirror push notifications

Writing custom handler

MobileMessaging library provides NotificationSettings configuration class which configures how notification will look like if the library is displaying it. To display messages when app is running in the foreground, you have to:

  1. Disable displaying foreground notifications by calling withoutForegroundNotification() method:

     MobileMessaging.Builder(application)
             .withMessageStore(SharedPreferencesMessageStore::class.java)
             .withDisplayNotification(NotificationSettings.Builder(this)
                     .withoutForegroundNotification()
                     .build())
             .build()
    expand to see Java code

     new MobileMessaging.Builder(application)
             .withMessageStore(SharedPreferencesMessageStore.class)
             .withDisplayNotification(new NotificationSettings.Builder(this)
                     .withoutForegroundNotification()
                     .build())
             .build();
  2. Create BroadcastReceiever to handle push message:

    private val messageReceiver: BroadcastReceiver = object: BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val message: Message = Message.createFrom(intent.extras)
            displayMyForegroundNotification(message)
        }
    }
    expand to see Java code

    private final BroadcastReceiver messageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Message message = Message.createFrom(intent.getExtras());
            displayMyForegroundNotification(message);
        }
    };

Before that, you need to register BroadcastReceiver for MESSAGE_RECEIVED event:

localBroadcastManager.registerReceiver(messageReceiver, IntentFilter(Event.MESSAGE_RECEIVED.key))
expand to see Java code

localBroadcastManager.registerReceiver(messageReceiver, new IntentFilter(Event.MESSAGE_RECEIVED.getKey()));
and unregister it afterwards (e.g. in ```onDestroy()``` method):
localBroadcastManager.unregisterReceiver(messageReceiver)
expand to see Java code

localBroadcastManager.unregisterReceiver(messageReceiver);
Clone this wiki locally