Android Question Notifications based on firebase are randomly received

gregorio_adrian_gimenez

Active Member
Licensed User
Longtime User
Hi,
Managed to publish an app that sends notifications from a device and all authorized auth firebase members should receive it.
What happens to me, after trying a lot and having put it into production, is that not all users receive the notifications, and I do not know why, apply the code of the tutorial of EREL. Sometimes they receive it and others do not, I do not realize the problem.

The users are subscribed correctly to the topics, this is not the problem, and notifications sending them from an app installed on the device.


in module service:

B4X:
Sub Process_Globals
   Private fm As FirebaseMessaging
    Private a As Long
    Private notimap As Map

End Sub

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

Public Sub SubscribeToTopics

  
   fm.SubscribeToTopic("curso")  
 
End Sub

Sub Service_Start (StartingIntent As Intent)
   If StartingIntent.IsInitialized And fm.HandleIntent(StartingIntent) Then Return
End Sub

Sub fm_MessageArrived (Message As RemoteMessage)
   
   Log("Message arrived")
   Log($"Message data: ${Message.GetData}"$)
   Dim from As String
   Dim cola As String
   Dim nb As NotificationBuilder
   Dim imag As String
  
  
   Dim bigtext As NotificationBigTextStyle
   Dim extender As NotificationWearableExtender
 
    If Main.auth.CurrentUser.IsInitialized = True Then
   
    nb.Initialize
    extender.Initialize
  
    nb.SmallIcon = "icon"
    nb.Ticker = "Jularo"
  
  
   
   
    nb.setActivity(Me)
    nb.ContentTitle = Message.GetData.Get("title")
    nb.SubText = Message.GetData.Get("body")
   
    imag = Message.GetData.Get("photourl")
    nb.ContentInfo =Message.GetData.Get("user")
   

   
    nb.SubText = "Barrio Parque Jularo"
    bigtext.Initialize
    bigtext.BigContentTitle = Message.GetData.Get("title")
    bigtext.Bigtext =Message.GetData.Get("body")
 
  
    nb.SetStyle(bigtext)
    notimap.Initialize
    notimap.Put("body",Message.GetData.Get("body"))
    notimap.Put("title",Message.GetData.Get("title"))
    notimap.Put("photourl",Message.GetData.Get("photourl"))
    notimap.Put("user",Message.GetData.Get("user"))
    notimap.Put("token" ,Message.CollapseKey)
    notimap.Put("email",Message.GetData.Get("tag"))
    notimap.Put("userid",Message.GetData.Get("userid"))
    Dim archivo As String
   
    archivo = a
    File.WriteMap(File.DirInternal,archivo &".txt" ,notimap)
   
    'extender.AddAction("","",a,note)
    nb.Extend(extender)
   
     nb.AddAction("","Leer siempre",archivo,note)
    nb.AutoCancel =False

   
    nb.Notify(a)
    a = a +1

End If
End Sub

Sub variables (valor As String)
    Dim vnote As Map
    vnote.Initialize
   
    vnote = File.ReadMap(File.DirInternal,valor & ".txt")
    CallSubDelayed2(note, "GetResult", vnote)
    File.Delete(File.DirInternal,valor & ".txt")
    Dim nb As NotificationBuilder

    nb.Initialize
    nb.Cancel(valor)
'    File.Delete(File.DirInternal,valor)

End Sub


Sub Service_Destroy

End Sub
 

KMatle

Expert
Licensed User
Longtime User
Check if the devices allow apps running in the background. On My Huawei P8 unknown apps are not (!) unless you set it manually. Took me hours to find out. Even WhatsApp had problems so they did an update.

This must be set in energy savings.
 
Upvote 0

gregorio_adrian_gimenez

