B4A Library FirebaseNotifications - Push messages / Firebase Cloud Messaging (FCM)

Status
Not open for further replies.
Updated tutorial: https://www.b4x.com/android/forum/threads/b4x-firebase-push-notifications-2023.148715/


Clarification: The nice thing about FCM is that your app doesn't need to run in order to receive messages. The FirebaseMessaging receiver will be started by the OS when a new message arrives.
It is not a real issue, but if the user closed your app with a "force close" from the device settings then messages will not arrive, until the app is started again.
On some misbehaving devices, killing the app with a swipe will also cause messages not to arrive, until the app is started again.

Firebase Cloud Messaging service is a layer above Google Cloud Messaging service.
It makes it simple to add support for push messages.

Sending messages is done with a simple HTTP request. It is also possible to send message from the Firebase console, though it is not very useful and is actually more complicated than using the REST api.

1. The first step is to follow the Firebase integration tutorial:
https://www.b4x.com/android/forum/threads/integrating-firebase-services.67692/

Make sure to add the Notifications snippet.
You should also reference FirebaseAnalytics

2. Add a Receiver named FirebaseMessaging to your app (must be this name):
B4X:
Sub Process_Globals
    Private fm As FirebaseMessaging
End Sub

Private Sub Receiver_Receive (FirstTime As Boolean, StartingIntent As Intent)
    If FirstTime Then
        fm.Initialize("fm")
    End If
    fm.HandleIntent(StartingIntent)
End Sub

Public Sub SubscribeToTopics
    fm.SubscribeToTopic("general")
End Sub

Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data: ${Message.GetData}"$)
    Dim n2 As Notification
    n2.Initialize2(n2.IMPORTANCE_DEFAULT)
    n2.Icon = "icon"
    n2.SetInfo(Message.GetData.Get("title"), Message.GetData.Get("body"), Main)
    n2.Notify(1)  
End Sub

Sub fm_TokenRefresh (Token As String)
    Log("TokenRefresh: " & Token)
End Sub

fm_MessageArrived will be raised whenever a message is received. In this case we show a notification. You can do whatever you need.

We call SubscribeToTopics from the starter service to make sure that the app will be subscribed when it starts:
B4X:
'Starter service
Sub Process_Globals

End Sub

Sub Service_Create
   CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")
End Sub

Now we can send messages to a "topic" and all the subscribed devices will receive it.

See the code in the attached B4J tool. Note that the API_KEY should be set in the B4J code. It shouldn't be distributed in your app.

API_KEY is the server key from:

SS-2017-04-07_08.10.47.png


A simple non-ui B4J program is attached.

Note that messages sent from Firebase Console will not arrive in some cases. Use the B4J code to test it.
 

Attachments

  • B4J-SendingTool.zip
    1.1 KB · Views: 1,123
Last edited:

Douglas Farias

Expert
Licensed User
Longtime User
Hi, its possible send a message only to one app? by package name?

i tested this
"restricted_package_name": "teste.notifica.id"
but dont works (sended a message to all apps)

B4X:
Private Sub SendMessage(Topic As String, Title As String, Body As String)
   Dim Job As HttpJob
   Job.Initialize("fcm", Me)
   Dim m As Map = CreateMap("to": $"/topics/${Topic}"$)
   Dim data As Map = CreateMap("title": Title, "body": Body, "restricted_package_name": "teste.notifica.id")
   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;charset=UTF-8")
   Job.GetRequest.SetHeader("Authorization", "key=" & API_KEY)
End Sub


Sub JobDone(job As HttpJob)
   If job.Success Then
    
 
     Log(job.GetString)
  
  
   End If
   job.Release
End Sub

https://firebase.google.com/docs/cloud-messaging/http-server-ref#mensagens-descendentes-http-json

thx





Edit reSOLVED:
this is done using package name on subscribe
B4X:
fm.SubscribeToTopic("teste.notifica.id")
and later send with this package name
B4X:
SendMessage("teste.notifica.id","lala","lala")

thx
 
Last edited:

scsjc

Well-Known Member
Licensed User
Longtime User
Hello...
i don't know why... sometimes have error on FM_MESSAGEARRIED.... (null object refernce.... stringtoreal.parsedouble....???)

i'm try:
B4X:
Sub fm_MessageArrived (Message As RemoteMessage)
    If Not(Message.IsInitialized) Or Message.GetData = Null Or codigo.Nz(Message.GetData,"") = "" Then Return
    Log($"Message data: ${Message.GetData}"$)

the errors:
B4X:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
at java.lang.StringToReal.parseDouble(StringToReal.java:263)
at java.lang.Double.parseDouble(Double.java:301)
at myworldapp.wow.com.firebasemessaging._fm_messagearrived(firebasemessaging.java:335)
at java.lang.reflect.Method.invoke(Native Method)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:169)
at anywheresoftware.b4a.BA$1.run(BA.java:293)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
 
