onMessageReceived
Callback invoked when a push notification is received, before it is displayed.
This is the primary method for customizing notification display behavior. Override this method to suppress notification display when the app is in the foreground, filter unwanted notifications, or handle notifications with custom UI.
Important: This method runs on a background worker thread, so it's safe to perform I/O operations, but you must use android.os.Handler or runOnUiThread() for UI updates.
Return Value:
- true - Notification will NOT be displayed in the notification center. Use this when handling the notification with custom in-app UI or when suppressing foreground notifications.
- false - Notification will be displayed normally in the notification center.
By default, this method returns true if the app is in the foreground and "Show foreground alert" is enabled in Pushwoosh settings, otherwise returns false. Example 1: Suppress notifications when app is in foreground
protected boolean onMessageReceived(PushMessage message) {
if (isAppOnForeground()) {
// Show custom in-app notification
Context context = getApplicationContext();
Handler mainHandler = new Handler(context.getMainLooper());
mainHandler.post(() -> {
Toast.makeText(context,
message.getMessage(),
Toast.LENGTH_LONG).show();
});
return true; // Don't show system notification
}
return false; // Show notification normally
}
Example 2: Filter notifications by priority
protected boolean onMessageReceived(PushMessage message) {
String priority = message.getCustomData().getString("priority");
// Block low-priority notifications when user is busy
if ("low".equals(priority) && isUserBusy()) {
Log.d("Notifications", "Suppressed low priority notification");
return true; // Suppress notification
}
// Show high-priority with custom sound
if ("high".equals(priority)) {
playCustomSound();
}
return false; // Show notification
}
Example 3: Handle notifications with custom in-app UI
protected boolean onMessageReceived(PushMessage message) {
if (isAppOnForeground()) {
Context context = getApplicationContext();
Handler mainHandler = new Handler(context.getMainLooper());
mainHandler.post(() -> {
// Show custom dialog or banner
Intent intent = new Intent(context, InAppNotificationActivity.class);
intent.putExtra("message", message.getMessage());
intent.putExtra("title", message.getHeader());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
});
return true; // Notification handled in-app
}
return false; // Show system notification
}
Return
true to suppress notification display, false to show notification normally
Parameters
the push message data containing notification content and custom payload