Android Question how to pass recieved firebase message to layout b4a

Makumbi

Well-Known Member
Licensed User
Good morning Members this is my code below when i click on the recieved firebase Message on My app the layout comes out but blank yet i wanted to pass that recieved message direct to the layout so that a person can easily read it . thanks in advance

B4X:
#Region  Service Attributes
    #StartAtBoot: False
   
#End Region

Sub Process_Globals
    Private fm As FirebaseMessaging
    Dim cursor1 As Cursor
End Sub

Sub Service_Create
    fm.Initialize("fm")
End Sub

Public Sub SubscribeToTopics
    'fm.SubscribeToTopic("general") 'you can subscribe to more topics
    'fm.SubscribeToTopic("No0781703474") 'you can subscribe to more topics
   
    cursor1 = Starter.SQL1.ExecQuery("SELECT phone AS Phone,Sex FROM Register")
    If cursor1.RowCount > 0 Then
        '    For i = 0 To cursor1.RowCount - 1
        cursor1.Position =0
        Dim Phoneg As String
        Phoneg = cursor1.Getstring("Phone")
        Log(Phoneg)
        fm.SubscribeToTopic(Phoneg) 'you can subscribe to more topics
       
        'Next
    End If
End Sub

Sub Service_Start (StartingIntent As Intent)
    If StartingIntent.IsInitialized Then fm.HandleIntent(StartingIntent)
    Sleep(0)
    Service.StopAutomaticForeground 'remove if not using B4A v8+.
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"), Sendsms)
    'n.Build("Important Good Work sula!!!", "Content", "tag", Me).Notify(9)
    n.Notify(1)
    'CallSub2(Sendsms, "SetText", Message.GetData.Get("title"))
    'If Message.GetData.ContainsKey("title") Then
        'Dim sms As String = Message.GetData.Get("title")
        'Log(sms)
    'End If
   
End Sub



Sub Service_Destroy

End Sub




B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Type Message (Body As String, From As String)
Private const API_KEY As String = ""
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Private txtMessage As EditText
    'Private lstUsers As ListView
    Private txtLogs As EditText
    Private serializator As B4XSerializator
    Private chat As EditText
    Dim cursor1 As Cursor
    Private spnFirstName As Spinner
   
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
   
    Activity.LoadLayout("2")
    If IsConnectedToInternet=True Then
    InitSpinners

    Else
        MsgboxAsync("Error Connecting to the Server Please Check Your Internet Connection","Server Error")

        Return
        End If
End Sub


Private Sub client_MessageArrived (Topic As String, Payload() As Byte)
    Dim receivedObject As Object = serializator.ConvertBytesToObject(Payload)

Dim m As Message = receivedObject
        CallSub2(chat, "NewMessage", m)
   
    End Sub
Private Sub CreateMessage(Body As String) As Byte()
    Dim m As Message
    m.Initialize
    m.Body = Body
    m.From = "currentName"
    Return serializator.ConvertObjectToBytes(m)
End Sub
Public Sub NewMessage(msg As Message)
    txtLogs.Text = $"${msg.From}: ${msg.Body}"$ & CRLF & txtLogs.Text
End Sub
Sub Activity_Resume
    Dim in As Intent = Activity.GetStartingIntent
    'If in.IsInitialized And in <> OldIntent Then
        'OldIntent = in
    Log(in.ExtrasToString)
        If in.HasExtra("Notification_Tag") Then
            Log("Activity started from notification. Tag: " & in.GetExtra("Notification_Tag"))
        'Log("Activity started from notification. Tag: " & in.GetExtra("Notification_Tag"))
        txtLogs.Text= in.GetExtra("Notification_Tag")
        'CallSub2(Sendsms, "SetText", Message.GetData.Get("title"))
        End If
       
       
    'CallSubDelayed2(ActivityA, ReceiveMsg, SelectedMsg)
    'End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)
Activity.Finish
End Sub


Sub btnSend_Click
   
    If txtMessage.Text <> "" Then
        If    spnFirstName.SelectedItem ="Select from the List..." Then
            Msgbox("You Must Select the Student Name. ", "SMIS")
            spnFirstName.RequestFocus
            Return
        End If
         CallSub2(Starter, "SendMessage", txtMessage.Text)
        txtLogs.Text = txtMessage.Text
        CreateMessage(txtMessage.Text)
       
        Else
    If    txtMessage.Text="" Then
            Msgbox("You Must Enter Some Text To Countinue. ", "SMIS")
            txtMessage.RequestFocus
            Return
        End If
       
       
        'NewMessage
    End If
    If IsConnectedToInternet=True Then
    cursor1 = Starter.SQL1.ExecQuery("SELECT ID FROM Sentmessages")
    If cursor1.RowCount > 0 Then
        For i = 0 To cursor1.RowCount - 1
            cursor1.Position = i
            Dim NewID As Int
            NewID = cursor1.GetInt("ID")
        Next

    End If
           
    NewID = NewID +1      ' add 1 to the ID number to make a new ID field
   
    Dim l As Long
    DateTime.DateFormat = "dd/MM/yyyy" ' "1961-08-29"
    Dim datestring As String = DateTime.Date(JsonDateToTick(DateTime.Now))
    l = DateTime.DateParse(datestring)
    DateTime.DateFormat = "dd/MM/yyyy"
        Log(DateTime.Date(l))
        Dim now As Long
        now = DateTime.Now
        Log(DateTime.Now)
        DateTime.DateFormat = "dd/MM/yyyy" : DateTime.TimeFormat = "hh:mm a"
       
        Log(DateTime.Date(l)& " "& DateTime.Time(now))
        Starter.SQL1.ExecNonQuery2("INSERT INTO Sentmessages VALUES(?, ?, ?)", Array As Object(DateTime.Date(l)& " "& DateTime.Time(now), txtMessage.Text, NewID ))
    'txtMessage.Text=""
    cursor1 =Starter.SQL1.ExecQuery2("SELECT Account,Phone,Sex,Phone2 FROM SMSlist where Names = ?", Array As String(spnFirstName.SelectedItem))
    If cursor1.RowCount<>0 Then
    'user registered
    For i = 0 To cursor1.RowCount - 1
        cursor1.Position = i