Active Member
Licensed User
Longtime User
Hi Erel.
1. Yes Erel, Is published in play store :(
2. What I did was, delete the Auth validation code in this service module,
B4X:
 If Main.auth.CurrentUser.IsInitialized = True Then

Will it be that in back ground can not validate if it is logged? I am testing the code without that line of validation but I'm not sure.
Also add this line that could be the problem, but I'm not sure either,
B4X:
#Region  Service Attributes
    #StartAtBoot: true
    #StartCommandReturnValue: android.app.Service.START_STICKY
#End Region


This is what he tries to do to see if it was the problem, but I'm not sure ..
If you can think of anything else, thanks for your suggestion, thank you all!
 
Upvote 0

gregorio_adrian_gimenez

Active Member
Licensed User
Longtime User
Thanks Erel.

I am sending the messages,
The Sub button5_Click send message, you think it has something wrong ?, because the same message, reaches some users and not others.
I verify that the other devices are registered to the topic


B4X:
#Region  Project Attributes
    #ApplicationLabel: Barrio Jularo
    #VersionCode: 2
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False  
#End Region

#Region  Activity Attributes
    #FullScreen: false
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim NativeMe As JavaObject
    Dim auth As FirebaseAuth
    Dim mapCurrentUser As Map
    Dim topi As FirebaseMessaging
    Dim linkus As String
    Dim userd As String
  
    Private googleuser 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.
    Dim sf As StringFunctions
    sf.Initialize
  
  
    Private btnSignIn As Button
    Private btnSignOut As Button
    Private mapCurrentUser As Map

    Private lblName As Label
    Private lblmail As Label
    Private ImageView1 As ImageView
    Private imageView2 As ImageView
    Private Button3 As Button
    Private TabStrip1 As TabStrip
  
    Private linea As Label
    Private texto As Label
    Dim marcar As PhoneCalls
    Dim exal As Label
    Private Label7 As Label
    Private Label1 As Label
    Private Label2 As Label
    Private Label3 As Label
    Private Label4 As Label
    Private Label5 As Label
    Private Label6 As Label
    Private Label8 As Label
  
    Dim TOPIC As String  


    Private EEditText1 As EmojiEditText
    Private ImageView3 As ImageView
    Private Button5 As Button

    Private Label02 As Label
    Private Label03 As Label
    Private Label04 As Label
    Private Label05 As Label
    Private Label06 As Label
  
    Private A1 As AnimCheckBox
    Private A2 As AnimCheckBox
    Private A3 As AnimCheckBox
    Private A4 As AnimCheckBox
    Private A5 As AnimCheckBox
    Private Label9 As Label
  
    Private ScrollView1 As ScrollView

    Private Panel1 As Panel
    Private exal3 As Label
    Private Panel2 As Panel
  
    Dim ff1 As String
    Dim ff2 As String
    Dim ff3 As String
    Dim ff4 As String
    Dim ff5 As String
    Dim ff6 As String
  
    Private A01 As AnimCheckBox
    Private A02 As AnimCheckBox
    Private A03 As AnimCheckBox
    Private A04 As AnimCheckBox
    Private A05 As AnimCheckBox
    Private A06 As AnimCheckBox
    Private EText1 As EditText
    Private Labelpass As Label
    Private Labelpas As Label
    Private pass As String
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("principal")
  
  
  

    Activity.Padding = Array As Int (1dip, 1dip, 1dip, 1dip)

    Activity.Title = "BARRIO PARQUE JULARO"
    Activity.AddMenuItem3("Jularo","",LoadBitmap(File.DirAssets,"jularo.jpg"),True)

  
  
    If FirstTime Then
        'important!!! init only in firsttime
        NativeMe.InitializeContext
        auth.Initialize("auth")
        topi.Initialize("topi")
      
        End If
  
    TabStrip1.LoadLayout("Pagina1", "INICIO  ")
    TabStrip1.LoadLayout("Pagina2", "ENVIAR  ")
    TabStrip1.LoadLayout("Pagina3", "CONFIGURACION")
  
  
    'Activity.AddMenuItem("Inicio", "INICIO")
    'Activity.AddMenuItem("Enviar", "ENVIAR")
    'Activity.AddMenuItem("configuración", "CONFIGURACION")
  
  
    ImageView1.SetLayout(2%X,2%Y,20%X,13.5%Y)
    lblName.SetLayout(24%x,2%Y,70%X,4%Y)
    lblmail.SetLayout(24%x,5%Y,70%X,4%Y)
    btnSignIn.SetLayout(23%x,8.5%Y,35%X,7%Y)
    btnSignIn.Color = Colors.ARGB(50,130,100,150)
    btnSignOut.SetLayout(60%x,8.5%Y,35%X,7%Y)
    btnSignOut.Color =Colors.ARGB(50,100,130,30)
    EText1.SetLayout(27%x,16%Y,63%X,8%Y)
    Labelpass.SetLayout(2%x,16%Y,25%X,8%Y)
    Labelpas.SetLayout(25%x,15.3%Y,65%X,8%Y)
  
    Button3.SetLayout(21%x,25%y,55%x,37%y)
    Button3.SetTextColorAnimated(5000,Colors.Blue)
    texto.SetLayout(15%x,60%y,80%x,10%y)
    imageView2.Bitmap=(LoadBitmap(File.DirAssets,"jularo.jpg"))
    imageView2.SetLayout(2%X,78%y,20%x,12%y)
    exal.SetLayout(23%X,80%y,70%x,9%y)
    A01.SetLayout(6%x,20%y,12%x,7%y)
    Label1.SetLayout( 27%x,20%y,65%x,7%y)
    A02.SetLayout(6%x,27%y,12%x,7%y)
    Label2.SetLayout( 27%x,27%y,65%x,7%y)
    A03.SetLayout(6%x,34%y,12%x,7%y)
    Label3.SetLayout( 27%x,34%y,65%x,7%y)
    A04.SetLayout(6%x,41%y,12%x,7%y)
    Label4.SetLayout( 27%x,41%y,65%x,7%y)
    A05.SetLayout(6%x,48%y,12%x,7%y)
    Label5.SetLayout( 27%x,48%y,65%x,7%y)
    A06.SetLayout(6%x,55%y,12%x,7%y)
    Label6.SetLayout( 27%x,55%y,65%x,7%y)
    Label8.SetLayout( 6%x,10%y,78%x,7%y)
    A01.Checked = True
    A02.Checked = True
    A03.Checked = True
    A04.Checked = True
    A05.Checked = True
    A06.Checked = True
  
  
    ImageView3.Bitmap=(LoadBitmap(File.DirAssets,"jularo.jpg"))
    ImageView3.SetLayout(2%X,78%y,20%x,12%y)
    exal3.SetLayout(23%X,90%y,70%x,9%y)
  
    If auth.CurrentUser.IsInitialized Then Auth_SignedIn(auth.CurrentUser)
  


  
  
  
    A1.StrokeWidth = 7
    A2.StrokeWidth = 7
    A3.StrokeWidth = 7
    A4.StrokeWidth = 7
    A5.StrokeWidth = 7
    A1.TickColor = Colors.Magenta
    A2.TickColor = Colors.Magenta
    A3.TickColor = Colors.Magenta
    A4.TickColor = Colors.Magenta
    A5.TickColor = Colors.Magenta
  
    A1.Checked = True
    TOPIC= "robo"
    'TOPIC= "prueba"
    A2.Checked = False
    A3.Checked = False
    A4.Checked = False
    A5.Checked = False
  

  
    A1.SetLayout(5%x,46%y,11%x,11%y)
    A2.SetLayout(5%x,53%y,11%x,11%y)
    A3.SetLayout(5%x,60%y,11%x,11%y)
    A4.SetLayout(5%x,67%y,11%x,11%y)
    A5.SetLayout(5%x,74%y,11%x,11%y)
    Label02.SetLayout(16%x,46%y,80%x,8%y)
    Label03.SetLayout(16%x,53%y,80%x,8%y)
    Label04.SetLayout(16%x,60%y,80%x,8%y)
    Label05.SetLayout(16%x,67%y,80%x,8%y)
    Label06.SetLayout(16%x,74%y,80%x,8%y)
    EEditText1.SetLayout(5%x,9%y,89%x,25%y)
    EEditText1.Textcolor = Colors.Black
  

    ScrollView1.SetLayout(5%x,8%y,91.5%x,26.5%y)
    Panel2.SetLayout(0%x,0%y,100%x,100%y)
    Label9.SetLayout(6%x,2%y,90%x,5%y)
    'Label10.SetLayout(6%x,3%y,30%x,5%y)
    Button5.SetLayout(6%x,36%y,90%x,9%y)
  
    If File.Exists(File.DirInternal, "F1.txt") = True Then
        ff1 = File.ReadString(File.DirInternal,"F1.txt")
        End If
        If ff1 = "S" Then
            A01.Checked = True
            Else
        A01.Checked = False
    End If
  
    If File.Exists(File.DirInternal, "F2.txt") = True Then
        ff2 = File.ReadString(File.DirInternal,"F2.txt")
    End If
    If ff2 = "S" Then
        A02.Checked = True
    Else
        A02.Checked = False
    End If
  
    If File.Exists(File.DirInternal, "F3.txt") = True Then
        ff3 = File.ReadString(File.DirInternal,"F3.txt")
    End If
    If ff3 = "S" Then
        A03.Checked = True
    Else
        A03.Checked = False
    End If
    If File.Exists(File.DirInternal, "F4.txt") = True Then
        ff4 = File.ReadString(File.DirInternal,"F4.txt")
    End If
    If ff4 = "S" Then
        A04.Checked = True
    Else
        A04.Checked = False
    End If
  
    If File.Exists(File.DirInternal, "F5.txt") = True Then
        ff5 = File.ReadString(File.DirInternal,"F5.txt")
    End If
    If ff5 = "S" Then
        A05.Checked = True
    Else
        A05.Checked = False
    End If
  
    If File.Exists(File.DirInternal, "F6.txt") = True Then
        ff6 = File.ReadString(File.DirInternal,"F6.txt")
    End If
    If ff6 = "S" Then
        A06.Checked = True
    Else
        A06.Checked = False
    End If
  
  
End Sub

Sub Activity_Resume


End Sub

Sub Activity_Pause (UserClosed As Boolean)
  
  
End Sub
  



Sub btnSignIn_Click
    auth.SignOutFromGoogle

    lblName.Text = "Hasta luego"
    lblName.TextColor = Colors.Red
    ImageView1.Bitmap=(LoadBitmap(File.DirAssets,"Chrysanthemum.jpg"))
    lblmail.Text = ""
    auth.SignInWithGoogle
  
  
End Sub

Sub btnSignOut_Click
    auth.SignOutFromGoogle
    lblName.Text = "Hasta luego"
    lblName.TextColor = Colors.Red
    ImageView1.Bitmap=(LoadBitmap(File.DirAssets,"Chrysanthemum.jpg"))
    lblmail.Text = ""
    'auth.SignInWithGoogle
End Sub

Sub Auth_SignedIn (user As FirebaseUser)
  
    ToastMessageShow("Espera un momento..logueando",True)
  
    Log("SignedIn: " & user.DisplayName)
    lblName.Text = "Usuario: " & user.DisplayName
    lblName.TextColor = Colors.DarkGray
    lblmail.text ="Mail: " & user.Email
   
    Log("#-starter.auth_SignedIn=" & user.DisplayName & ", User.PhotoUrl=" & user.PhotoUrl & ", User.Uid=" & user.Uid)
    mapCurrentUser.Initialize
    mapCurrentUser.Put("Uid", user.Uid)
    mapCurrentUser.Put("DisplayName", user.DisplayName)
    mapCurrentUser.Put("Email", user.Email)
    mapCurrentUser.Put("PhotoUrl", user.PhotoUrl)
    linkus = user.PhotoUrl
  
    Dim links As Map
    links.Initialize
    links.Put(ImageView1, mapCurrentUser.GetDefault("PhotoUrl", ""))
    CallSubDelayed2(imagedownloader, "Download", links)
    googleuser = user.Uid
  
    If File.Exists(File.DirInternal,"pass.txt") = True Then
          
    pass = File.ReadString(File.DirInternal,"pass.txt")
  
    Else
        EText1.Enabled = True
        EText1.Visible = True
        Labelpas.Enabled = True
        Labelpas.Visible = True
        Labelpass.Visible =True
        Labelpass.Enabled = True
        pass = EText1.Text  
  
    End If
  
    If sf.Right(googleuser,8) = pass Then
        EText1.Enabled = False
        EText1.Visible = False
        Labelpas.Visible = False
        Labelpas.Enabled =False
        Labelpass.Visible =False
        Labelpass.Enabled = False
        If File.Exists(File.DirInternal,"pass.txt") = True Then
          
        Else
        File.WriteString(File.DirInternal,"pass.txt",EText1.Text)
        End If
    Else
        auth.SignOutFromGoogle
        lblName.Text = "Pida la clave unica"
        lblName.TextColor = Colors.Red
        ImageView1.Bitmap=(LoadBitmap(File.DirAssets,"Chrysanthemum.jpg"))
        lblmail.Text = ""
        EText1.Enabled = True
        EText1.Visible = True
        Labelpas.Visible = True
        Labelpas.Enabled =True
        Labelpass.Visible =True
        Labelpass.Enabled = True
        File.Delete(File.DirInternal,"pass.txt")
        ToastMessageShow("solicita la clave unica al administrador o bien ingresala nuevamente",False)
    End If
  
End Sub

Private Sub SendMessage(tema As String, Title As String, Body As String, tag As String, userr As String,photourl As String, userid As String,tstamp As String)
    Dim Job As HttpJob  
    Job.Initialize("fcm", Me)
    Dim m As Map = CreateMap("to": $"/topics/${tema}"$)
    Dim data As Map = CreateMap("title":tema , "body": Body, "tag": tag,"user":userr,"photourl":linkus,"userid":userid)
    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=" & "dsklkdkkjjdjjdjdjdjdjdjd") ' change code only send this questions

End Sub





Sub Button3_Click

    If auth.CurrentUser.IsInitialized = True Then  

    SendMessage("curso" ,"curso", "Llamada en Curso", mapCurrentUser.Get("Email"),mapCurrentUser.Get("DisplayName"),linkus,mapCurrentUser.Get("Uid"),DateTime.Now)

        StartActivity(marcar.Call("08006669009"))

Else
        StartActivity(marcar.Call("08006669009"))
End If

End Sub



Sub button5_Click

    If     auth.CurrentUser.IsInitialized = True Then
    'SendMessage("prueba" ,"prueba", EEditText1.Text, mapCurrentUser.Get("Email"),mapCurrentUser.Get("DisplayName"),linkus,mapCurrentUser.Get("Uid"),DateTime.Now)
      
    SendMessage(TOPIC ,TOPIC, EEditText1.Text, mapCurrentUser.Get("Email"),mapCurrentUser.Get("DisplayName"),linkus,mapCurrentUser.Get("Uid"),DateTime.Now)
    EEditText1.Text=""
    ToastMessageShow("Mensaje enviado",True)
  
    Else
        ToastMessageShow("Logueate para enviar un mensaje",True)
      
        End If
End Sub




Sub A1_check_changed

    Log("acb4 status = " & A1.isCheckBoxChecked)
    If A1.isCheckBoxChecked = True Then
        A2.Checked = False
        A3.Checked = False
        A4.Checked = False
        A5.Checked = False
        TOPIC = "robo"
        'TOPIC = "prueba"
    End If
  

End Sub

Sub A2_check_changed

    Log("acb4 status = " & A2.isCheckBoxChecked)
    If A2.isCheckBoxChecked = True Then
        A1.Checked = False
        A3.Checked = False
        A4.Checked = False
        A5.Checked = False
        TOPIC = "animales"
            End If
  

End Sub

Sub A3_check_changed

    Log("acb4 status = " & A3.isCheckBoxChecked)
    If A3.isCheckBoxChecked = True Then
        A1.Checked = False
        A2.Checked = False
        A4.Checked = False
        A5.Checked = False
        TOPIC = "salud"  
            End If

End Sub

Sub A4_check_changed

    Log("acb4 status = " & A4.isCheckBoxChecked)
    If A4.isCheckBoxChecked = True Then
        A1.Checked = False
        A2.Checked = False
        A3.Checked = False
        A5.Checked = False
        TOPIC = "sospechosos"
      
    End If
  

End Sub

Sub A5_check_changed

    Log("acb4 status = " & A5.isCheckBoxChecked)
    If A5.isCheckBoxChecked = True Then
        A1.Checked = False
        A2.Checked = False
        A3.Checked = False
        A4.Checked = False
        TOPIC = "incendio"
  
    End If
  

End Sub


Sub A01_check_changed

    If A01.isCheckBoxChecked = True Then
        topi.SubscribeToTopic("curso")
        File.WriteString(File.DirInternal,"F1.txt","S")
    Else
        topi.UnsubscribeFromTopic("curso")
        File.WriteString(File.DirInternal,"F1.txt","U")
    End If

End Sub

Sub A02_check_changed

    If A02.isCheckBoxChecked = True Then
        topi.SubscribeToTopic("robo")
        'topi.SubscribeToTopic("prueba")
        File.WriteString(File.DirInternal,"F2.txt","S")
    Else
        topi.UnsubscribeFromTopic("robo")
        ' topi.UnsubscribeFromTopic("prueba")
        File.WriteString(File.DirInternal,"F2.txt","U")
    End If

End Sub

Sub A03_check_changed

    If A03.isCheckBoxChecked = True Then
        topi.SubscribeToTopic("animales")
        File.WriteString(File.DirInternal,"F3.txt","S")
    Else
        topi.UnsubscribeFromTopic("animales")
        File.WriteString(File.DirInternal,"F3.txt","U")
    End If

End Sub

Sub A04_check_changed

    If A04.isCheckBoxChecked = True Then
        topi.SubscribeToTopic("salud")
        File.WriteString(File.DirInternal,"F4.txt","S")
    Else
        topi.UnsubscribeFromTopic("salud")
        File.WriteString(File.DirInternal,"F4.txt","U")
    End If

End Sub

Sub A05_check_changed

    If A05.isCheckBoxChecked = True Then
        topi.SubscribeToTopic("sospechosos")
        File.WriteString(File.DirInternal,"F5.txt","S")
    Else
        topi.UnsubscribeFromTopic("sospechosos")
        File.WriteString(File.DirInternal,"F5.txt","U")
    End If

End Sub

Sub A06_check_changed

    If A06.isCheckBoxChecked = True Then
        topi.SubscribeToTopic("incendio")
        File.WriteString(File.DirInternal,"F6.txt","S")
    Else
        topi.UnsubscribeFromTopic("incendio")
        File.WriteString(File.DirInternal,"F6.txt","U")
    End If
 
Last edited:
Upvote 0

KMatle

Expert
Licensed User
Longtime User
It's all about sending the message correctly. So it doesn't matter from where. Your B4A code looks good (would be the same as in B4J.

A lot of users have rooted devices with old play services installed. On Those devices there will be problems for sure. So first check which devices are envolved.

And: Please take a look at my post about energy savings on Huawei devices. As I've written, Huawei did an update extra for WhatsApp to set permissions to "run in the background" to ON. At least 10-20% of the Android users have a Huawei (other manufators may behave the same: Standard here is OFF).

As you send DATA messages, Android will receive it but your app doesn't when the FCM service is stopped (there's no notification, too). So it IS transmitted to the device but it's not buffered.
 
Upvote 0

gregorio_adrian_gimenez

Active Member
Licensed User
Longtime User
Hi Kmatle, many thanks for your answer, of course I took into account the inconvenience with the Huawei, it was very useful.

To your answer, is there any way to save or queue messages that for some reason do not arrive?
An example that I could verify, if I send a notification and some target device is turned off, the messages are not queued and will never receive it. Is there a way to solve this?

other example that I could verify,when the device enters energy saving mode it also does not receive messages, the messages that should have been received never arrive, even when the power saving mode is re-established to full.
Because my app, if it is not being functional if I do not solve this.
 
Last edited:
Upvote 0
Top