Messaging
This section contains documentation related to push notifications and in-app messages provided by the Metrix Notification module.
Firebase Implementation
- To begin, download the
google-services.jsonfile from the Firebase console and place it in your project.
app/ directory of your Android project-
Then, you need to enter the Push Credentials or the
service-account.jsonfile of the Firebase project in the Metrix panel. -
Update the
build.gradlefile:
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
customUserIdattribute 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 Key | Type | Default | Description |
|---|---|---|---|
notif_enabled | Boolean | true | Whether notifications are enabled globally |
notif_build_max_attempts | Integer | 8 | Maximum attempts to build a notification |
notif_max_sound_duration | Time | 5 seconds | Maximum duration for custom notification sounds |
registration_backoff_policy | BackoffPolicy | EXPONENTIAL | FCM token registration retry policy |
registration_backoff_delay | Time | 30 seconds | Delay between FCM token registration retries |
Troubleshooting
Notifications Not Received
Causes:
google-services.jsonnot added to app directory- Firebase credentials not configured in Metrix panel
- User ID (customUserId) not set
- Notifications disabled via
disableNotifications()
Solutions:
- Verify
google-services.jsonis inapp/directory - Check Firebase credentials in Metrix panel settings
- Set user ID:
MetrixAnalytics.User.setUserCustomId("userId") - 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:
- Call
MetrixNotification.loadInAppMessages()on the desired screen - Check if paused:
MetrixNotification.isInAppMessagingPaused() - Verify initialization:
MetrixNotification.isInitialized()
Firebase Service Not Found
Causes:
MetrixFirebaseMessagingServicenot declared in manifestcom.google.gms:google-servicesplugin not applied
Solutions:
- Add service to
AndroidManifest.xml(see Firebase Messaging Service setup) - Apply
com.google.gms.google-servicesplugin inbuild.gradle
Missing Permissions
Symptoms: Logcat warnings about POST_NOTIFICATIONS permission
Solution:
- Add permission to manifest:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> - 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());
}
});
}