1

For some reason my Firebase notifications are not showing in the foreground. They work fine in the background however, and I followed what Anroid Studio told me to add as well as this tutorial example on github

Judging by the Run window, it is receiving the notification but not sending in foreground

Here is my service code for sending the notification

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

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

import static android.support.constraint.Constraints.TAG;

public class FirebaseNotificationsRecieverService extends FirebaseMessagingService {
    private static final String TAG = FirebaseNotificationsRecieverService.class.getName();

    public FirebaseNotificationsRecieverService() {
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // ...
        System.out.println("RECIEVED");
        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: (there was a link here)
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                //scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }
        sendNotification(remoteMessage.getNotification().getBody());
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.drawable.wlmaclogo)
                        .setContentTitle(getString(R.string.fcm_message))
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

}

Manifest:

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <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/AppTheme"
        android:usesCleartextTraffic="true">
        <service
            android:name=".FirebaseNotificationsRecieverService"
            android:enabled="true"
            android:exported="true"></service>
        <service android:name="com.google.firebase.messaging.FirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
  • have you defined the service in the manifest? – Kaveri Mar 14 '19 at 16:55
  • Yup. Just added the manifest^ if you could check it out to make sure it's fine. My run module says "Connected to remote service" and then "Inactivity, disconnecting from service" but when I push a notification it seems to start it again. – Andrey Starenky Mar 14 '19 at 17:25
  • I added a System.out.println("RECIEVED"); to see if it even calls the onMessageReceived but it didn't print anything so I don't think its calling the method – Andrey Starenky Mar 14 '19 at 17:31
  • Try it like this https://stackoverflow.com/questions/52609283/push-notification-in-android-with-firebase-get-token/52611381#52611381 – Yasiru Nayanajith Mar 14 '19 at 17:36

2 Answers2

3

Replace the manifest as below:-

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

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

<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/AppTheme"
    android:usesCleartextTraffic="true">

    <service android:name=".FirebaseNotificationsRecieverService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

The intent filter com.google.firebase.MESSAGING_EVENT should be placed in your service, which you are using to get the notifications.

Kaveri
  • 1,060
  • 2
  • 12
  • 21
  • Thank you so much this fixed everything! Could you please tell me how to switch out the `.setContentTitle(getString(R.string.fcm_message))` for the title that comes with the firebase notification? I tried passing the remoteMessage to the `sendNotification(RemoteMessage remoteMessage)` and it worked for description, but `remoteMessage.getNotification().getTitle()` for title gives error `Cannot resolve method 'getString(java.lang.String)'` – Andrey Starenky Mar 14 '19 at 17:59
0

Remember to remove the existing messaging service from the AndroidManifest.xml. If you leave the FireBaseMessagingService in the Manifest. your newly defined service doesn't get picked up.

E.g. remove the following:

    <service
        android:name="com.google.firebase.messaging.FirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

and add the following:

    <service
        android:name=".MyFirebaseNotificationService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
BenJ
  • 51
  • 1
  • 4