Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

quickstart-android messaging app doesn't receive data messages in background #89

Closed
2ndGAB opened this issue Jul 18, 2016 · 79 comments
Closed
Assignees

Comments

@2ndGAB
Copy link

2ndGAB commented Jul 18, 2016

Step 1: Are you in the right place?

  • Issues related to the code in this repository.

Step 2: Describe your environment

  • Android device: Asus Nexus 7 wifi
  • Android OS version: 6.0.1
  • Google Play Services version: 3.0.0
  • Firebase/Play Services SDK version: 9.2.1

But I cannot get it working on Nexus 7 LTE 6.0.1 or Samsung GT-9295 5.0.1 as well.

Step 3: Describe the problem:

I send the following message with Advanced REST Client, the message is sent successfully, but is only received in foreground and not when the application is in background.

{
    "to" : "egu9jGiMcew:APA91bFv2RewdzlrC4Q0 ... dYZgv91oZVfTtrfAojLMKZZmEURvbq-aA2",
    "data": {
        "title": "Title test",
        "msg": "Text of the test",
        "code": 2
    },
    "delay_while_idle" : false,
    "priority" : "high",
    "content_available" : true
}

Steps to reproduce:

  1. Build the quickstart-android project
  2. Execute the messaging app
  3. Send it a data message when the application is in background

Observed Results:

  • In my case, the message given above is not received. Is there any mistake in it?

  • It seems that the message is received by the device as I see the following messages:

    07-18 15:28:34.371 3068-3068/? W/GCM-DMM: broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000000 pkg=com.google.firebase.quickstart.fcm (has extras) }
    

Expected Results:

  • The message should be received and generate a notification the application is in foreground or in background.

Relevant Code:

My FirebaseMessagingService is:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // [START_EXCLUDE]
        // There are two types of messages data messages and notification messages. Data messages are handled
        // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
        // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
        // is in the foreground. When the app is in the background an automatically generated notification is displayed.
        // When the user taps on the notification they are returned to the app. Messages containing both notification
        // and data payloads are treated as notification messages. The Firebase console always sends notification
        // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
        // [END_EXCLUDE]

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        Log.i(TAG, "From: " + remoteMessage.getFrom());
        Log.i(TAG, "Notification Message Body: " + remoteMessage.getData());

        sendNotification("FCM message received");

        // 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.
    }
    // [END receive_message]

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String messageBody) {
        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_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .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());
    }
}
@kroikie
Copy link
Contributor

kroikie commented Jul 18, 2016

  1. Could you clarify how you are placing the app into the background? Eg: Are you tapping the device's home button?
  2. I'm assuming that when you say "Advanced REST Client" you are referring to the FCM REST API. If this is not the case please state more clearly.
  3. In your description of your environment you indicate a Nexus 7 wifi, then you say you are not able to get things working on the Nexus 7 LTE and the Samsung GT-9295

Note: The error you are seeing is usually associated with an application that has been forced stopped in which case it cannot respond to incoming notifications. However if you are getting this error without the application being forced stopped then it will require some further investigation.

@jtushar53 your input here would also be appreciated, if this is indeed a duplicate of your background issue.

@anantshah93
Copy link

I have same problem... cannot able to handle notification when app is in background. It is handled by system tray.

@2ndGAB
Copy link
Author

2ndGAB commented Jul 19, 2016

Hello,

  1. I tap the recent apps button then swipe the application out of the recent application list
    I currently have an application published which perfectly receives GCM/FCM messages in this state via onMessageReceive().
  2. I mean Google Advanced REST client which sends the message to https://fcm.googleapis.com/fcm/send
  3. Yes that's not a device or OS version specific issue.

The message I talk about W/GCM-DMM... is displayed in the log window just after I send a message to the device and everytime I send it to the device.

For example, I just sent it 3 times to the device for demo and I get the following display in logcat:

07-19 08:21:14.691 3068-3068/? W/GCM-DMM: broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000000 pkg=com.google.firebase.quickstart.fcm (has extras) }
07-19 08:21:16.480 3068-3068/? W/GCM-DMM: broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000000 pkg=com.google.firebase.quickstart.fcm (has extras) }
07-19 08:21:18.934 3068-3068/? W/GCM-DMM: broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000000 pkg=com.google.firebase.quickstart.fcm (has extras) }

