This library requires B4A v6+.
Firebase Cloud Messaging service is a layer above Google Cloud Messaging service.
It makes it simple to add support for push messages. Although it is not clear in their
documentation you don't need any additional server.
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.
2. Add a Service named FirebaseMessaging to your app (must be this name):
Sub Process_Globals
Private fm As FirebaseMessaging
End Sub
Sub Service_Create
fm.Initialize("fm")
End Sub
Public Sub SubscribeToTopics
fm.SubscribeToTopic("general") 'you can subscribe to more topics
End Sub
Sub Service_Start (StartingIntent As Intent)
If 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"
n.SetInfo(Message.GetData.Get("title"), Message.GetData.Get("body"), Main)
n.Notify(1)
End Sub
Sub Service_Destroy
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:
'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.
This is done with this request:
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)
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
Sub JobDone(job As HttpJob)
Log(job)
If job.Success Then
Log(job.GetString)
End If
job.Release
End Sub
API_KEY is the server key from:
OMG! I cant believe how easy to send push . It took me 2 minutes.. I hope yuou can implement all firebase soluitoons to ios too . Great Work Erel !!