67

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
  • 418,229
  • 62
  • 649
  • 645
xec86
  • 1,006
  • 1
  • 10
  • 16
  • 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

21 Answers21

58

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
  • 1,823
  • 13
  • 16
  • 1
    I don't know why details is not listed in many of tutorials – VSB Oct 14 '16 at 17:02
  • it might be because it is not needed now – Killer Jun 13 '17 at 09:44
  • @tristan I don't why i have same issue, and my service is still with in application like what you mentioned. I think my device id is storing in the firebase server – Prasad Oct 30 '19 at 17:43
56

"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,403
  • 3
  • 33
  • 57
  • 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
38

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
  • 741
  • 9
  • 22
  • 4
    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
12

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

Nikhil Setty
  • 156
  • 1
  • 3
8

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,155
  • 9
  • 14
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
  • 49,224
  • 12
  • 97
  • 156
tx802
  • 3,386
  • 2
  • 15
  • 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
  • 541
  • 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,223
  • 4
  • 40
  • 44
5

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
  • 7,251
  • 8
  • 45
  • 59
2

In my case, I just turn on WIFI and mobile data in the emulator and it works like a charm. cause I can't send comments, post a reply. Good luck

vahid sabet
  • 120
  • 2
  • 11
2

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. The compiler 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
  • 49,709
  • 33
  • 153
  • 169
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
  • 953
  • 13
  • 20
1

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

Sam
  • 5,427
  • 7
  • 64
  • 78
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,077
  • 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,174
  • 11
  • 20
  • Where do you put the createBigNotification method from and where do you call it from? – Gilboot 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
-1
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
-1
    <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
  • 59
  • 8
-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
  • 3,387
  • 5
  • 25
  • 38
  • 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
-1

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
  • 283
  • 1
  • 4
  • 11
-1

I was experiencing a weird issue, and I could not figure out why I could not receive FCM, if it was working, but then I changed the xml a bit. And I figured out why it was not working.

I changed this:

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

To this:

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

The location where > was put, was causing some issue and so I closed the tag in one line.

Alejandro H
  • 424
  • 5
  • 15
  • Please do not thumbs down without a reason. I didnt just make this up, it is an actual issue that I had and fixed the format of the xml that solved the issue of not being able to receive notifications. Anchor tags and format of code is something important that a lot of people do not know about that can actually cause real issues, not just in xml but in react code as well. – Alejandro H Apr 04 '21 at 00:41
-2

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