said omar
said omar

Reputation: 25

Firebase Cloud Messaging push notification not working in foreground, only background, on Android

I'm trying to create an app that can receive a notification when certain requirements are filled. I tried to set up a seperate project to make a simple cloud messaging system but no notifications show up when the app is running in the foreground, only in the background.

Here is the main MapActivity code:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        Intent intentBackgroundService = new Intent(this,FirebasePushNotification.class);
        startService(intentBackgroundService);
    }

The firebase Messaging Class:

package com.example.traindetectionproject;

import androidx.annotation.NonNull;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class FirebasePushNotification extends FirebaseMessagingService {


    public FirebasePushNotification() {
        super();
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
    }
}

The manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.traindetectionproject">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the "MyLocation" functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Traindetectionproject">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>



    <service android:name=".FirebasePushNotification">
        <intent-filter>
            <action android:name="android.intent.action.RESPOND_VIA_MESSAGE"/>
        </intent-filter>
    </service>
    </application>

</manifest>

Thank you for any advice

Upvotes: 1

Views: 5488

Answers (2)

niranj1997
niranj1997

Reputation: 847

The below code snippet might help you arrive at the solution

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onNewToken ( @NonNull String s ) {
        super.onNewToken ( s );
    }

    @Override
    public void onMessageReceived ( @NonNull RemoteMessage remoteMessage ) {
        super.onMessageReceived ( remoteMessage );
        NotificationManager notificationManager = (NotificationManager) getSystemService ( Context.NOTIFICATION_SERVICE );
        if (!Objects.equals ( null, remoteMessage.getNotification () )) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                NotificationChannel notificationChannel = new NotificationChannel ( NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH );
                notificationManager.createNotificationChannel ( notificationChannel );
            }
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder ( this, NOTIFICATION_CHANNEL_ID );
            notificationBuilder.setAutoCancel ( true )
                    .setStyle ( new NotificationCompat.BigTextStyle ().bigText ( remoteMessage.getNotification ().getBody () ) )
                    .setDefaults ( Notification.DEFAULT_ALL )
                    .setWhen ( System.currentTimeMillis () )
                    .setSmallIcon ( R.drawable.ic_notification_icon )
                    .setTicker ( remoteMessage.getNotification ().getTitle () )
                    .setPriority ( Notification.PRIORITY_MAX )
                    .setContentTitle ( remoteMessage.getNotification ().getTitle () )
                    .setContentText ( remoteMessage.getNotification ().getBody () );   
            notificationManager.notify ( 1, notificationBuilder.build () );
        }
    }
}

Add this to your AndroidManifest.xml before any Activity TAG

<service
   android:name=".utilities.MyFirebaseMessagingService"
   android:exported="false">
   <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
   </intent-filter>
</service>

Upvotes: 0

from56
from56

Reputation: 4127

In the foreground the notification is received in onMessageReceived but not shown, then your code in onMessageReceived should compose and show it,

Instead when the app is in the background then the notification is shown directly in the Notification bar without onMessageReceived being called

Look here : https://firebase.google.com/docs/cloud-messaging/android/receive

Upvotes: 1

Related Questions