15

I am checking Firebase Cloud Messaging to send notification. Have implemented it already and its receiving notification when app is in open state. But if I close app, its no longer gives notification. Is there any solution for this.

Code:

WebRequest wRequest;
wRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
wRequest.Method = "post";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));

wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));

string postData = "{\"registration_ids\":[\"" + regIds + "\"], \"data\": "+ value +"}";

Byte[] bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;

Stream stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();

WebResponse wResponse = wRequest.GetResponse();

Messaging service-

public class MessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Map<String, String>  data = remoteMessage.getData();
        sendNotification(data);
    }

    public void showMessage(Map<String, String>  serverData) {
        Intent i = new Intent(this,MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentTitle(serverData.get("Title"))
                .setContentText(serverData.get("Message"))
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentIntent(pendingIntent);

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

        manager.notify(Integer.parseInt(serverData.get("ItemId")),builder.build());
    }

    private void sendNotification(Map<String, String>  serverData) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT);

        long[] pattern = {500,500,500,500,500};

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentTitle(serverData.get("Title"))
                .setContentText(serverData.get("Message"))
                .setAutoCancel(true)
                .setVibrate(pattern)
                .setLights(Color.BLUE,1,1)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(Integer.parseInt(serverData.get("ItemId")), notificationBuilder.build());
    }

}

Main activity-

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       FirebaseMessaging.getInstance().subscribeToTopic("test");
        FirebaseInstanceId.getInstance().getToken();
    }
}

Manifest-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="test.com.firebasenotify">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <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=".MessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".InstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

    </application>

</manifest>
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Anup Das Gupta
  • 772
  • 1
  • 7
  • 24
  • 1
    Show fcm listener class, and show the POST request you make to fcm – Tim Jun 16 '16 at 10:44
  • Updated messaging service, FCM post and main activity code – Anup Das Gupta Jun 16 '16 at 10:55
  • Do you receive the message in the onreceive at least? – Tim Jun 16 '16 at 10:57
  • yes I receive message on onMessageReceived when my app is open or at least running in the background and also get notification. If I close the app its not working. I should get notification if the app is closed too – Anup Das Gupta Jun 16 '16 at 10:59
  • Can u add the manifest as well – Tim Jun 16 '16 at 11:00
  • updated manifest also – Anup Das Gupta Jun 16 '16 at 11:04
  • Ok looks good. What do you mean if you say to "close" the app? Force stop? – Tim Jun 16 '16 at 11:08
  • Sorry for my lack of knowledge on mobile terminology. What I mean is if I restart my phone then all application will be closed. e.g. even if I have not opened facebook app, I will still get notification from facebook app – Anup Das Gupta Jun 16 '16 at 11:13
  • I cannot reproduce that. After I restart my phone I still receive messages of my app even if I don't open the app – Tim Jun 16 '16 at 11:17
  • even if I clear all app without restarting. It does not work for me. I need to keep it open or run in the background. I am using android version 4.4.4 – Anup Das Gupta Jun 16 '16 at 11:25
  • Is there any setting I am missing in firebase console – Anup Das Gupta Jun 16 '16 at 11:51
  • 4
    When the app is not running (or backgrounded), `onMessageReceived` will not be called for notifications. In such a situation Android should show a system notification (in the bar at the top) when the notification comes in. – Frank van Puffelen Jun 16 '16 at 13:28
  • If I kill app, no notification is displaying. Sot sure what is the issue – Anup Das Gupta Jun 17 '16 at 03:54
  • I am initialized FCM in MainActivity - onCreate. Logically thinking this method will get called once I open the APP. Is this the issue - when app is closed its not working? Is there any way I can call FCM initialization when app is installed or something like that. – Anup Das Gupta Jun 17 '16 at 04:12
  • You don't have to initialize FCM, since you're not using the topics – Tim Jun 17 '16 at 09:12
  • 1
    @Frank it will be called if there is no `notification` key in the POST payload – Tim Jun 17 '16 at 09:12
  • Can you please explain it little more. I am not able to make it work still if app is closed – Anup Das Gupta Jun 17 '16 at 09:18
  • @TimCastelijns correct, that's why I said "for notifications" ;-) – Frank van Puffelen Jun 17 '16 at 15:04
  • @Frank ah. My bad. Sometimes my eyes skip a couple of words.. – Tim Jun 17 '16 at 15:06
  • @AnupDasGupta i also facing same problem, but it is occur only when i lock my cell phone more than 5 to 10 min, then i doesn't get any notifications, but when i unlock it i instantly get those notifications no matter app is open or not. Did you find out why these problem arises in FCM ? – ULHAS PATIL Sep 20 '16 at 12:40
  • Did anyone get a fix for this issue? In my case, this issue is occurring in all devices having Android 5.1. Not happening in devices 7.0 above. Donno about 6 though. If the app is background then notification received, if it's closed completely then receives nothing. – Ari Mar 01 '17 at 11:37

5 Answers5

10

There was no issue with the code. I was using Mi note 4, and somehow it does not show notification in Mi4 when app is closed. I tested with other android device and its working fine.

Thanks to Tim Castelijns and Frank van Puffelen for participating in the conversation.

Anup Das Gupta
  • 772
  • 1
  • 7
  • 24
2

There's good solution and explanation about that issue here. You need to set high priority for notification to tell android react immediately, otherwise it takes couple of minutes to display received notification.

Dharman
  • 30,962
  • 25
  • 85
  • 135
slothdeboss
  • 29
  • 1
  • 5
0

I used Legacy Server Key instead of Server Key it had worked for me.

saigopi.me
  • 14,011
  • 2
  • 83
  • 54
-1

adding time_to_live key in your POST Payload will solve this problem.The value of this parameter must be a duration from 0 to 2,419,200 seconds, and it corresponds to the maximum period of time for which FCM stores and attempts to deliver the message. "time_to_live" : 3 Refer Firebase Docs

Ajith E R
  • 1
  • 2
-3

As per FCM docs onMessageReceived() won't be called when app is in the background. You should send a notification object on order to show it up in the system tray and when user clicks it the launcher activity will be open with data as extras with the intent. For payloads you should use data object. see docs and Receive Messages in an Android App

Sjd
  • 1,261
  • 1
  • 12
  • 11
  • 2
    if you see the code there no notification object. He is only sending data object – Nikhil Gaur Oct 27 '16 at 09:10
  • you need to send notification object as well. – Sjd Oct 27 '16 at 09:19
  • 2
    but if we will send notification object then it will not hit onMessageReceived and notification will be handled by android itself and will be displayed in notification tray (without your client app). And if we send without notification object but data object is there then it will always hit onMessageReceived. – Nikhil Gaur Oct 28 '16 at 05:21