94

I am having an issue with FireBase Cloud Messaging in which I get the Token from the device and send the notification test through the Google Firebase notification console however, the notification is never logged nor pushed to the android virtual device. The documentation for FCM is almost exactly the code that I have below and little else in the way of what else you would have to do to get push notifications working with firebase. I have gone through all of the setup information (build.gradle additions, Installing google play services, etc...) as specified in the documentation but still do not have messages generating. I do receive a one-time error immediately after pushing the notification that states "I/FA: Tag Manager is not found and thus will not be used" but that is the only data that is output and I did not find anything related to Tag Manager requirements and FCM on the googles. What is wrong with the code that I am not receiving my push notifications to the logcat or the device? Please let me know any further information that would be helpful. Thanks.

NotificationGenie.java

public class NotificationGenie extends FirebaseMessagingService {

private static final String TAG = "Firebase_MSG";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // TODO(developer): Handle FCM messages here.
    // If the application is in the foreground handle both data and notification messages here.
    // 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.
    sendNotification(remoteMessage.getNotification().getBody());
    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
}

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

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.tf2spyprofile)
            .setContentTitle("FCM Message")
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

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

}

AndroidManifest.xml

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

<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".LoginActivity"
        android:label="@string/title_activity_login">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".DashBoardActivity"
        android:label="@string/title_activity_dash_board"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

    <activity
        android:name=".NewOrderActivity"
        android:label="@string/title_activity_dash_board"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>

    <activity
        android:name=".PostLoginActivity"
        android:label="@string/title_activity_dash_board"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>
</application>

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

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
xec86
  • 1,291
  • 1
  • 11
  • 17
  • google play services is not installed on virtual device. check this link if you want to see how to send notification from server http://codingaffairs.blogspot.com/2016/06/firebase-cloud-messaging-push.html – Developine Jun 24 '16 at 17:22
  • You can visit this thread. It has clear description on firebase cloud messaging http://stackoverflow.com/questions/39046270/google-fcm-getintent-dont-returning-expected-data-when-app-is-in-background-stat – Md. Sajedul Karim Aug 27 '16 at 09:27

23 Answers23

80

"You must also keep in mind that to receive Messages sent from Firebase Console, App must be in background, not started neither hidden." --- According to @Laurent Russier's comment.

I never got any message from Firebase, until i put my app in the background.

This is true only on usb connection for emulator you get notification in foreground as well

aaa118
  • 1
  • 4
Tosin Onikute
  • 3,883
  • 6
  • 38
  • 61
  • I have to open the app and next press the home button? – JCarlosR Oct 24 '16 at 01:11
  • 1
    No, you need to make sure your app is on background to get a Notification message from console – Tosin Onikute Oct 24 '16 at 07:21
  • You can test using http://pushtry.com easier than Firebase console. You can also send custom JSON. – Arvind Dec 29 '16 at 11:13
  • Thanks @HtmlTosin! It worked for me too on the App that I am migrating from GCM to FCM. However, when I tested on the following example project I could send Push Notifications through Firebase Console even when the App is in foreground: https://github.com/ton1n8o/FCMTutorial Weird... – Marie Amida Jan 09 '17 at 12:29
  • I am not getting in the foreground, even after installing application build on phone – Zeeshan Ahmad Khalil Jul 26 '21 at 07:21
  • It also takes time depending on internet connectivity. Took about 2 min in my case – Ravi Mishra May 23 '22 at 13:23
60

You have placed your service outside the application tag. Change bottom to this.

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

</application>
Tristan Richard
  • 3,385
  • 1
  • 15
  • 17
47

I had the same problem and it is solved by defining enabled, exported to true in my service

  <service
            android:name=".MyFirebaseMessagingService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
