Android Question Firebase Notification Content not available in background

ZenWhisk

Member
Licensed User
Longtime User
Can anyone help me?

I have been playing with the firebase notification example from Erel.

It works perfectly, that is, I always get a notification.

However, the content of the notification is not available if the app was in background.

For example if my message body says 'Hello' and my app is currently in the foreground. Then I get a notification and when I click on it, the content 'Hello' is placed in the label1.

But, if my app is not in the foreground, then I still get the notification, but when I touch it, the activity starts but not knowing what the content is.

Here is the service...

B4X:
#Region  Service Attributes
    #StartAtBoot: True
   
#End Region

Sub Process_Globals
   Private fm As FirebaseMessaging
   Public notificationCount As Int=0
End Sub

Sub Service_Create
   fm.Initialize("fm")
End Sub

Public Sub SubscribeToTopics
    'just commented out to test we can send to a token
   'fm.SubscribeToTopic("general") 'you can subscribe to more topics
End Sub
Public Sub SubscribeToTopic(topic As String)
   fm.SubscribeToTopic(topic) 'you can subscribe to more topics
End Sub
public Sub token
    CallSubDelayed2(Main,"showtoken",fm.Token)
End Sub
Sub Service_Start (StartingIntent As Intent)
   If StartingIntent.IsInitialized And fm.HandleIntent(StartingIntent) Then Return
End Sub

Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data: ${Message.GetData}"$)
    Dim n As Notification

    n.Initialize
    n.Icon = "icon"

    Dim contentToSend As String=Message.GetData.Get("body")
    n.SetInfo2( "M=" & Message.GetData.Get("title"), Message.GetData.Get("body"), contentToSend  , Main)
    n.Light=True
    n.Sound=True

    n.Notify(1 )
End Sub

Sub Service_Destroy

End Sub


This is the main Activity.

So, if my app is visible, and I send 'Hello', the notification appears and when I touch it, label1 is filled out with the message. (the content also appears in the notification)

But if my app is not visible, the notification appears, but no content when I touch it. (the content does not appear in the notification, just the app title)

B4X:
#Region  Project Attributes
    #ApplicationLabel: Test Firebase
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.

End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Private Label1 As Label
    Private lblToken As Label
    Private btnGetToken As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("layout1")
End Sub

public Sub showtoken(token As String)
    lblToken.Text=token
End Sub
Sub Activity_Resume
    Dim contents As String
    Dim in As Intent
    in = Activity.GetStartingIntent
    If in.HasExtra("Notification_Tag") Then
        contents=in.GetExtra("Notification_Tag")
        ToastMessageShow(contents,True) 'Will log the tag
        Label1.Text=contents
    End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub btnGetToken_Click
    CallSubDelayed(FirebaseMessaging,"token")
End Sub


Thank you for anybody pointing out where I've gone wrong.
 

ZenWhisk

Member
Licensed User
Longtime User
Thanks for the quick reply, I appreciate it.

No I'm using a URL (from Visual Basic). But I'm assuming that that is ok, because the message sent is always received by the mobile. It is just the content that is missing when the app is not active.

Here is the code, it always sends a notification, it is just that the content is not available when the app is in background.

B4X:
Private Sub Command1_Click(index As Integer)

   
    Dim objHTTP As Object
    Dim URL As String
    Dim authKey As String   'aka server key
    Dim body As String
    Dim token As String
   
    token = "cldW_EMfJs0:APA91bFDfuxmcQ_LutaOs6zjXJxA0PZk7VPlxr8onlQcr0EFfmBIqNar8-rIPNHbicVGJK-vIKLWXkiYpTgFrW6YIxpS21729Bx5LHyD4HTgjLbjBVagsTwbLj2N9bLP21ZaSXUk6KAP"

    authKey = MY AUTH KEY HERE
    body = "{""notification"":{""click_action"":""no.zenwhisk.Firebase.REQUEST""},""data"":{""title"":""Test Mobile"",""body"":""" & txtMessage.Text & """},""to"":""" & token & """}"""

    Debug.Print body
   
    Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    URL = "https://fcm.googleapis.com/fcm/send"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.setRequestHeader "Content-Type", "application/json"
    objHTTP.setRequestHeader "Authorization", "key=" & authKey
    objHTTP.send (body)
    Debug.Print objHTTP.responseText
   