So I don't think my application has been stopped three times successively but I think that the system cannot call the application for any reason. Does what was called receiver in GCM and now handled by the library still works anymore as expected?

I also see that when I tap on the recent apps button, the following message is displayed:

07-19 08:48:57.656 32267-32267/com.my.example D/FirebaseApp: Notifying background state change listeners.

But to be honest, I wonder if the problem only comes from FCM because if I start from my own project which worked few weeks ago and rebuild it, I cannot get it working anymore. But I had many updates suggested by Android through the studio. I currently use Studio 2.1.2, build tools 24.0.0

What really disturb me is the blur about this functionality everywhere including in the doc as if the ability to send data messages to a background/stopped (as you want) application was just discovered last night!
But almost all applications such as client mail, news, etc..., work like that no??

@jtushar53
Copy link

jtushar53 commented Jul 19, 2016

Hii,

for me tested other devices inlcuding Moto G edition and One Plus 2 it is working and on Mi5 it is not working, was getting same error.

Updated:
@kroikie application was not force close just swiped away from recents tray, also if i just press home button(app is minimise) it i am able to see notification in notification tray.

After googling a bit looks like lots of mi5 users are getting this issue from http://en.miui.com/thread-268224-1-1.html and http://en.miui.com/thread-272403-1-1.html , tried that but no luck.

@kroikie
Copy link
Contributor

kroikie commented Jul 19, 2016

This error is seen when your application has been forced stopped.

Using the command:
adb shell dumpsys package | grep stopped

If you get the result:
User 0: installed=true hidden=false stopped=false notLaunched=false enabled=0
Then since stopped is false your app should get the notification. If however your result is:
User 0: installed=true hidden=false stopped=true notLaunched=false enabled=0
Then since stopped is true your app cannot be started to handle the incoming message.

Could you check if when you remove the app from the recents list or just pause the app by hitting the home button, what the status of your app is? stopped=true or stopped=false?

The expectation is that when you swipe an app from recents the stopped value should still be false, but some launchers are not adhering to this, so if you can confirm the status of your app we can narrow down the issue.

@2ndGAB
Copy link
Author

2ndGAB commented Jul 22, 2016

Hello @kroikie
Sorry for the late reply.
The command
adb shell dumpsys package | grep stopped

tells me the following message, the application running or not:

Can't find service: com.google.firebase.quickstart.fcm

For information, when I put your application in background, I get the following log:

                                                    --------- beginning of system
07-22 12:28:00.591 671-745/? I/ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10200000 cmp=com.android.launcher/com.android.launcher2.Launcher} from uid 10024 on display 0
07-22 12:28:00.630 671-3321/? I/ActivityManager: Killing 17165:com.google.firebase.quickstart.fcm/u0a293 (adj 9): remove task
07-22 12:28:00.656 671-31254/? D/GraphicsStats: Buffer count: 4
07-22 12:28:00.656 671-745/? I/WindowState: WIN DEATH: Window{2349355 u0 com.google.firebase.quickstart.fcm/com.google.firebase.quickstart.fcm.MainActivity}
07-22 12:28:01.011 745-745/? W/Binder_2: type=1400 audit(0.0:13166): avc: denied { ioctl } for path="socket:[2808607]" dev="sockfs" ino=2808607 ioctlcmd=7704 scontext=u:r:system_server:s0 tcontext=u:r:system_server:s0 tclass=unix_stream_socket permissive=0
07-22 12:28:01.011 745-745/? W/Binder_2: type=1400 audit(0.0:13167): avc: denied { ioctl } for path="socket:[2808607]" dev="sockfs" ino=2808607 ioctlcmd=7704 scontext=u:r:system_server:s0 tcontext=u:r:system_server:s0 tclass=unix_stream_socket permissive=0
07-22 12:28:01.579 3723-3958/? W/OpenGLRenderer: Incorrectly called buildLayer on View: ShortcutAndWidgetContainer, destroying layer...
07-22 12:28:01.579 3723-3958/? W/OpenGLRenderer: Incorrectly called buildLayer on View: ShortcutAndWidgetContainer, destroying layer...
07-22 12:28:01.660 17340-17340/? D/AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 2000 <<<<<<
07-22 12:28:01.669 17340-17340/? D/AndroidRuntime: CheckJNI is OFF
07-22 12:28:01.707 27646-27659/? D/==FindMyPhone==: 1469183281707
07-22 12:28:01.752 17340-17340/? D/ICU: No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
07-22 12:28:01.819 17340-17340/? I/Radio-JNI: register_android_hardware_Radio DONE
07-22 12:28:01.857 17340-17340/? D/AndroidRuntime: Calling main entry com.android.commands.am.Am
07-22 12:28:01.860 671-745/? I/ActivityManager: Force stopping com.google.firebase.quickstart.fcm appid=10293 user=0: from pid 17340
07-22 12:28:01.865 17340-17340/? D/AndroidRuntime: Shutting down VM
07-22 12:28:01.867 201-201/? D/NuPlayerDriver: stop(0xb3d2b6c0)
07-22 12:28:01.867 201-201/? D/NuPlayerDriver: notifyListener_l(0xb3d2b6c0), (8, 0, 0)
07-22 12:28:01.869 3032-2494/? W/MessageQueue: Handler (android.media.MediaPlayer$EventHandler) {2d81fea} sending message to a Handler on a dead thread
                                               java.lang.IllegalStateException: Handler (android.media.MediaPlayer$EventHandler) {2d81fea} sending message to a Handler on a dead thread
                                                   at android.os.MessageQueue.enqueueMessage(MessageQueue.java:543)
                                                   at android.os.Handler.enqueueMessage(Handler.java:631)
                                                   at android.os.Handler.sendMessageAtTime(Handler.java:600)
                                                   at android.os.Handler.sendMessageDelayed(Handler.java:570)
                                                   at android.os.Handler.sendMessage(Handler.java:507)
                                                   at android.media.MediaPlayer.postEventFromNative(MediaPlayer.java:2988)