Dim act As String= cursor1.GetString("Account")
Dim phone As String= cursor1.GetString("Phone")
Dim phoneteacher As String= cursor1.GetString("Phone2")
Dim sx As String= cursor1.GetString("Sex")
    Next
    'Dim j As HttpJob
    'j.Initialize("", Me)
            'j.Download($"http://kccug.com/KabojjaApp/RecieveSMS.ashx?customerId=${act}&s=${txtMessage.Text}&d=${DateTime.Date(l)& " "& DateTime.Time(now)}&id=${NewID}&ph=${phone}&f=${sx}"$ )
   
           
            Dim j As HttpJob
            j.Initialize("", Me)
            j.Download($"http://kccug.com/KabojjaApp/RecieveSMS.ashx?customerId=${act}&s=${txtMessage.Text}&d=${DateTime.Date(l)& " "& DateTime.Time(now)}&id=${NewID}&ph=${phone}&f=${sx}"$ )
            Wait For (j) JobDone(j As HttpJob)
            If j.Success Then
                Log(j.GetString)
            End If
           
           
            SendMessage(phoneteacher, "Kabojja Junior School Message From Parent", txtMessage.Text)
            j.Release
            txtMessage.Text=""
            Dim b As Beeper
            b.Initialize(300, 500) '300 milliseconds, 500 hz
            b.Beep
        MsgboxAsync("SMS Sent Successfully ", "SMIS")
    End If
    Else
        MsgboxAsync("Error Connecting to the Server Please Check Your Internet Connection","Server Error")

        Return
    End If
End Sub
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
    'StopMessageLoop '<-- non ui app only
End Sub
Sub JsonDateToTick(s As String) As Long
    Dim m As Matcher = Regex.Matcher("\d+", s)
    If m.Find Then
        Return m.Match
    End If
    Log("Invalid date: " & s)
    Return 0
End Sub

Sub IsConnectedToInternet As Boolean
    Dim r As Reflector

    r.Target = r.GetContext
    r.Target = r.RunMethod2("getSystemService", "connectivity", "java.lang.String")
    r.Target = r.RunMethod("getActiveNetworkInfo")

    If r.Target <> Null Then
        Return r.RunMethod("isConnectedOrConnecting")
    End If

    Return False
End Sub
Sub InitSpinners
    Private i As Int
    Private Query1 As String
    Private Curs As Cursor
    'query = "CREATE TABLE SMSlist (Account Text, Names Text,Phone text,Sex, ID INTEGER )"
    'We execute a query for each column and fill the Spinner
    'We use SELECT DISTINCT to have each existing first name in the database only once
    Query1 = "SELECT DISTINCT Account,Names FROM SMSlist"
    Curs = Starter.SQL1.ExecQuery(Query1)
    'Log(Curs)
    'we add 'no filter' as no selection
    spnFirstName.Clear
    spnFirstName.Add("Select from the List...")
    'we fill the Spinner with the data from the database
    For i = 0 To Curs.RowCount - 1
        Curs.Position = i
        'spnFirstName.Add(Curs.GetString("Account"))
        spnFirstName.Add(Curs.GetString("Names"))
        'Dim kk As String = Curs.GetString("Names")
        'Log(kk)
    Next
    'Curs.Close
   
End Sub

Sub btnEdit_Click
    'ShowTable
End Sub
 
Last edited:

kisoft

Well-Known Member
Licensed User
Hello
I haven't analyzed your code that thoroughly. When a message arrives, try to save it to a text file as well. When you open an activity you will be able to read it from a text file..
 
Upvote 0

aeric

Expert
Licensed User
B4X:
n.SetInfo(Message.GetData.Get("title"), Message.GetData.Get("body"), Sendsms)

You can pass the values to global variables in Starter module and then call the values from Activity_Resume of the Activity you load the layout.

Starter
B4X:
Sub Process_Globals
    Dim strTitle As String
    Dim strBody As String
End Sub

FirebaseMessaging Service Module
B4X:
Sub fm_MessageArrived(Message As RemoteMessage)
    Starter.strTitle = Message.GetData.Get("title")
    Starter.strBody = Message.GetData.Get("body")
End Sub

Activity
B4X:
Sub Activity_Resume
    lblTitle.Text = Starter.strTitle
    lblBody.Text = Starter.strBody
End Sub

Alternatively, what I normally do is save the data to SQLite first and then load the values from the activity.
 
Upvote 0
Top