1

I have integrated FCM in my app. Whenever app is in background, no fcm message is received. I have tried both notification type and data type messages. Even notification messages are not displayed in notification tray. They are just lost!

Please help me out where I am going wrong. I have followed everything as per documentation and have been researching on this for a whole week.

My Manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application ....>    
<service
        android:name=".MyFirebaseMessagingService"
        android:exported="true"
        android:enabled="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
</application>

My Firebase messaging service:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    SharedPreferences sharedPref;

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message"));
        }


        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
    }

    @Override
    public void onNewToken(String token) {
        sendRegistrationToServer(token);
    }

    private void sendRegistrationToServer(String token) {
    //Sending handled here
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String title, String messageBody) {
        Intent intent = new Intent(this, UserHomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("title", title);
        intent.putExtra("message", messageBody);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 273, intent,
                PendingIntent.FLAG_ONE_SHOT);

        //String channelId = getString(R.string.default_notification_channel_id);
        String channelId = "Sandeep123";
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setContentTitle(title)
                        .setSmallIcon(R.mipmap.ic_launcher_foreground_new)
                        .setColorized(true)
                        .setColor(Color.BLUE)
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setVisibility(VISIBILITY_PUBLIC)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    getString(R.string.channel_name),
                    NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }

        notificationManager.notify(createID(), notificationBuilder.build());
    }

    public int createID() {
        Date now = new Date();
        int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.US).format(now));
        return id;
    }
}

I have added both my debug and release SHA-1 in firebase console. I dont know where else i can be going wrong. It works on all devices when app is active. But it does not work at all when app is in background.

*------------Update - server side code

function sendGcmNotification($amountAdded, $tok,$des){
    define( 'API_ACCESS_KEY', '***' );
     $title = "Rs.".$amountAdded." added as credit";
     $notificationMsg = "***";
    //$token = array();
    //$token[] = $tok;
     $msg =
 [
    'message'   => $notificationMsg,
    'title'   => $title
 ];

 $android = ["priority"=>"high"];
 $fields = 
 [
    'to'  => $tok,
    'data'      => $msg,
    'time_to_live' => 900,
    'priority' => 10,
    'android' => $android
 ];

 $headers = 
 [
   'Authorization: key=' . API_ACCESS_KEY,
   'Content-Type: application/json'
 ];

 $ch = curl_init();
 curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
 curl_setopt( $ch,CURLOPT_POST, true );
 curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
 curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
 curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
 curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
 $result = curl_exec($ch );
  curl_close( $ch );
 echo $result;

}

The Log cat Log is as follows:

2019-01-24 11:14:08.310 1541-1578/? W/ActivityManager: Background start not allowed: service Intent { act=com.google.firebase.MESSAGING_EVENT pkg=in.dailydelivery.dailydelivery cmp=in.dailydelivery.dailydelivery/.MyFirebaseMessagingService (has extras) } to in.dailydelivery.dailydelivery/.MyFirebaseMessagingService from pid=26445 uid=10210 pkg=in.dailydelivery.dailydelivery 2019-01-24 11:14:08.311 26445-26445/? 
E/FirebaseInstanceId: Error while delivering the message: ServiceIntent not found

Please help me out. Sandeep.

  • Can you check logcat if the notification has been received.? – Hemil Kumbhani Jan 24 '19 at 05:04
  • 2019-01-24 11:14:08.310 1541-1578/? W/ActivityManager: Background start not allowed: service Intent { act=com.google.firebase.MESSAGING_EVENT pkg=in.dailydelivery.dailydelivery cmp=in.dailydelivery.dailydelivery/.MyFirebaseMessagingService (has extras) } to in.dailydelivery.dailydelivery/.MyFirebaseMessagingService from pid=26445 uid=10210 pkg=in.dailydelivery.dailydelivery 2019-01-24 11:14:08.311 26445-26445/? E/FirebaseInstanceId: Error while delivering the message: ServiceIntent not found. – Sandeep Mukundan Jan 24 '19 at 05:45

3 Answers3

0

For FCM to deliver the message to app in foreground/background to create notification on notification bar the message format being send from app server should match the following format, please note Notification Message won't receive any callback when app is background, only Data message will receive

Notification Message format:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"great match!"
    }
  }
}

Data message:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "data":{
      "Nick" : "Mario",
      "body" : "great match!",
      "Room" : "PortugalVSDenmark"
    }
  }
}

Refer below link for more details https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message

For fcm to deliver the push notification when device is locked or in background, the message from app server should have the following tags

{
   ....
   "android": {"priority":"high"},
   "priority": 10,
   ....
}

Refer below for more details https://firebase.google.com/docs/cloud-messaging/concept-options#setting-the-priority-of-a-message

  • Pls see the log cat Log i have attached in my comments to the question. Message is delivered when the app is recently closed. But after a while of inactivity, the above Log is observed. Pls help me out – Sandeep Mukundan Jan 24 '19 at 05:47
  • Please check the below link https://stackoverflow.com/questions/46117554/firebasemessagingservice-crashes-on-android-o-due-to-background-execution-limits – Jitheesh S Khan Jan 26 '19 at 21:33
0

Messages with both notification and data payload, when received in the background. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

Handling Messages: Receive messages in an Android app

djo
  • 193
  • 8
-1

You need to declare the service in the application tag of your Manifest.

see this sample code.

To know more, please check this guide.

n.sil
  • 1
  • 2
  • Hi... The service is in application tag only..I had cut only the required part and put it here.. thanks... I have updated in question. I do receive the notification when app is active. I dont receive in background.. that is the issue. – Sandeep Mukundan Jan 24 '19 at 06:06
  • maybe you've missed out some implementation on the MessagingService, try to cross check your implementation on Firebase sample project https://github.com/firebase/quickstart-android/tree/master/messaging – n.sil Jan 24 '19 at 08:27