07-22 12:28:01.869 201-698/? D/NuPlayerDriver: reset(0xb3d2b6c0)
07-22 12:28:01.876 201-17250/? W/AMessage: failed to post message as target looper for handler 0 is gone.
07-22 12:28:01.879 201-17250/? D/NuPlayerDriver: notifyResetComplete(0xb3d2b6c0)

How can I help you more?
Didi you verified if you are able to send message to your quickstart-android messaging app from your side?

@kroikie
Copy link
Contributor

kroikie commented Jul 22, 2016

@2ndGAB Thanks for the logcat info, looks like the fcm sample is being stopped when it is being sent to the background.

07-22 12:28:01.860 671-745/? I/ActivityManager: Force stopping com.google.firebase.quickstart.fcm appid=10293 user=0: from pid 17340

I'm not sure why Activity Manager is killing the sample app when you put it in a background state. This is not expected behaviour, what device are you trying this one? Some devices have restrictions on what applications can be run in the background, I'm wondering if your device is stopping some apps when swiped from recents and not others.

@2ndGAB
Copy link
Author

2ndGAB commented Jul 23, 2016

Hi @kroikie
I tried on a Nexus 7 6.0.1
So I tried on a GT-9295 5.0.1 and I get the same result:

07-23 20:16:34.620 803-1408/? I/ActivityManager: Force stopping com.google.firebase.quickstart.fcm appid=10317 user=0: from pid 7231
07-23 20:16:34.620 803-1408/? I/ActivityManager:   Force stopping service ServiceRecord{3cada6f8 u0 com.google.firebase.quickstart.fcm/.MyFirebaseMessagingService}

And these are the same devices I used for months to test my apps.
If the Nexus has been regularly updated, this is not the question of the GT9295/5.0.1 so no reason to doubt on them.

that's really incredible.

I tried to rebuild an old working project of mine with sdk 23, GCM 8.4.0, java 1.7, so the environment I got working project with and I cannot get a working application anymore!

The only differnece I see now is the version of Android-studio/gradle.

Could please tell me if you build working projects with the last development environment updates???

@2ndGAB
Copy link
Author

2ndGAB commented Jul 24, 2016

THAT'S COMPLETELY INCREDIBLE

I've reisntalled Android Studio 1.5 bundle 141.2422023, sdk 23.0.3, java jdk1.7.0_79 and rebuilt your application.

The result is amazing. I don't have the Force Stopping message anymore when I put the application in background.