Hoby
  • 1,024
  • 12
  • 24
  • 5
    This worked for me. Actually, I was finding that I was only receiving notifications when my app was running. If I restarted the phone, notifications wouldn't come through. But after setting the `enabled` and `exported` attributes, the push notifications come through fine now. Thanks, Hoby! :-) – ban-geoengineering Sep 05 '16 at 21:51
  • 3
    I think it would probably be a good idea to add the same two attributes to your `MyInstanceIDListenerService` service, too. – ban-geoengineering Sep 05 '16 at 21:53
  • 2
    Thanks. I was trying a lot of things, but it is the solution. Do you know why it happens? – JCarlosR Oct 24 '16 at 01:25
  • 4
    Not necessary. Tried Firebase Sample Messaging Project - with and without "enabled" and "exported" - it's excessive. Helped running and hiding app to see notification at topbar - see Html Tosin's answer. – Zon Jul 12 '17 at 06:04
  • 3
    As per android docs enabled is `true` by default and exported means if service can be invoked by components external to the app. Not sure why this is necessary here. https://developer.android.com/guide/topics/manifest/service-element#exported – Adi Oct 06 '19 at 06:54
  • Worked for me too! Tutorial I watched had "exported=false", it worked when I changed to true :) – Sam Chahine Jul 31 '22 at 10:42
14

Call super.OnMessageReceived() in the Overriden method. This worked for me! Finally!

Nikhil Setty
  • 176
  • 1
  • 3
10

I faced the same issue of Firebase cloud messaging not received by device.

In my case package name defined on Firebase Console Project was diferent than that the one defined on Manifest & Gradle of my Android Project.

As a result I received token correctly but no messages at all.

To sumarize, it's mandatory that Firebase Console package name and Manifest & Gradle matchs.

You must also keep in mind that to receive Messages sent from Firebase Console, App must be in background, not started neither hidden.

Juan Pablo
  • 1,213
  • 10
  • 15
  • 10
    "You must also keep in mind that to receive Messages sent from Firebase Console, App must be in background, not started neither hidden." – Laurent Russier Jul 07 '16 at 09:06
  • 3
    What do you mean when you say "not started neither hidden"? – Gilbert Apr 27 '20 at 14:02
  • That's a typo. That app has to be running but in the background. If you have the app currently open when the push notification comes in the OS will not display it. – d512 Apr 26 '23 at 01:53
9

In my case, I noticed mergedmanifest was missing the receiver. So I had to include:

 <receiver
            android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
 </receiver>
Irshu
  • 8,248
  • 8
  • 53
  • 65
  • even i am using latest firebase 18.0.0 still i was not getting notification. But your solution worked for me. – AKASH WANGALWAR Jun 12 '19 at 08:47
  • I thought FirebaseInstanceIdService was depreciated. What is this receiver – Dr Deo Apr 04 '20 at 23:13
  • I spent the whole day investigating and try all approaches, suggestions from Firebase official page, SO.... and this is the one which just make FCM work for my app. – Tiny Sonhh Dec 18 '22 at 16:27
8

I had a similar problem, but in my case I was missing the google-services plugin from my Gradle build (I was adding Firebase to an existing project).

I added the following to my root build.gradle:

classpath 'com.google.gms:google-services:3.1.0'

and the following to the end of my app-level build.gradle:

apply plugin: 'com.google.gms.google-services'

