Skip to Content
AI Powered Docs! 🤖 These docs are translated with AI, so keep an eye out for minor quirks. We're always improving!

Messaging

This section contains documentation related to push notifications and in-app messages provided by the Metrix Notification module.

Firebase Implementation

  1. To begin, download the google-services.json file from the Firebase console and place it in your project.
app/ directory of your Android project
  1. Then, you need to enter the Push Credentials or the service-account.json file of the Firebase project in the Metrix panel.

  2. Update the build.gradle file:

Project-level build.gradle file:

buildscript { dependencies { classpath 'com.google.gms:google-services:4.4.2' } }

Application-level build.gradle:

plugins { id 'com.android.application' id 'com.google.gms.google-services' } dependencies { // Notification module (automatically includes Firebase messaging) implementation 'ir.metrix.notification:metrix:2.8.1' }

Firebase BOM Configuration (Optional)

If you need to manage Firebase dependencies separately, use the Firebase BOM with proper exclusions: Note: If you want to have Firebase dependencies in your project, exclude the firebase-iid and firebase-messaging values. Example:

dependencies { implementation platform('com.google.firebase:firebase-bom:32.0.0') { exclude group: 'com.google.firebase', module: 'firebase-messaging' exclude group: 'com.google.firebase', module: 'firebase-iid' } // Notification module provides firebase-messaging implementation 'ir.metrix.notification:metrix:2.8.1' }

Push Notification Setup

Add Notification Module Dependency

implementation 'ir.metrix.notification:metrix:2.8.2'

Implement Firebase Messaging Service

Add the Firebase Messaging Service to your AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application> <!-- Firebase Cloud Messaging Service --> <service android:name="ir.metrix.notification.receivers.MetrixFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> </application> </manifest>

Identify Users for Push Notifications

Push notifications are only sent to identified users. Set the custom user ID when a user logs in:

// When user logs in MetrixAnalytics.User.setUserCustomId("user@example.com"); // When user logs out MetrixAnalytics.User.deleteUserCustomId();

Important: The customUserId attribute must be set for users to receive notifications. Notifications are sent to the current identified user only.

Automatic notification permission prompt

By default, when the notification module initializes it creates the default notification channel and shows the system notification permission prompt (required on Android 13+ / API 33 to display push notifications).

To disable this automatic behavior and control when the prompt is shown yourself, add this meta-data inside the <application> tag:

<manifest> ... <application> ... <meta-data android:name="metrix_auto_notification_permission" android:value="false" /> </application> </manifest>

Defaults to true when not present. When disabled, the SDK also skips creating the default notification channel, so create it and request the permission manually at the moment of your choosing:

Push Notification Management

Enable/Disable Notifications

Control whether the user receives notifications:

// Enable notifications (default: enabled) MetrixNotification.enableNotifications(); // Disable notifications MetrixNotification.disableNotifications(); // Check notification status boolean isEnabled = MetrixNotification.isNotificationEnable();

Custom Sound Management

Control whether notifications play custom sounds:

// Enable custom sounds (default: enabled) MetrixNotification.enableCustomSound(); // Disable custom sounds MetrixNotification.disableCustomSound(); // Check custom sound status boolean isSoundEnabled = MetrixNotification.isCustomSoundEnable();

Create Default Notification Channel

For Android 8.0 (API 26) and higher, create a default notification channel:

MetrixNotification.createNotificationDefaultChannel();

Set Notification Listener

Handle notification events with a custom listener:

MetrixNotification.setNotificationListener(new MetrixNotificationListener() { @Override public void onNotificationReceived(PushNotification notification) { // Handle incoming notification Log.d("Notification", "Received: " + notification.getTitle()); } @Override public void onNotificationClicked(PushNotification notification) { // Handle notification click Log.d("Notification", "Clicked: " + notification.getTitle()); } @Override public void onNotificationDismissed(PushNotification notification) { // Handle notification dismiss Log.d("Notification", "Dismissed: " + notification.getTitle()); } });

Check Initialization Status

Verify that the notification module has initialized:

boolean isInitialized = MetrixNotification.isInitialized(); // Or use a listener for initialization completion MetrixNotification.setInitializationCompleteListener(() -> { Log.d("Notification", "Notification module initialized"); });

In-App Messages

In-app messages are lightweight messages displayed directly within your application without requiring push notifications. They can be customized, triggered based on user actions, and include interactive elements.

Auto-Loading In-App Messages

By default, in-app messages are automatically loaded and displayed when the app is opened.

Manual In-App Message Loading

To disable auto-loading and manually trigger message loading:

1. Disable Auto-Loading in Manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application> <!-- Disable auto-load in-app messages --> <meta-data android:name="metrix_auto_load_in_app_messages" android:value="false" /> </application> </manifest>

2. Call loadInAppMessages() When Needed

// Load messages on a specific screen public class MyActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Load in-app messages for this screen MetrixNotification.loadInAppMessages(); } }

Control In-App Message Display

Pause and resume in-app messaging:

// Pause in-app messaging (useful during gameplay or important interactions) MetrixNotification.pauseInAppMessages(true); // Resume in-app messaging MetrixNotification.pauseInAppMessages(false); // Check if in-app messaging is paused boolean isPaused = MetrixNotification.isInAppMessagingPaused();

Use Cases for Manual Control

Pause during important interactions:

public class GameActivity extends AppCompatActivity { private void startGame() { // Pause messages during active gameplay MetrixNotification.pauseInAppMessages(true); } private void gameOver() { // Resume messages after game ends MetrixNotification.pauseInAppMessages(false); // Load messages to show reward notifications MetrixNotification.loadInAppMessages(); } }

Load messages on specific screens:

public class PromotionalScreen extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.promotional_screen); // Load in-app messages only on promotional screen MetrixNotification.loadInAppMessages(); } }

Notification Permissions

Android 13+ Runtime Permissions

For Android 13 (API 33) and higher, request the POST_NOTIFICATIONS permission:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> </manifest>

Request at runtime:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, PERMISSION_REQUEST_CODE); } }

Configuration

The notification module supports various configuration options for advanced customization:

Configuration KeyTypeDefaultDescription
notif_enabledBooleantrueWhether notifications are enabled globally
notif_build_max_attemptsInteger8Maximum attempts to build a notification
notif_max_sound_durationTime5 secondsMaximum duration for custom notification sounds
registration_backoff_policyBackoffPolicyEXPONENTIALFCM token registration retry policy
registration_backoff_delayTime30 secondsDelay between FCM token registration retries

Troubleshooting

Notifications Not Received

Causes:

  • google-services.json not added to app directory
  • Firebase credentials not configured in Metrix panel
  • User ID (customUserId) not set
  • Notifications disabled via disableNotifications()

Solutions:

  1. Verify google-services.json is in app/ directory
  2. Check Firebase credentials in Metrix panel settings
  3. Set user ID: MetrixAnalytics.User.setUserCustomId("userId")
  4. Check notification status: MetrixNotification.isNotificationEnable()

In-App Messages Not Appearing

Causes:

  • Auto-loading disabled without calling loadInAppMessages()
  • Messaging paused via pauseInAppMessages(true)
  • Notification module not initialized

Solutions:

  1. Call MetrixNotification.loadInAppMessages() on the desired screen
  2. Check if paused: MetrixNotification.isInAppMessagingPaused()
  3. Verify initialization: MetrixNotification.isInitialized()

Firebase Service Not Found

Causes:

  • MetrixFirebaseMessagingService not declared in manifest
  • com.google.gms:google-services plugin not applied

Solutions:

  1. Add service to AndroidManifest.xml (see Firebase Messaging Service setup)
  2. Apply com.google.gms.google-services plugin in build.gradle

Missing Permissions

Symptoms: Logcat warnings about POST_NOTIFICATIONS permission

Solution:

  1. Add permission to manifest: <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
  2. Request permission at runtime for Android 13+

Best Practices

1. Always Set User ID for Identified Users

// Set immediately after user authentication if (user.isAuthenticated()) { MetrixAnalytics.User.setUserCustomId(user.getId()); }

2. Handle Notifications Gracefully

MetrixNotification.setNotificationListener(new MetrixNotificationListener() { @Override public void onNotificationClicked(PushNotification notification) { // Navigate to relevant screen Intent intent = new Intent(context, NotificationDetailActivity.class); intent.putExtra("notification_id", notification.getId()); startActivity(intent); } });

3. Respect User Preferences

// Allow users to disable notifications from app settings private void onNotificationSettingsClick() { boolean currentStatus = MetrixNotification.isNotificationEnable(); MetrixNotification.enableNotifications(); // or disableNotifications() updateSettingsUI(); }

4. Load Messages at Appropriate Times

// Don't load during critical moments private void onLoadingScreen() { MetrixNotification.pauseInAppMessages(true); } private void onLoadingComplete() { MetrixNotification.pauseInAppMessages(false); MetrixNotification.loadInAppMessages(); }

5. Test Notifications in Development

// Add test push notification handling if (BuildConfig.DEBUG) { MetrixNotification.setNotificationListener(new MetrixNotificationListener() { @Override public void onNotificationReceived(PushNotification notification) { Log.d("NotifTest", "Test notification: " + notification.getTitle()); } }); }