07-24 12:00:10.409 671-3321/? I/ActivityManager: Killing 11067:com.google.firebase.quickstart.fcm/u0a297 (adj 9): remove task
07-24 12:00:10.425 671-31254/? D/GraphicsStats: Buffer count: 4
07-24 12:00:10.425 671-31254/? I/WindowState: WIN DEATH: Window{996cbf7 u0 com.google.firebase.quickstart.fcm/com.google.firebase.quickstart.fcm.MainActivity}

And, it correctly receives and processes the data message in background

messaging app has been successfully rebuilt under Studio 1.5.2 with sdk 24, buildtools 24.0.0, and java 1.8.0_92

Please Please Pleasssssssseeeeeeeee tell me what's wrong !!!!!!

@kroikie
Copy link
Contributor

kroikie commented Jul 25, 2016

@2ndGAB thanks for the information, we do test our samples against the latest developer environments. I don't think that you are doing anything wrong here, it is very unusual what you are experiencing. I'm looking into it and will reply here with more. If you can, in the meantime, use AS 1.5.2.

@kroikie
Copy link
Contributor

kroikie commented Jul 25, 2016

Hi @2ndGAB there should be no change affecting the build between AS 1.5 and 2.1, could you confirm that you are not changing anything in the messaging quickstart? As in git status does not indicate any changes?

@2ndGAB
Copy link
Author

2ndGAB commented Jul 26, 2016

Hi @kroikie

OOOOOOOHHHHHHHHHHHHH YESSSSSSS!!!

Please have a look at my complete tests here

;-/

Regards,

@kroikie
Copy link
Contributor

kroikie commented Jul 26, 2016

Hi @2ndGAB couple things that you did not mention that might help:

After updating to 2.1.2:

  • were you using instant run?

  • did you clean the project?

  • did you try building the project from the command line? From the project directory:

    .\gradlew.bat :app:assembleDebug
    

@2ndGAB
Copy link
Author

2ndGAB commented Jul 26, 2016

Hi @kroikie

I deactivated instant run
Yes of course I cleaned/rebuilt many times/
But I didn't try to built it from command line.
I'll test it.

@Nicomalacho
Copy link

@2ndGAB hey did you fixed using AS 1.52 ?

@yucheng82
Copy link

CAN NOT receive a message when app is in background .
D/FirebaseApp: Notifying background state change listeners.
W/FirebaseMessaging: Unable to log event, missing measurement library

@2ndGAB
Copy link
Author

2ndGAB commented Aug 4, 2016

@yucheng82 First check if your device receives the message. Have a look at the logcat view and see if you receive such kind of messages:

mm-dd hh:ii:ss.nnn 1461-1461/? W/GCM-DMM: broadcast intent callback: result=CANCELLED forIntent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10000000 pkg=com.your.package (has extras) }

If no, maybe you don't use the right token.

If yes, please tell me what Android Studio version do you use.

@2ndGAB
Copy link
Author

2ndGAB commented Aug 4, 2016

@Nicomalacho Yes, definitively, as explained in detail here

@yucheng82
Copy link

@2ndGAB
My Android Studio is 2.1.2
message lib version:
com.google.firebase:firebase-messaging:9.2.1
My App token is ok .

When App is in foreground, Can receive FCM message:

D/MyFirebaseMsgService: From: 568540028909
D/MyFirebaseMsgService: Message Notification Body: Test Message

when in background CAN NOT receive Message and log is:
W/FirebaseMessaging: Unable to log event, missing measurement library

@yucheng82
Copy link

yucheng82 commented Aug 4, 2016

@2ndGAB
I find when APP is in background the FCM message is show by notification , not send message to my APP.
and when message is stop, noting is received.
How can i receive a message when app is in background and app is not running.
Thanks!

@2ndGAB
Copy link
Author

2ndGAB commented Aug 4, 2016

@yucheng82 so to see if you are facing the same problem as me, I can advise you to install Android Studio 1.5 from here.

Install it in a different folder so you keep 2.1.2 version.
You can specify a different sdk folder as well but in fact, the problem seems not coming from it.

Then you open your project in AS 1.5, without changing anything except if you swithed to Java 1.8. You will have to come back to 1.7.

Build your project and verify if now you receive data message in background...

Just a precision, I as working with data message only, not notification + data messages.
It seems it's what you use.

SO I tested this case, to see. If I'm right, the message should be :

