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: 899
Last edited:

Bel

Member
Licensed User
Hi
In this push we dont need to google play service looklike gcm?
In gcm or c2dm if device rooted so push not send
 

coslad

Well-Known Member
Licensed User
Longtime User
When i load the Firebase Notification library ,it comes out this error :
"Maven artifact not found"
what does it mean ?
 

Attachments

  • errore.jpg
    errore.jpg
    7.9 KB · Views: 329

VTSinLincoln

Member
Licensed User
Longtime User
How do I get topic subscription to work on device start-up?

I've set the starter service to start at boot and installed the app then rebooted the device. I can see the starter service and the firebasemessaging service running in the device's Application Manager. However, it doesn't appear to have actually subscribed to my topic, as I don't get a notification when I subsequently send a message to the FCM API.

If I uninstall the app and rebuild it so the starter service doesn't start at boot, then install and run it, my topic subscription works as expected (i.e. I can send a message to the FCM API with the topic in the post request that causes a notification on my device).

Any suggestions gratefully accepted :)

Vaughan
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
"Maven artifact not found"
what does it mean ?
You need to install the two repositories: https://www.b4x.com/android/forum/threads/integrating-firebase-services.67692/

How do I get topic subscription to work on device start-up?
You don't need to do anything special. Once the app has subscribed to a topic it will remain subscribed until the app is uninstall. No need to start at boot.

Note that you need to run the app in Release mode in order to test it.
 

VTSinLincoln

Member
Licensed User
Longtime User
You don't need to do anything special. Once the app has subscribed to a topic it will remain subscribed until the app is uninstall. No need to start at boot.

Note that you need to run the app in Release mode in order to test it.

Thanks Erel

It works :)

I just have to be a bit more patient when the device restarts as it can take a few minutes for the notification to arrive.


V
 

ilan

Expert
Licensed User
Longtime User
WOW, this is amazing. it is really working :D
thank you very much @Erel!!!!

i have integrated Admob + Push Notification and it is working like a charm!! (please make it also for b4i)
 

driesvp

Member
Licensed User
Longtime User
I'm also facing problems with "Maven artifact..."
upload_2016-6-26_22-44-33.png


I added the manifest snippets for Google play, Firebase and notifications.
The repositories are installed.

upload_2016-6-26_22-43-21.png


Also, I created a Firebase Project.

What can be the problem?
 

ilan

Expert
Licensed User
Longtime User

ilan

Expert
Licensed User
Longtime User
so you copied those 3 snippets

'************ Google Play Services Base ************
'************ Firebase Base ************
'************ Firebase Notifications ************

have you created the json file and put it in the folder where the b4a file is located?

do you have any other attributes in you code?
 

shashkiranr

Active Member
Licensed User
Longtime User
Hi All,

Just one question. If i need to send a massage for just one selected device out of 100 devices, how can I do that?

Best,
SK
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
What can be the problem?
Are you sure that the IDE uses the correct Android SDK (Tools - Configure Paths)?

Just one question. If i need to send a massage for just one selected device out of 100 devices, how can I do that?
Either subscribe each device to a unique topic or use your own server with the token ids (see FirebaseMessaging.Token).
 

shashkiranr

Active Member
Licensed User
Longtime User
Hi Erel,

Thank you for the reply. I am saving individual tokens in the db. what is the format to send the messages using tokens.

Best,
SK
 

DonManfred

Expert
Licensed User
Longtime User
based on this i would try something like

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

shashkiranr

Active Member
Licensed User
Longtime User
based on this i would try something like

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

Thank you DonManfred.
 

aarroyo

Member
Licensed User
Longtime User
I have a problem , after initializing, do not assign me token and returns me the following error:

Error: Cannot run method from watch expression.
 

Attachments

  • Captura.PNG
    Captura.PNG
    7 KB · Views: 442

alimanam3386

Active Member
Licensed User
Longtime User
Hi

As far as I understand this library ( FirebaseNotification ) is just for push a notify to users , but how can I send a message to an user ? ( without app_key , because it is secrect key and we can't use it in the source code ( client side ))

Regards
 
Status
Not open for further replies.
Top