Last edited:

Carlos M. Cruz Malerva

Member
Licensed User
Longtime User
Hello
Good afternoon, I did all the steps for the application with Firebase Notifications and everything ok, I get notifications from the Firebase console, but not from FCMPush.b4j, the answer is fine. [jobname=fcm, success=true, username=
, password=, errormessage=, target=class b4j.example.main
, taskid=........]
Also from an application made in C# I do not receive them, where I get the following response:
{"Multicast_id": 7964210222556020299, "success": 1, "failure": 0, "canonical_ids": 0, "results": [{"message_id": "0: 1482971171027252% 0000000000000000"}]}.
It's wrong?.
Thank you

Edit:

Resolved, the topic had not been created.
Thank you.

I could also send it from VB.Net and C#
 
Last edited:

JohnnyHamburg

Member
Licensed User
Longtime User
Hello everybody,
I just started new with programming on b4a, and I could need some help.
I try to get this example working, but I receive these errors.
Thanks

*edit deleted nonsense picture
 

Attachments

  • johnb4afcm1.JPG
    johnb4afcm1.JPG
    124.3 KB · Views: 297
Last edited:

DonManfred

Expert
Licensed User
Longtime User
I just started new with programming on b4a, and I could need some help.
Some hints.

- ALWAYS start a NEW Thread in the questions-Forum if you have ANY new question.
- Post the Error AS TEXT (using Quote-Tag)
- Post code using CODE Tag or upload the project (IDE File-Export as ZIP)
 

JohnnyHamburg

Member
Licensed User
Longtime User
Some hints.

- ALWAYS start a NEW Thread in the questions-Forum if you have ANY new question.
- Post the Error AS TEXT (using Quote-Tag)
- Post code using CODE Tag or upload the project (IDE File-Export as ZIP)

Sorry, if I did it the wrong way, but, this is the Code from the first post from Erel, so I thoght it would belong to this Thread.

I only would like to know why B4A tells me that "main" and "firebasemassaging" (in the starter-module) are variables, that aren`t declared?

It doesn`t let me compile.
 

Derek Johnson

Active Member
Licensed User
Longtime User
Sorry, if I did it the wrong way, but, this is the Code from the first post from Erel, so I thoght it would belong to this Thread.

I only would like to know why B4A tells me that "main" and "firebasemassaging" (in the starter-module) are variables, that aren`t declared?

It doesn`t let me compile.

I'm sure that your question will be answered if you post a new thread as Don has suggested. This makes it much easier to find answers to specific questions. Just click on the "New Thread" button in the Android Questions forum.

upload_2017-1-10_12-25-57.png


Derek
 

scsjc

Well-Known Member
Licensed User
Longtime User
FirebaseNotifications v1.10 is released. It is attached to the first post.

It fixes an issue where messages can be lost if multiple messages arrive at the same time, for example after the device is booted or becomes online.
Thanks a lot for your great work !!!
 

JohnnyHamburg

Member
Licensed User
Longtime User
I have a problem with this new version of FCM. On Android 4.3 it doesn`t receive messages any more. On devices using Android 4.4 + it works. I'm very sure that it worked before. Can anybody confirm my point?
Can somebody please put the old library 1.0 for download here? I deleted it, so I can not test myself with the old on.
 

scsjc

Well-Known Member
Licensed User
Longtime User
I have a problem with this new version of FCM. On Android 4.3 it doesn`t receive messages any more. On devices using Android 4.4 + it works. I'm very sure that it worked before. Can anybody confirm my point?
Can somebody please put the old library 1.0 for download here? I deleted it, so I can not test myself with the old on.

Hello, I am currently using the new library in my app WALUCHAT, and I have not tested it in 4.3, I do not know if it works.
If you want you can install the app and test if the general room chat works.

regards
 

scsjc

Well-Known Member
Licensed User
Longtime User
Hello, I am currently using the new library in my app WALUCHAT, and I have not tested it in 4.3, I do not know if it works.
If you want you can install the app and test if the general room chat works.

regards

I'm try in 4.2.2 and WORK
 

JohnnyHamburg

Member
Licensed User
Longtime User
I'm try in 4.2.2 and WORK

Ok, thank You for your answer. I don't get it why it's not working. Maybe I use FCM different than you.

So again would anybody please upload the FirebaseMessaging v1.0.

Edit: Ok, Problems are gone after deinstallation and complete new.
 
Last edited:

Seneca

Active Member
Licensed User
Hi,

I am testing the code of message #1. The app receives the messages correctly while it's in foreground or in background. But if the messages are sent while the app is fully closed, when I run the app doesn't receive those pending messages. The messages are sent with the code B4J.

Why is this happening?

Best regards.
 
Status
Not open for further replies.
Top