{
  "to" : "ff7dwHxWZeE:APA91bFbzYFqFKUwYW...c_1TfunYKKYXcjiX5a",
   "notification": {
     "title": "just a test",
       "msg": "Just to verify"
   }
  "data": {
    "id": 19,
    "title": "Title test",
    "msg": "Text of the test",
    "code": 2,
    "infosUrl": "http://www.example.com",
    "longitude": 5.5,
    "latitude": 44.5,
    "eventLocation": "nowhere",
    "startDate": "31/07/2016 20:00",
    "endDate": "31/07/2016 22:00",
    "publishEndDate": "31/07/2016 20:00"
  }
  "content_available": true

}

In that case, when the application is in foreground, the application receives the data and when the application is in background, the system receives the notification.

So, to be sure that your application receives a data message in foreground AND in background, you need to send a DATA ONLY message like below:

{
  "to" : "ff7dwHxWZeE:APA91bFbzYFqFKUwYW...c_1TfunYKKYXcjiX5a",
  "data": {
    "id": 19,
    "title": "Title test",
    "msg": "Text of the test",
    "code": 2,
    "infosUrl": "http://www.example.com",
    "longitude": 5.5,
    "latitude": 44.5,
    "eventLocation": "nowhere",
    "startDate": "31/07/2016 20:00",
    "endDate": "31/07/2016 22:00",
    "publishEndDate": "31/07/2016 20:00"
  }
  "content_available": true

}

AFAIK, firebase console is not able to send such message, so you need to use the API mode with Google Advanced REST Client

@kroikie
Copy link
Contributor

kroikie commented Aug 4, 2016

@yucheng82 are you seeing this behaviour while running this sample? The warning you are mentioning about the missing measurement library should not prevent your app from receiving the message, that is just an indication that the automatic analytics provided by FCM will not work.

@2ndGAB I'm not convinced that the issue you are facing is due to an Android Studio version change, nor am I convinced that it is the issue being faced by @yucheng82. All Android Studio is doing is executing kicking off the build eg: ./gradlew :app:assembleDebug so there should not be anything in Android Studio itself that would affect the built APK of your application. I understand that it looks like Android Studio to you, and it may be, but I'd suggest trying building from the command line first and seeing if the issue persists.

@2ndGAB
Copy link
Author

2ndGAB commented Aug 5, 2016

@kroikie maybe but did you have a look at all tests I made here ?

And I installed the resulting package

adb -s xxxxxxx install .\app\build\outputs\apk\app-debug.apk

And the application receives data message in background.

  • Then I tried the same from Android Studio 2.1.2 terminal:

And I installed the resulting package

adb -s xxxxxxx install .\app\build\outputs\apk\app-debug.apk

And the application receives data message in background.

  • Then I tried to rebuild/install the app from Android Studio 2.1.2 ide

And the application DOES NOT receive data message in background.

Anyway, what I see from my side is the development environment installed by Android Studio and everything installed to build an application from the source code.
And the tests I made prove that something installed beside sdk, build-tools and Java modify the build.

How can we conclude something else?

There is something which would really interest me, this is to know if for you, sending a data message it to your messaging app really works when built from the latest dev env.
And if yes, why that point is not clearly explained in the doc?

@kroikie
Copy link
Contributor

kroikie commented Aug 5, 2016

@2ndGAB could you try uninstalling both versions of Android Studio and building from the command line like you have done here and see if the issue persists?

@2ndGAB
Copy link
Author

2ndGAB commented Aug 5, 2016

@kroikie but as you can see, that doesn't depend on sdk and build tools, so I'll be in one of the 2 first cases i.e. building from the command line and building from command line seems to work without problem.
Again, the problem comes if I launch the build from Android Studio 2.
So what do you expect to see more?

@fajaranugrah
Copy link

@privatejava can you help me how to create service running on FirebaseMessagingService?

@najeira
Copy link

najeira commented Sep 25, 2018

Why does not SDK call onMessageReceived in background? I can not find a reasonable reason.

@taranjeetsapra
Copy link

I found a related topic stating that we can send only notification messages through Firebase Console. If we want a datapayload message we can send that using Postman.

{
"to" : "token of client",
"collapse_key" : "type_a",
"data" : {
     "body" : "Test",
    "title": "Test",
    "message" : "Test"
}
 }

Please note that we have not sent "notification" here as we only want the payload to be given.
Reference: https://stackoverflow.com/questions/37454501/firebase-fcm-force-ontokenrefresh-to-be-called

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests