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,122
Last edited:

ChrisKrohne

Member
Licensed User
Longtime User
Hi, I´m trying to integrate firebase
Done yet:
Update SDK,download Google repository, Android Repository
Download google-services.json with package name
edit manifest as noted (Google Play Services Base, Firebase Base, Firebase Notifications)
add #AdditionalJar: com.google.android.gms : play-services

after compiling I got the error "Maven artifact not found: com.google.android.gms / play-services"
any ideas?
Thanks!!!!
 

ChrisKrohne

Member
Licensed User
Longtime User
Hi Manfred,
thanks for the reply.
I´m not sure. But as I understand I had to add #AdditionalJar: com.google.android.gms : play-services to the code because I add google play service base to the manifest. Without the #add tag, the compiler stop with the error "AndroidManifest.xml:29: error: Error: No resource found that matches the given name (at 'value' with value '@Integer/google_play_services_version')."
 

Douglas Farias

Expert
Licensed User
Longtime User
Erros on google analytics report
Exception java.lang.RuntimeException: Object should first be initialized (Intent).


anywheresoftware.b4a.AbsObjectWrapper.getObject (AbsObjectWrapper.java:50)
afina.baixo.id.firebasemessaging._service_start (firebasemessaging.java:162)
java.lang.reflect.Method.invoke (Method.java)
java.lang.reflect.Method.invoke (Method.java:372)
anywheresoftware.b4a.BA.raiseEvent2 (BA.java:169)
anywheresoftware.b4a.BA.raiseEvent (BA.java:153)
afina.baixo.id.firebasemessaging.handleStart (firebasemessaging.java:95)
afina.baixo.id.firebasemessaging.access$000 (firebasemessaging.java:8)
afina.baixo.id.firebasemessaging$1.run (firebasemessaging.java:76)
android.os.Handler.handleCallback (Handler.java:739)
android.os.Handler.dispatchMessage (Handler.java:95)
android.os.Looper.loop (Looper.java:145)
android.app.ActivityThread.main (ActivityThread.java:6917)
java.lang.reflect.Method.invoke (Method.java)
java.lang.reflect.Method.invoke (Method.java:372)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1404)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1199)


where is the error here? i m using the sample example of first post

maybe on this line?
B4X:
If fm.HandleIntent(StartingIntent) Then Return

thx
 
Last edited:

RjCl

Member
Licensed User
Longtime User
Everything works great and device is receiving the messages.

However, i only get the message if the phone is not locked, no message is received or anything to wake the phone.

I've changed the priority to high still nothing, nor anything from firebase console is received. Only get messages if phone awake.

Any ideas please ?
 

An Schi

Well-Known Member
Licensed User
This is a limitation of the firebase console.
To wake the phone you have to send the push via http request.
 

RjCl

Member
Licensed User
Longtime User
This is a limitation of the firebase console.
To wake the phone you have to send the push via http request.

Yes, its same if i use FCMPush.jar file to send a message, it still does not wake the phone. If i awake the phone, then still no message.

I only get the message if the phone is awake at the time of sending message.
 

RjCl

Member
Licensed User
Longtime User
Yes, its same if i use FCMPush.jar file to send a message, it still does not wake the phone. If i awake the phone, then still no message.

I only get the message if the phone is awake at the time of sending message.

Got it figured out, was some settings on my phone..... "Background Task Cleaner"

Anyone else have that in their phones ? Had to whitelist app(s) that can still run in the background and not get cleared with screen lock.

Do you any others have this ?
 

Leni Berry

Active Member
Licensed User
Longtime User
i cant get the message (Log($"Message data: ${Message.GetData}"$) is null) if i send message from web firebase console in Notification Menu, but the application can detect that the message arrives.

B4X:
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

web Firebase Console url :
https://console.firebase.google.com/project/xxxxxchat-xxxxx/notification/compose
 

victormedranop

Well-Known Member
Licensed User
Longtime User
I dont know whats happend.

use the exact code

but no received. no error on code.
b4j result

Waiting for debugger to connect...
Program started.
[jobname=fcm, success=true, username=
, password=, errormessage=, target=class b4j.example.main
, taskid=1, [EMAIL]req=anywheresoftware.b4h.okhttp.OkHttpClientWrapper$OkHttpRequest@11bc7ed[/EMAIL], tag=java.lang.Object@d84586
, httputils2service=null]
{"message_id":7015284701458445731}
Program terminated (StartMessageLoop was not called).
but nothing on logs.

can some one post and example.

Victor
 

johndb

Active Member
Licensed User
Longtime User
[SOLVED] What is the maximum size (number of bytes) permitted in the body of a Firebase message?

I apologize if this question has been previously asked but couldn't find an answer in SEARCH.

Thank you in advance,

John

[EDIT] I found the answer in the Firebase docs: "Data messages can have a 4KB maximum payload."
 
Last edited:

stari

Active Member
Licensed User
Longtime User
I get notifications, all is OK, but how i read notifications, if my application is in background and then a switch to foreground and wish to see previouslx notifications ?
 
Status
Not open for further replies.
Top