FCM push notification not working when app is closed Android
Asked Answered
T

3

8

Ok so i have looked everywhere and I can't find an answer to this. I have implemented the push notification in my Android app and everything works fine while the app is alive (Foreground or background), however if I close the app I stop receiving notifications. Here is the php code where I send the notification.

public static function sendNotification($token){
    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array(
        'notification' => array("title" => "Test","body" => "Test Message","icon" => "default","sound" => "default"),
        "data" => "test message",
        'to' => $token
    );
    $headers = array(
        'Authorization:key = AIzaSyAKHM3MoMACjmeVK46TDg8-rTj1KoVjzWs',
        'Content-Type: application/json'
    );
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);                           
    curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
    $result = curl_exec($ch);
    if($result === FALSE) {
        throw new errorSendingNotification();
    }
    curl_close($ch);
    // Result returns this
    // {"multicast_id":8978533958735781479,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1468627796530714%7c0e4bee7c0e4bee"}]}
    return $result;
}
Tophus answered 16/7, 2016 at 0:11 Comment(4)
do you have a service for notifications in your app?Oversubtle
Possible duplicate of How to handle notification when app in background in firebaseEaseful
I am also facing problem with FCM, may I know please after getting the response like u mentioned in comment line, what to do with that responseTarpaulin
I am not creating any backend server for my app, just calling the api in my MainActivityTarpaulin
C
15

I had the same problem. And this helped me.

Please remove "notification" key from payload and provide only "data" key.

Application handles notification messages only if the app is in foreground but it handles data messages even if the application is in background or closed.

If the application is in the foreground onMessageReceived handle both data and notification messages. If the application is closed or in the background only data messages are delivered to onMessageReceived . notification messages are not delivered to onMessageReceived . So you can't customize your messages.

It would be better to remove notification key from payload.

Charlyncharm answered 9/8, 2016 at 11:55 Comment(5)
In this situation, you can override handleIntent in FirebaseMessagingService. when app is closed, this method will fireAcrosstheboard
I found that when the notification key is removed, the push notification stops working on iOS when the app is killed. Does anyone encounter this?Dela
@MajidSadeghi this works for me i close app now i can see logsAphrodite
@AmAnDroid: i know this is very old post. I am getting same issue, where after closing the app (not in forground and not in background) FCM notification stop working. i tired your step as you mentioned to remove notifiaction key from payload but that not helped. issue is as soon as, i kill/close the running app. i start getting return message - FirebaseAdmin.Messaging.FirebaseMessagingException: 'Requested entity was not found.' Any suggestion!!Salts
more error detail: Httpresponse {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Vary: X-Origin Vary: Referer Vary: Origin Vary: Accept-Encoding X-XSS-Protection: 0 X-Frame-Options: SAMEORIGIN X-Content-Type-Options: nosniff Alt-Svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000 Transfer-Encoding: chunked Accept-Ranges: none Cache-Control: private Date: Sun, 28 Jul 2024 20:47:41 GMT Server: scaffolding Server: on Server: HTTPServer2 Content-Type: application/json; charset=UTF-8 }}Salts
Q
1

One Solution is as AmAnDroid Gave.

2nd solution is: Unfortunately this was a limitation of Firebase Notifications in SDK 9.0.0-9.6.1. When the app is in the background the launcher icon is use from the manifest (with the requisite Android tinting) for messages sent from the console.

With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:

Add below code in menifest:

 <meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/com_facebook_button_send_icon_blue" />

    <meta-data android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/bt_blue_pressed" />

Body/Payload:

{ "notification": 
 {
   "title": "Your Title",
   "text": "Your Text",
   "click_action": "MAIN_ACTIVITY" // should match to your intent filter
 },
 "data": 
 {
   "keyname": "any value " //you can get this data as extras in your activity and this data is optional
 },
 "to" : "to_id(firebase refreshedToken)"
} 

After with this add below code(intent-filter) in your acivity to be called:

<activity
        android:name="MainActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="MAIN_ACTIVITY" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
 </activity>

Make sure your Body/Payload's "click_action": "MAIN_ACTIVITY" and intent-filter's android:name="MAIN_ACTIVITY" should match.

Quintic answered 25/1, 2017 at 5:27 Comment(2)
What exactly your issue is? @AjayPandyaQuintic
Let me try another way which i found rightnow on one blog of ravitamada otherwise i'll let you know here in detail or show you code if requiredClementclementas
S
0

Put this code in your startActivity (Which is calling when notification is clicked)

  val bundle = intent.extras
        if (bundle != null) {
            for (key in bundle.keySet()) {
                // Get the value associated with the key and log it
                val value = bundle.get(key)
                Log.e(TAG, "Key: $key, Value: $value")

            }
            //bundle must contain all info sent in "data" field of the notification
        }

Must put above code in Oncreate

Optional: You can also get the keys from here which you are sending in FCM

Socher answered 29/4, 2024 at 8:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.