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

Smee

Well-Known Member
Licensed User
Longtime User
Can you post a link to the code?

What is the problem? It is very simple to implement this solution and handle the message.
Can you post a link to the code?

What is the problem? It is very simple to implement this solution and handle the message.
Sorry Erel I did not make myself clear,

I am shortly going to be renewing my sub. I was looking at the Firebase messaging and because I am not able to write and test yet I was wondering what the difference was between the Java snippet for receiving messages and the same code written in B4A. It looks the same to me
Cheers
 

Smee

Well-Known Member
Licensed User
Longtime User
Sorry yes I meant the B4J and Thanks I thought it did not look any different from B4A
 

Mahesh Ramnathan

Member
Licensed User
Hi Erel,
I got following error while trying to implement FCM (Firebase Notification) as per the instruction given above.

Error :
B4A version: 6.31
Parsing code. (0.17s)
Compiling code. (0.33s)
Compiling layouts code. (0.01s)
Organizing libraries. Error
Maven artifact not found: com.google.firebase/firebase-messaging

I have installed following latest version
- Android Support Repository - 47
- Google Repository - 8
- Google Play Service -39

Also installed fresh Android-sdk on D Drive after un-installed from C Drive.

upload_2017-5-5_18-25-52.png
 

Attachments

  • upload_2017-5-5_18-24-24.png
    upload_2017-5-5_18-24-24.png
    15.5 KB · Views: 247

Mahesh Ramnathan

Member
Licensed User
Can you guide us how we can test firebase notificaiton ? How we can send scheduled push notification through dot net application ?
Incidentally, we are switching from a working setup of GCM+B4X over to Firebase
 
Last edited:

Ohanian

Active Member
Licensed User
Longtime User
Can you guide us how we can test firebase notificaiton ? How we can send scheduled push notification through dot net application ?
Incidentally, we are switching from a working setup of GCM+B4X over to Firebase

Hi,

Here's a sample vb.net code :

B4X:
Imports System.Net.Http
Imports System.Web.Script.Serialization
Imports Newtonsoft.Json
Imports System.Net.Http.Headers
Imports System.Text
Imports System.ComponentModel


Sub SendPush

   Dim sKey As String = String.Empty
   sKey = "YOUR_KEY"

   Dim HTTPClient As New HttpClient

    Const QUOTE = """"

    Dim sTopic As String = String.Empty

    Dim js As New JavaScriptSerializer()
    Dim Data As String = ""

Data = "{'priority':'high', 'to':'\/topics\/$TOPIC$','data':{'title':'$TITLE$','body':'$BODY$','id':'$ID$'}}".Replace("$TOPIC$", sTopic).Replace("$TITLE$", txtTitle.Text).Replace("$BODY$", txtBody.Text).Replace("$ID$", txtID.Value)

     Data = Data.Replace("'", QUOTE)

     Dim Request As New HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send")
     Request.Content = New StringContent(Data, System.Text.Encoding.UTF8, "application/json")

    HTTPClient.BaseAddress = New Uri("https://fcm.googleapis.com/fcm/send")
    HTTPClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("key", "=" & sKey)

    Dim result = HTTPClient.SendAsync(Request).Result
    Dim oResult = result.Content.ReadAsStringAsync
    If oResult.Result.Contains("message_id") Then
            MessageBox.Show("Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
    Else
           MessageBox.Show(oResult.Result, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If
    
end sub

BUT It’s not reliable (I don’t know why), use B4J code to send push.
 

biometrics

Active Member
Licensed User
Longtime User
I have a B4A and B4i app that needs notifications but it will be sent from a website running PHP.

Does anyone have PHP code to share to demonstrate how to send a notification to Firebase?

Also is Firebase the easiest way to send notifcations?
 

luke2012

Well-Known Member
Licensed User
Longtime User
It is possible to configure an App (for FCM test purpose only) without publish it on the Play Store?

I mean that the app will be installed on a Android (internet connected) device and registered within firebase console only ?
 

luke2012

Well-Known Member
Licensed User
Longtime User
Hi all,
How to implement / call the "SendMessage" code within a UI (desktop) B4J Application ?
 
Last edited:

An Schi

Well-Known Member
Licensed User
I just made two EditText for title and body and a button. In the button_click i pasted the send code given here and adjusted it to my keys. That's it...
Oh and don't forget to check the needed libraries.
 
Status
Not open for further replies.
Top