End Sub
 
Upvote 0

ZenWhisk

Member
Licensed User
Longtime User
This is the reply from Firebase

B4X:
{"notification":{"click_action":"no.zenwhisk.Firebase.REQUEST"},"data":{"title":"Test Mobile","body":"foreground"},"to":"cldW_EMfJs0:APA91bFDfuxmcQ_LutaOs6zjXJxA0PZk7VPlxr8onlQcr0EFfmBIqNar8-rIPNHbicVGJK-vIKLWXkiYpTgFrW6YIxpS21729Bx5LHyD4HTgjLbjBVagsTwbLj2N9bLP21ZaSXUk6KAP"}"
{"multicast_id":8274753547667738179,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1506070605619871%85cc04e085cc04e0"}]}
 
Upvote 0

ZenWhisk

Member
Licensed User
Longtime User
It works perfectly with B4J, thank you, I will try and see what the difference in the request is.
I thought the difference was that the B4J demo sent by topic and I wanted to target one device with token, but the B4J worked with both topics and tokens.

Here I am sending one message to one phone only and it is ok
B4X:
Private Sub SendMessage(Topic As String, Title As String, Body As String)
    Dim Job As HttpJob
    Job.Initialize("fcm", Me)
   
    Dim token As String = "diqQLSmrejM:APA91bHSjh7u.............vGcnu0a0t"
    'Dim m As Map = CreateMap("to": $"/topics/${Topic}"$)
    Dim m As Map = CreateMap("to":  token )
    Dim data As Map = CreateMap("title": Title, "body": Body)
    m.Put("data": data)
    Dim jg As JSONGenerator
    jg.Initialize(m)
    Job.PostString("https://fcm.googleapis.com/fcm/send", jg.ToString)
    Job.GetRequest.SetContentType("application/json")
    Job.GetRequest.SetHeader("Authorization", "key=" & API_KEY)
End Sub
 
Upvote 0

ZenWhisk

Member
Licensed User
Longtime User
I have found the answer, but I don't understand it.

If I include a 'click_action' in the message then the behavior is as described in the original post, (title only if in background, title and body if foreground).
If I remove the 'click_action' part, then both the B4J and my VB sender work as desired. Here is my broken B4J script, remove the notif as map and m.put notification and it is ok.

(Just found out that I don't need the click_action anyway, what was I thinking)

B4X:
Private Sub SendMessage(Topic As String, Title As String, Body As String)
    Dim Job As HttpJob
    Job.Initialize("fcm", Me)

    Dim token As String = "diqQLSmrejM:APA91bHSjh7uA-b44FPJT7ThsmpYneynNjE9MshJu5drImiGYzXvCcHVRpE8Q7o-Jrogd3HvYXxiI2LdKTmFjP................"
    'Dim m As Map = CreateMap("to": $"/topics/${Topic}"$)
    Dim m As Map = CreateMap("to":  token )
    Dim data As Map = CreateMap("title": Title, "body": Body)
    m.Put("data": data)

    'If this notification is included, the body is not shown
    Dim notif As Map=CreateMap("click_action":"no.zenwhisk.Firebase.REQUEST")
    m.Put("notification",notif)
    'end of notification part

    Dim jg As JSONGenerator
    jg.Initialize(m)
    Job.PostString("https://fcm.googleapis.com/fcm/send", jg.ToString)
    Job.GetRequest.SetContentType("application/json")
    Job.GetRequest.SetHeader("Authorization", "key=" & API_KEY)
End Sub
 
Last edited:
Upvote 0
Top