Cant receive Notifications from FCM while the app is in Foreground state












1














I am new to Android and programming and I am creating an app that receives messages from FCM and its work normally while the app in the Background, so I have added a FirebaseMessagingService class that receives the notifications in onMessageReceived method and followed out google docs but still the notification does not work while the app in the foreground state, I have followed every step and can't figure out where is the problem in my code as the Logs does not help me and I don't receive any bug expect this one which I don't know if its the source if the problem:
Error while parsing timestamp in GCM event java.lang.NumberFormatException: s == null



Here is my MyFirebaseMessagingService class



import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;

import com.app.muhammadgamal.swapy.R;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

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

String click_Action = remoteMessage.getNotification().getClickAction();


String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();


NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_main_logo)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);


Intent intent = new Intent(click_Action);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);


int mNotificationID = (int)System.currentTimeMillis();
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
manager.notify(mNotificationID,mBuilder.build());

}
}


and my Manifest File



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

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<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="@drawable/ic_main_logo"
android:label="@string/app_name"
android:roundIcon="@drawable/ic_main_logo"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".Activities.SignInActivity"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activities.SignUpActivity"
android:theme="@style/AppTheme.NoActionBar" />
<activity
android:name=".Activities.ProfileActivity"
android:theme="@style/AppTheme.NoActionBar" />
<activity
android:name=".Activities.NavDrawerActivity"
android:theme="@style/AppTheme.NoActionBar" />
<activity
android:name=".Activities.SwapCreationActivity"
android:theme="@style/AppTheme.NoActionBar" />

<activity android:name=".Activities.ReceivedSwapRequest">
<intent-filter>
<action android:name="com.app.muhammadgamal.swapy.Activities.ReceivedSwapRequest_NOTIFICATION_TASK"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</activity>

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

</application>

</manifest>


and my index function



   'use strict'


const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);


exports.sendNotification = functions.database.ref('/Notifications/{receiver_user_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_user_id = context.params.receiver_user_id;
const notification_id = context.params.notification_id;


console.log('We have a notification to send to :' , receiver_user_id);


if (!data.after.val())
{
console.log('A notification has been deleted :' , notification_id);
return null;
}

const DeviceToken = admin.database().ref(`/Users/${receiver_user_id}/device_token`).once('value');

return DeviceToken.then(result =>
{
const token_id = result.val();

const payload =
{
notification:
{
title: "New Swap Request",
body: `you have a new Swap Request, Please Check.`,
click_action: "com.app.muhammadgamal.swapy.Activities.ReceivedSwapRequest_NOTIFICATION_TASK"
}
};

return admin.messaging().sendToDevice(token_id, payload)
.then(response =>
{
return console.log('This was a notification feature.');
});
});
});









