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

VTSinLincoln

Member
Licensed User
Longtime User
Try to send the message with high priority:
B4X:
Dim m As Map = CreateMap("to": $"/topics/${Topic}"$, "priority": "high")

From my experience notifications arrive quicker if the device is connected to a cellular network.

Thanks @Erel

I already send the messages with high priority (which does seem to make a difference). I'll try to start recording delivery time for different users (I know some of them are not on WiFi).

V

p.s. Fantastic product you've got here!
 

scsjc

Well-Known Member
Licensed User
Longtime User
Hello
is possible change the name from service FirebaseMessaging to another ????
 

ykucuk

Well-Known Member
Licensed User
Longtime User
Hello ,

i did follow steps but get error when app starting

Error is "firebasemessaging_service_create (java line: 150) java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist. "

Package name is same with firebase console project package name

any help
 

Daniel-White

Active Member
Licensed User
Longtime User
Hello ,

i did follow steps but get error when app starting

Error is "firebasemessaging_service_create (java line: 150) java.lang.IllegalStateException: FirebaseApp with name [DEFAULT] doesn't exist. "

Package name is same with firebase console project package name

any help

Did you check in firebase console the packname of you APP is added? and downloaded the new Json file to B4A root folder of your project.
 

Daniel-White

Active Member
Licensed User
Longtime User
How to avoid to bother our end users with Notifications. I am looking the reverse or PRIORITY HIGH and I did it.

Hello I did this test and work great and I would like to share here , checking the post #124 and this link https://firebase.google.com/docs/cloud-messaging/concept-options#lifetime

I did this change with "delay_while_idle" : True

Dim m As Map = CreateMap("to": $"/topics/${Topic}"$, "delay_while_idle" : True)

It is nice, I was looking to avoid to bother the end user, everybody are tire out about receive a lot notifications, whats APP, Email, Facebook and so on, hence, I am looking the FCM only send the notification when the user is using the phone, with "delay_while_idle" : True we can do it :D, when the phone go to idle or sleep, the notification will not arrive , until the phone is in use by end user and wake up the phone. :eek: and I guess it will help to save battery life too, because the FCM will not need to keep the TCP socket in the time. o_O

I was looking to avoid the end user uninstall my APP, my notifications can wait to read by end user. So? why bother him LoL
 

freedom2000

Well-Known Member
Licensed User
Longtime User
How to avoid to bother our end users with Notifications. I am looking the reverse or PRIORITY HIGH and I did it.

Hello I did this test and work great and I would like to share here , checking the post #124 and this link https://firebase.google.com/docs/cloud-messaging/concept-options#lifetime

I did this change with "delay_while_idle" : True

Dim m As Map = CreateMap("to": $"/topics/${Topic}"$, "delay_while_idle" : True)

It is nice,


Thanks for sharing this link.

On my side I will test the "collapse_key" to avoid to acknowledge several times the same alarm message in my App
 

scsjc

Well-Known Member
Licensed User
Longtime User
Hello,
I'm working on a chat proyect, with the FireBaseNotification, and its great to work, and work excellent, i have a Beta working with some users and all work great

but i don't know, some days, the service dont work (like today), Send a messages (i see the number from message) but not recive fm_MessageArrived , i change the users SuscribeToTopic, or create new but don't work.. :(

i don't know because i'm try the beta 4 days working excellent... all messages work to all users
-is possible the FireBaseNotification service stop some times????
-is more better work with another way ... like WebSocketClientLibrary ... to make a chat?

Thanks
 
Last edited:

vbmundo

Well-Known Member
Licensed User
Hi,

I has sent a Message from the Firebase Console , And I has received an Push Message, with the ICON, and NULL in TITTLE & NULL in MESSAGE

This is my Message

Fire-1.jpg


Fire-2.jpg


What's wrong ?

Regards
 

Daniel-White

Active Member
Licensed User
Longtime User
Hi,

I has sent a Message from the Firebase Console , And I has received an Push Message, with the ICON, and NULL in TITTLE & NULL in MESSAGE

This is my Message

Fire-1.jpg


Fire-2.jpg


What's wrong ?

Regards

I had the same result, nothing is wrong, try to send push notification directly from APP, the code example in this forum. you will see it will work fine. from the firebase console does not work 100%.
 

vbmundo

Well-Known Member
Licensed User
I had the same result, nothing is wrong, try to send push notification directly from APP, the code example in this forum. you will see it will work fine. from the firebase console does not work 100%.

NO no !!!

Look

you must include this 2 fields to the EREL code works

Fire-3.jpg
 

lkching7

Member
Licensed User
Longtime User
If I Have 10K Users, Is That Suitable Using "Topic" To Handle Push Notification Of Each User ?
For Example, Push Notification of Payment Make, Order Expire for Each User.
 

tznikos

Member
Licensed User
Longtime User
Hi,
Before use the firebasenotification the apk file was 1Mb, after the FCM the apk increased to 2.5MB,

It is normal that, why it is so large ?

Thanks
 
Last edited:

Sebastiano Canfora

Member
Licensed User
Hello i have a problem,
sorry for my english ....
When my app is in the background I get the notification normally,
when I'm using crashes and the log appears to me:
** Service (starter) Create **
** Service (starter) Start **

** Activity (main) Create, isFirst = true **
** Activity (main) Resume **

FirebaseMessaging not found.
java.lang.RuntimeException: java.lang.ClassNotFoundException: com.crmcentro.android.firebasemessaging
at anywheresoftware.b4a.objects.FirebaseNotificationsService.createIntent(FirebaseNotificationsService.java:44)
at anywheresoftware.b4a.objects.FirebaseNotificationsService.onMessageReceived(FirebaseNotificationsService.java:52)
at com.google.firebase.messaging.FirebaseMessagingService.zzo(Unknown Source)
at com.google.firebase.messaging.FirebaseMessagingService.zzn(Unknown Source)
at com.google.firebase.messaging.FirebaseMessagingService.zzm(Unknown Source)
at com.google.firebase.iid.zzb$2.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.ClassNotFoundException: com.crmcentro.android.firebasemessaging
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:324)
at java.lang.Class.forName(Class.java:285)
at anywheresoftware.b4a.objects.FirebaseNotificationsService.createIntent(FirebaseNotificationsService.java:42)
... 8 more
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.crmcentro.android.firebasemessaging" on path: DexPathList[[zip file "/data/app/com.crmcentro.android-1/base.apk"],nativeLibraryDirectories=[/data/app/com.crmcentro.android-1/lib/arm, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
... 12 more
Suppressed: java.lang.ClassNotFoundException: com.crmcentro.android.firebasemessaging
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
** Activity (main) Pause, UserClosed = true **

I do not understand what is wrong.

Tanks
 
Status
Not open for further replies.
Top