I then had to download the google-services.json file from the Firebase Console (having originally imported an existing Google Cloud project) and copy it to my app directory`.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
tx802
  • 3,524
  • 2
  • 17
  • 22
8

I faced the same problem but I had still had some debris in my manifest from the old GCM. When I took the following permission out of my manifest it fixed the error. com.google.android.c2dm.permission.RECEIVE

RSSV
  • 591
  • 1
  • 4
  • 8
6

If you have just added FCM to an existing app, onTokenRefresh() will NOT be called. I got it to run by uninstalling the app and installing it again.

Tash Pemhiwa
  • 7,590
  • 4
  • 45
  • 49
6

After spending hours on this issue I finally realised the problem when I intentionally corrupted the format of the "google-services.json" and my build still succeeded. My IDE(AndroidStudio) does not notice the changes in this file. I tried many things, "reload from disk", gradle task "cleanBuildCache", new virtual device, uninstalling/reinstalling the app etc but none worked.

For me the solution was in AndroidStudio -> Build -> Clean Project and Build -> Rebuild Project

PS: Also make sure "google-services.json" is in the "app" folder.

Caner
  • 57,267
  • 35
  • 174
  • 180
  • 1
    Thanks for posting this. The package name of my app in FCM's console was different from the package name in my local. Even though I had fixed that in the google-services.json, I still had to uninstall the app, clean build, rebuild, redeploy. Thanks! – Andrew Nov 16 '21 at 22:32
5

In my case, I just turned on WiFi and mobile data in the emulator and it worked like a charm.

iDecode
  • 22,623
  • 19
  • 99
  • 186
vahid sabet
  • 485
  • 1
  • 6
  • 16
2

When you copying your device token, it might copying the space, double check you have copied the correct token

Sam
  • 6,215
  • 9
  • 71
  • 90
1

You need to Follow Below Manifest Code (must have Service in manifest)

 <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="soapusingretrofitvolley.firebase">
        <uses-permission android:name="android.permission.INTERNET"/>
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

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

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

            <service
                android:name=".MyFirebaseInstanceIDService">
                <intent-filter>
                    <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
                </intent-filter>
            </service>
        </application>

    </manifest>
Nilesh
  • 1,013
  • 14
  • 21
1

I had this problem, I checked my code. I tried to fix everything that was mentioned here. lastly the problem was so stupid. My device's Sync was off. that was the only reason I wasn't receiving notifications as expected.

enter image description here

Soorena
  • 4,352
  • 5
  • 30
  • 42
  • 1
    It is strange. I also disable Sync, even don't authorize in Google. Before everything worked, I hardly changed anything, but now it doesn't connect. Will search further. – CoolMind Oct 16 '19 at 12:49
0
private void sendNotification(String message) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    int requestCode = 0;
    PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.URI_COLUMN_INDEX);
    NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText(message)
            .setColor(getResources().getColor(R.color.colorPrimaryDark))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("FCM Message")
            .setContentText("hello").setLargeIcon(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap())
            .setStyle(new NotificationCompat.BigPictureStyle()
                    .bigPicture(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap()))
            .setAutoCancel(true)
            .setSound(sound)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, noBuilder.build());
  • when i am clear my recent not come notification please help me how can i fix this issue and when i am disconnect to usb debuging mode then my phone notification context doesnt show – Ashish Shahi Apr 20 '17 at 11:52
0
    <activity android:name=".activity.MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!-- Firebase Notifications -->
    <service android:name=".service.MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service android:name=".service.MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
ashutosh
  • 69
  • 8
0

I've been working through this entire post and others as well as tutorial videos without being able to solve my problem of not receiving messages, the registration token however worked.

Until then I had only been testing the app on the emulator. After trying it on a physical phone it instantly worked without any prior changes to the project.

Jens
  • 1,157
  • 1
  • 8
  • 17
0

As if you want your app to run in > 24 versions too, follow these:

1.Add this in your strings.xml

< string name="default_notification_channel_id" translatable="false"> fcm_default_channel

  1. Add this meta-data in your manifest file:

< meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" />

3.for creating notifications (with images) use this method where you are handling notifications, if directly then add in the firebasemessaging service or if you are using some util class then add in that util class :

   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public static void createBigNotification(Bitmap bitmap, int icon, String message, Uri alarmSound) {
        final int NOTIFY_ID = 0; // ID of notification
        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
        String id = mContext.getString(R.string.default_notification_channel_id); // default_channel_id
        String title = mContext.getString(R.string.app_name);
        Intent intent;
        NotificationCompat.Builder builder;
        if (notificationManager == null) {
            notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        PendingIntent resultPendingIntent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = notificationManager.getNotificationChannel(id);
            if (mChannel == null) {
                mChannel = new NotificationChannel(id, title, importance);
                mChannel.enableVibration(true);
                mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
                notificationManager.createNotificationChannel(mChannel);
            }
            builder = new NotificationCompat.Builder(mContext, id);
            intent = new Intent(mContext, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
            bigPictureStyle.setBigContentTitle(title);
            bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
            bigPictureStyle.bigPicture(bitmap);

            builder.setContentTitle(title)        // required
                    .setSmallIcon(R.drawable.app_icon)   // required
                    .setContentText(message) // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setSound(alarmSound)
                    .setStyle(bigPictureStyle)
                    .setContentIntent(resultPendingIntent)
                    .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                    .setTicker(title)
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
        } else {
            builder = new NotificationCompat.Builder(mContext, id);
            intent = new Intent(mContext, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            resultPendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle();
            bigPictureStyle.setBigContentTitle(title);
            bigPictureStyle.setSummaryText(Html.fromHtml(message).toString());
            bigPictureStyle.bigPicture(bitmap);

            builder.setContentTitle(title)     // required
                    .setSmallIcon(R.drawable.app_icon)   // required
                    .setContentText(message) // required
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setSound(alarmSound)
                    .setStyle(bigPictureStyle)
                    .setContentIntent(resultPendingIntent)
                    .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
                    .setTicker(title)
                    .setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
                    .setPriority(Notification.PRIORITY_HIGH);
        }
        Notification notification = builder.build();
        notificationManager.notify(NOTIFY_ID, notification);
    }

Follow these steps and your notification will come in the notification tray.

amit pandya
  • 1,384
  • 13
  • 22
  • Where do you put the createBigNotification method from and where do you call it from? – Gilbert Apr 27 '20 at 15:38
  • @Ssenyonjo you can add it in your broadcast receiver or the Activity/Fragment file which you will access globally in the app. – amit pandya Apr 28 '20 at 06:08
0

In my case, I manually killed some google play services and forgot about it.

Later, I have to restart the device, after that I can receive notification without any problem.

dante
  • 984
  • 3
  • 10
  • 24
0

2 mistakes that I had to correct, after which the issue was resolved.

Referring to the official documentation gave this nice snippet which helped confirm the Subscription status.

 Firebase.messaging.subscribeToTopic(TOPIC)
                    .addOnCompleteListener { task ->
                        var topicSubscriptionStatus = "Subscribed"
                        if (!task.isSuccessful) {
                            topicSubscriptionStatus = "Subscribe failed"
                        }
                        Log.d(TAG, topicSubscriptionStatus)
                        Toast.makeText(baseContext, topicSubscriptionStatus, Toast.LENGTH_SHORT).show()
                    }
  1. my topic name had a typo "/topic/" instead of the correct one "/topics/". Right after correcting this the service started receiving the messages

  2. I had to add the flag "FLAG_IMMUTABLE" on the PendingIntent (error in logcat mentioned this is needed from S)

(I m on Tiramisu)

Basu R
  • 1
  • 2
0

Add in your app manifest Check docs https://firebase.google.com/docs/cloud-messaging/android/receive

<service
android:name=".java.MyFirebaseMessagingService"
android:exported="false">
 <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT" />
 </intent-filter>
</service>
Sehrish Waheed
  • 1,230
  • 14
  • 17
-1

I followed all the steps according to the firebase website to set up sending notifications for Android APPs. I tried many times but I can't received the notifications no matter on virtue device or physical device. After I changed some settings(those settings about receiving notifications in the SETTING section ) in virtue device and physical device, both virtual and physical devices started receiving notifications.

Oliver
  • 19
  • 2
-2

maybe it is from the connection I changed the connection from Ethernet to wireless the it worked without doing anything else