share|improve this question



























    1














    I am new to Android and programming and I am creating an app that receives messages from FCM and its work normally while the app in the Background, so I have added a FirebaseMessagingService class that receives the notifications in onMessageReceived method and followed out google docs but still the notification does not work while the app in the foreground state, I have followed every step and can't figure out where is the problem in my code as the Logs does not help me and I don't receive any bug expect this one which I don't know if its the source if the problem:
    Error while parsing timestamp in GCM event java.lang.NumberFormatException: s == null



    Here is my MyFirebaseMessagingService class



    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.BroadcastReceiver;
    import android.content.Intent;
    import android.support.v4.app.NotificationCompat;
    import android.support.v4.app.NotificationManagerCompat;

    import com.app.muhammadgamal.swapy.R;
    import com.google.firebase.messaging.RemoteMessage;

    public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

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

    String click_Action = remoteMessage.getNotification().getClickAction();


    String messageTitle = remoteMessage.getNotification().getTitle();
    String messageBody = remoteMessage.getNotification().getBody();


    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
    .setSmallIcon(R.drawable.ic_main_logo)
    .setContentTitle(messageTitle)
    .setContentText(messageBody)
    .setPriority(NotificationCompat.PRIORITY_DEFAULT);


    Intent intent = new Intent(click_Action);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(pendingIntent);


    int mNotificationID = (int)System.currentTimeMillis();
    NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    manager.notify(mNotificationID,mBuilder.build());

    }
    }


    and my Manifest File



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

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <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="@drawable/ic_main_logo"
    android:label="@string/app_name"
    android:roundIcon="@drawable/ic_main_logo"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
    android:name=".Activities.SignInActivity"
    android:theme="@style/AppTheme.NoActionBar">
    <intent-filter>
    <action android:name="android.intent.action.MAIN" />

    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>
    <activity
    android:name=".Activities.SignUpActivity"
    android:theme="@style/AppTheme.NoActionBar" />
    <activity
    android:name=".Activities.ProfileActivity"
    android:theme="@style/AppTheme.NoActionBar" />
    <activity
    android:name=".Activities.NavDrawerActivity"
    android:theme="@style/AppTheme.NoActionBar" />
    <activity
    android:name=".Activities.SwapCreationActivity"
    android:theme="@style/AppTheme.NoActionBar" />

    <activity android:name=".Activities.ReceivedSwapRequest">
    <intent-filter>
    <action android:name="com.app.muhammadgamal.swapy.Activities.ReceivedSwapRequest_NOTIFICATION_TASK"></action>
    <category android:name="android.intent.category.DEFAULT"></category>
    </intent-filter>
    </activity>

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

    </application>

    </manifest>


    and my index function



       'use strict'


    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);


    exports.sendNotification = functions.database.ref('/Notifications/{receiver_user_id}/{notification_id}')
    .onWrite((data, context) =>
    {
    const receiver_user_id = context.params.receiver_user_id;
    const notification_id = context.params.notification_id;


    console.log('We have a notification to send to :' , receiver_user_id);


    if (!data.after.val())
    {
    console.log('A notification has been deleted :' , notification_id);
    return null;
    }

    const DeviceToken = admin.database().ref(`/Users/${receiver_user_id}/device_token`).once('value');

    return DeviceToken.then(result =>
    {
    const token_id = result.val();

    const payload =
    {
    notification:
    {
    title: "New Swap Request",
    body: `you have a new Swap Request, Please Check.`,
    click_action: "com.app.muhammadgamal.swapy.Activities.ReceivedSwapRequest_NOTIFICATION_TASK"
    }
    };

    return admin.messaging().sendToDevice(token_id, payload)
    .then(response =>
    {
    return console.log('This was a notification feature.');
    });
    });
    });









    share|improve this question

























      1












      1








      1


      1





      I am new to Android and programming and I am creating an app that receives messages from FCM and its work normally while the app in the Background, so I have added a FirebaseMessagingService class that receives the notifications in onMessageReceived method and followed out google docs but still the notification does not work while the app in the foreground state, I have followed every step and can't figure out where is the problem in my code as the Logs does not help me and I don't receive any bug expect this one which I don't know if its the source if the problem:
      Error while parsing timestamp in GCM event java.lang.NumberFormatException: s == null



      Here is my MyFirebaseMessagingService class



      import android.app.NotificationManager;
      import android.app.PendingIntent;
      import android.content.BroadcastReceiver;
      import android.content.Intent;
      import android.support.v4.app.NotificationCompat;
      import android.support.v4.app.NotificationManagerCompat;

      import com.app.muhammadgamal.swapy.R;
      import com.google.firebase.messaging.RemoteMessage;

      public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

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

      String click_Action = remoteMessage.getNotification().getClickAction();


      String messageTitle = remoteMessage.getNotification().getTitle();
      String messageBody = remoteMessage.getNotification().getBody();


      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
      .setSmallIcon(R.drawable.ic_main_logo)
      .setContentTitle(messageTitle)
      .setContentText(messageBody)
      .setPriority(NotificationCompat.PRIORITY_DEFAULT);


      Intent intent = new Intent(click_Action);
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
      mBuilder.setContentIntent(pendingIntent);


      int mNotificationID = (int)System.currentTimeMillis();
      NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
      manager.notify(mNotificationID,mBuilder.build());

      }
      }


      and my Manifest File



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

      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
      <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="@drawable/ic_main_logo"
      android:label="@string/app_name"
      android:roundIcon="@drawable/ic_main_logo"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity
      android:name=".Activities.SignInActivity"
      android:theme="@style/AppTheme.NoActionBar">
      <intent-filter>
      <action android:name="android.intent.action.MAIN" />

      <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      </activity>
      <activity
      android:name=".Activities.SignUpActivity"
      android:theme="@style/AppTheme.NoActionBar" />
      <activity
      android:name=".Activities.ProfileActivity"
      android:theme="@style/AppTheme.NoActionBar" />
      <activity
      android:name=".Activities.NavDrawerActivity"
      android:theme="@style/AppTheme.NoActionBar" />
      <activity
      android:name=".Activities.SwapCreationActivity"
      android:theme="@style/AppTheme.NoActionBar" />

      <activity android:name=".Activities.ReceivedSwapRequest">
      <intent-filter>
      <action android:name="com.app.muhammadgamal.swapy.Activities.ReceivedSwapRequest_NOTIFICATION_TASK"></action>
      <category android:name="android.intent.category.DEFAULT"></category>
      </intent-filter>
      </activity>

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

      </application>

      </manifest>


      and my index function



         'use strict'


      const functions = require('firebase-functions');
      const admin = require('firebase-admin');
      admin.initializeApp(functions.config().firebase);


      exports.sendNotification = functions.database.ref('/Notifications/{receiver_user_id}/{notification_id}')
      .onWrite((data, context) =>
      {
      const receiver_user_id = context.params.receiver_user_id;
      const notification_id = context.params.notification_id;


      console.log('We have a notification to send to :' , receiver_user_id);


      if (!data.after.val())
      {
      console.log('A notification has been deleted :' , notification_id);
      return null;
      }

      const DeviceToken = admin.database().ref(`/Users/${receiver_user_id}/device_token`).once('value');

      return DeviceToken.then(result =>
      {
      const token_id = result.val();

      const payload =
      {
      notification:
      {
      title: "New Swap Request",
      body: `you have a new Swap Request, Please Check.`,
      click_action: "com.app.muhammadgamal.swapy.Activities.ReceivedSwapRequest_NOTIFICATION_TASK"
      }
      };

      return admin.messaging().sendToDevice(token_id, payload)
      .then(response =>
      {
      return console.log('This was a notification feature.');
      });
      });
      });









      share|improve this question













      I am new to Android and programming and I am creating an app that receives messages from FCM and its work normally while the app in the Background, so I have added a FirebaseMessagingService class that receives the notifications in onMessageReceived method and followed out google docs but still the notification does not work while the app in the foreground state, I have followed every step and can't figure out where is the problem in my code as the Logs does not help me and I don't receive any bug expect this one which I don't know if its the source if the problem:
      Error while parsing timestamp in GCM event java.lang.NumberFormatException: s == null



      Here is my MyFirebaseMessagingService class



      import android.app.NotificationManager;
      import android.app.PendingIntent;
      import android.content.BroadcastReceiver;
      import android.content.Intent;
      import android.support.v4.app.NotificationCompat;
      import android.support.v4.app.NotificationManagerCompat;

      import com.app.muhammadgamal.swapy.R;
      import com.google.firebase.messaging.RemoteMessage;

      public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {

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

      String click_Action = remoteMessage.getNotification().getClickAction();


      String messageTitle = remoteMessage.getNotification().getTitle();
      String messageBody = remoteMessage.getNotification().getBody();


      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
      .setSmallIcon(R.drawable.ic_main_logo)
      .setContentTitle(messageTitle)
      .setContentText(messageBody)
      .setPriority(NotificationCompat.PRIORITY_DEFAULT);


      Intent intent = new Intent(click_Action);
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
      mBuilder.setContentIntent(pendingIntent);


      int mNotificationID = (int)System.currentTimeMillis();
      NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
      manager.notify(mNotificationID,mBuilder.build());

      }
      }


      and my Manifest File



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

      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
      <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="@drawable/ic_main_logo"
      android:label="@string/app_name"
      android:roundIcon="@drawable/ic_main_logo"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity
      android:name=".Activities.SignInActivity"
      android:theme="@style/AppTheme.NoActionBar">
      <intent-filter>
      <action android:name="android.intent.action.MAIN" />

      <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
      </activity>
      <activity
      android:name=".Activities.SignUpActivity"
      android:theme="@style/AppTheme.NoActionBar" />
      <activity
      android:name=".Activities.ProfileActivity"
      android:theme="@style/AppTheme.NoActionBar" />
      <activity
      android:name=".Activities.NavDrawerActivity"
      android:theme="@style/AppTheme.NoActionBar" />
      <activity
      android:name=".Activities.SwapCreationActivity"
      android:theme="@style/AppTheme.NoActionBar" />

      <activity android:name=".Activities.ReceivedSwapRequest">
      <intent-filter>
      <action android:name="com.app.muhammadgamal.swapy.Activities.ReceivedSwapRequest_NOTIFICATION_TASK"></action>
      <category android:name="android.intent.category.DEFAULT"></category>
      </intent-filter>
      </activity>

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

      </application>

      </manifest>


      and my index function



         'use strict'


      const functions = require('firebase-functions');
      const admin = require('firebase-admin');
      admin.initializeApp(functions.config().firebase);


      exports.sendNotification = functions.database.ref('/Notifications/{receiver_user_id}/{notification_id}')
      .onWrite((data, context) =>
      {
      const receiver_user_id = context.params.receiver_user_id;
      const notification_id = context.params.notification_id;


      console.log('We have a notification to send to :' , receiver_user_id);


      if (!data.after.val())
      {
      console.log('A notification has been deleted :' , notification_id);
      return null;
      }

      const DeviceToken = admin.database().ref(`/Users/${receiver_user_id}/device_token`).once('value');

      return DeviceToken.then(result =>
      {
      const token_id = result.val();

      const payload =
      {
      notification:
      {
      title: "New Swap Request",
      body: `you have a new Swap Request, Please Check.`,
      click_action: "com.app.muhammadgamal.swapy.Activities.ReceivedSwapRequest_NOTIFICATION_TASK"
      }
      };

      return admin.messaging().sendToDevice(token_id, payload)
      .then(response =>
      {
      return console.log('This was a notification feature.');
      });
      });
      });






      java android node.js firebase firebase-cloud-messaging






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 10 at 7:57









      Ahmed Rabee

      307




      307
























          1 Answer
          1






          active

          oldest

          votes


















          1














          I discovered the problem, It was that I am using Android O and didn't set the Channel ID for the notification which is a must if you want to receive it on Android 8.0 or higher



          so here is the solution code



           private void createNotificationChannel() {
          // Create the NotificationChannel, but only on API 26+ because
          // the NotificationChannel class is new and not in the support library
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          CharSequence name = getString(R.string.channel_name);
          String description = getString(R.string.channel_description);
          int importance = NotificationManager.IMPORTANCE_DEFAULT;
          NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
          channel.setDescription(description);
          // Register the channel with the system; you can't change the importance
          // or other notification behaviors after this
          NotificationManager notificationManager = getSystemService(NotificationManager.class);
          notificationManager.createNotificationChannel(channel);
          }
          }





          share|improve this answer





















          • Where did you include the above code that solves the issue? Thanks
            – TonyL
            Nov 21 at 17:43










          • Inside MyFirebaseMessagingService class the class that is responsible for receiving the Notifications
            – Ahmed Rabee
            Nov 24 at 17:14













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237081%2fcant-receive-notifications-from-fcm-while-the-app-is-in-foreground-state%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          I discovered the problem, It was that I am using Android O and didn't set the Channel ID for the notification which is a must if you want to receive it on Android 8.0 or higher



          so here is the solution code



           private void createNotificationChannel() {
          // Create the NotificationChannel, but only on API 26+ because
          // the NotificationChannel class is new and not in the support library
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          CharSequence name = getString(R.string.channel_name);
          String description = getString(R.string.channel_description);
          int importance = NotificationManager.IMPORTANCE_DEFAULT;
          NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
          channel.setDescription(description);
          // Register the channel with the system; you can't change the importance
          // or other notification behaviors after this
          NotificationManager notificationManager = getSystemService(NotificationManager.class);
          notificationManager.createNotificationChannel(channel);
          }
          }





          share|improve this answer





















          • Where did you include the above code that solves the issue? Thanks
            – TonyL
            Nov 21 at 17:43










          • Inside MyFirebaseMessagingService class the class that is responsible for receiving the Notifications
            – Ahmed Rabee
            Nov 24 at 17:14


















          1














          I discovered the problem, It was that I am using Android O and didn't set the Channel ID for the notification which is a must if you want to receive it on Android 8.0 or higher



          so here is the solution code



           private void createNotificationChannel() {
          // Create the NotificationChannel, but only on API 26+ because
          // the NotificationChannel class is new and not in the support library
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          CharSequence name = getString(R.string.channel_name);
          String description = getString(R.string.channel_description);
          int importance = NotificationManager.IMPORTANCE_DEFAULT;
          NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
          channel.setDescription(description);
          // Register the channel with the system; you can't change the importance
          // or other notification behaviors after this
          NotificationManager notificationManager = getSystemService(NotificationManager.class);
          notificationManager.createNotificationChannel(channel);
          }
          }





          share|improve this answer





















          • Where did you include the above code that solves the issue? Thanks
            – TonyL
            Nov 21 at 17:43










          • Inside MyFirebaseMessagingService class the class that is responsible for receiving the Notifications
            – Ahmed Rabee
            Nov 24 at 17:14
















          1












          1








          1






          I discovered the problem, It was that I am using Android O and didn't set the Channel ID for the notification which is a must if you want to receive it on Android 8.0 or higher



          so here is the solution code



           private void createNotificationChannel() {
          // Create the NotificationChannel, but only on API 26+ because
          // the NotificationChannel class is new and not in the support library
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          CharSequence name = getString(R.string.channel_name);
          String description = getString(R.string.channel_description);
          int importance = NotificationManager.IMPORTANCE_DEFAULT;
          NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
          channel.setDescription(description);
          // Register the channel with the system; you can't change the importance
          // or other notification behaviors after this
          NotificationManager notificationManager = getSystemService(NotificationManager.class);
          notificationManager.createNotificationChannel(channel);
          }
          }





          share|improve this answer












          I discovered the problem, It was that I am using Android O and didn't set the Channel ID for the notification which is a must if you want to receive it on Android 8.0 or higher



          so here is the solution code



           private void createNotificationChannel() {
          // Create the NotificationChannel, but only on API 26+ because
          // the NotificationChannel class is new and not in the support library
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          CharSequence name = getString(R.string.channel_name);
          String description = getString(R.string.channel_description);
          int importance = NotificationManager.IMPORTANCE_DEFAULT;
          NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
          channel.setDescription(description);
          // Register the channel with the system; you can't change the importance
          // or other notification behaviors after this
          NotificationManager notificationManager = getSystemService(NotificationManager.class);
          notificationManager.createNotificationChannel(channel);
          }
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 10 at 22:51









          Ahmed Rabee

          307




          307












          • Where did you include the above code that solves the issue? Thanks
            – TonyL
            Nov 21 at 17:43










          • Inside MyFirebaseMessagingService class the class that is responsible for receiving the Notifications
            – Ahmed Rabee
            Nov 24 at 17:14




















          • Where did you include the above code that solves the issue? Thanks
            – TonyL
            Nov 21 at 17:43










          • Inside MyFirebaseMessagingService class the class that is responsible for receiving the Notifications
            – Ahmed Rabee
            Nov 24 at 17:14


















          Where did you include the above code that solves the issue? Thanks
          – TonyL
          Nov 21 at 17:43




          Where did you include the above code that solves the issue? Thanks
          – TonyL
          Nov 21 at 17:43












          Inside MyFirebaseMessagingService class the class that is responsible for receiving the Notifications
          – Ahmed Rabee
          Nov 24 at 17:14






          Inside MyFirebaseMessagingService class the class that is responsible for receiving the Notifications
          – Ahmed Rabee
          Nov 24 at 17:14




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237081%2fcant-receive-notifications-from-fcm-while-the-app-is-in-foreground-state%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          Academy of Television Arts & Sciences

          L'Équipe

          1995 France bombings