Spanish Implementar notificaciones con imagenes desde firebase

fernando1987

Active Member
Licensed User
New version available 3.00

Changes.

- The interface is improved and updated to be compatible with the new version of JdasboardUI.

cap 1.png

cap 2.png

cap 3.png


cap 4.png

cap 5.png
 

Nino Caminiti

Member
Licensed User
Hola , muchas gracias. Se puede probar si funciona? Cuando voy a enviar una push el programa se cierra y no envia nada
 

fernando1987

Active Member
Licensed User
hola de echo lo acabo de probar a mi me funciona bien asegurate de seguir este tutorial:
y que tu tema sea el mismo en tu proyecto, tambien es muy importante el archivo json. de echo para salir de dudas pregunte a un usuario que adquirio el codigo fuente en mi tienda y tampoco reporta problemas
 

Nino Caminiti

Member
Licensed User
Hola yo estoy utilizando el framework de b4x y he implementando este codigo en mi app para enviar la push. Mi app es una webview app conectada a mi pagina wordpress hasta la ultima actualización de wordpress enviaba la push automaticamente cada vez que publicaba un post pero ya no me funciona y no he conseguido arreglarlo. Tu solución me gusta mucho por esto quiero comprobar si funciona y en el caso me compro el codigo en tu pagína..Esto es lo que me aparece cuando hago click en send push y se cierra el app:
C:\Users\ninoc\Desktop\notifications\notifications\FirebaseMessaging\bin>pause
Presione una tecla para continuar . . .

y este warning cuando se abre:

C:\Users\ninoc\Desktop\notifications\notifications\FirebaseMessaging>cd bin

C:\Users\ninoc\Desktop\notifications\notifications\FirebaseMessaging\bin>java.exe @release_java_modules.txt -m b4j/b4j.notificacion.main
Apr 25, 2024 11:49:07 AM javafx.scene.CssStyleHelper calculateValue
WARNING: Caught 'java.lang.ClassCastException: class java.lang.String cannot be cast to class javafx.scene.paint.Paint (java.lang.String is in module java.base of loader 'bootstrap'; javafx.scene.paint.Paint is in module javafx.graphics of loader 'app')' while converting value for '-fx-background-color' from rule '*.button' in stylesheet jrt:/javafx.controls/com/sun/javafx/scene/control/skin/modena/modena.bss
Apr 25, 2024 11:49:07 AM javafx.scene.CssStyleHelper calculateValue
WARNING: Caught 'java.lang.ClassCastException: class java.lang.String cannot be cast to class javafx.scene.paint.Paint (java.lang.String is in module java.base of loader 'bootstrap'; javafx.scene.paint.Paint is in module javafx.graphics of loader 'app')' while converting value for '-fx-background-color' from rule '*.button' in stylesheet jrt:/javafx.controls/com/sun/javafx/scene/control/skin/modena/modena.bss
Apr 25, 2024 11:49:07 AM javafx.scene.CssStyleHelper calculateValue
WARNING: Caught 'java.lang.ClassCastException: class java.lang.String cannot be cast to class javafx.scene.paint.Paint (java.lang.String is in module java.base of loader 'bootstrap'; javafx.scene.paint.Paint is in module javafx.graphics of loader 'app')' while converting value for '-fx-background-color' from rule '*.button' in stylesheet jrt:/javafx.controls/com/sun/javafx/scene/control/skin/modena/modena.bss
(null string)
send._vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv5 (java line: -1)
java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "<parameter1>" is null
at b4j/anywheresoftware.b4a.objects.streams.File.OpenInput(Unknown Source)
at b4j/b4j.notificacion.send._vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv5(Unknown Source)
at b4j/b4j.notificacion.send$ResumableSub_Send1.resume(Unknown Source)
at b4j/b4j.notificacion.send._vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv7(Unknown Source)
at b4j/b4j.notificacion.send._send_mensajes_submit(Unknown Source)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at b4j/anywheresoftware.b4a.BA.raiseEvent2(Unknown Source)
at b4j/anywheresoftware.b4a.keywords.Common.CallSub4(Unknown Source)
at b4j/anywheresoftware.b4a.keywords.Common.access$0(Unknown Source)
at b4j/anywheresoftware.b4a.keywords.Common$CallSubDelayedHelper.run(Unknown Source)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Unknown Source)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(Unknown Source)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(Unknown Source)
at java.base/java.lang.Thread.run(Unknown Source)
 

Nino Caminiti

Member
Licensed User
Mi receiver firebasemessanging:
Sub Process_Globals
    Private fm As FirebaseMessaging
    Dim Title As String
    Dim Body As String
    Dim PostLinks As List ' List to store post links
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
  
  
Sub FetchPostLinks
    Dim apiUrl As String = "https://yeseuropa.org/wp-json/wp/v2/posts"
  
    Dim job As HttpJob
    job.Initialize("fetchPosts", Me)
    job.Download(apiUrl)
End Sub

Sub JobDone(job As HttpJob)
    If job.Success Then
        Dim response As String = job.GetString
        Dim parser As JSONParser
        parser.Initialize(response)
        Dim posts As List = parser.NextArray
      
        PostLinks.Initialize ' Initialize the list to store post links
      
        For Each post As Map In posts
            Dim postLink As String = post.Get("link")
            PostLinks.Add(postLink)
        Next
    Else
        Log("HTTP request failed: " & job.ErrorMessage)
    End If
    job.Release
End Sub
  

Public Sub SubscribeToTopics (Topics() As Object)
    For Each topic As String In Topics
        fm.SubscribeToTopic(topic)
    Next
End Sub

Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data: ${Message.GetData}"$)
  
    ' Get title and body, providing defaults if they are missing or null
    Dim Title As String = Message.GetData.GetDefault("title", "YES EUROPA MOVILIDAD INTERNACIONAL")
    Dim Body As String = Message.GetData.GetDefault("body", "Aquí te enviamos una nueva oportunidad publicadas en YesEuropa.")
  
    Dim PostLink As String = Message.GetData.Get("post_url")
    Dim NewsId As Int = Message.GetData.Get("news_id")
  
    If PostLink = Null Then
        Log("No post link found in the notification data.")
        Return
    End If
  
    Log($"Message data: Title=${Title}, Body=${Body}, PostLink=${PostLink}, NewsId=${NewsId}"$)
  
    FetchPostLinks
  
    If B4XPages.IsInitialized And B4XPages.GetManager.IsForeground Then
        ' App is in the foreground
        Dim n2 As Notification
        n2.Initialize2(n2.IMPORTANCE_HIGH)
        n2.Icon = "icon"
        n2.SetInfo(Title, Body, Main)
        n2.Notify(1)
      
        ' Open the post link in the phone's browser when the notification is clicked
        Dim i As Intent
        i.Initialize(i.ACTION_VIEW, PostLink)
        StartActivity(i)
    End If
    ' Handle image notification logic here from the first code snippet
    ' Be sure to adjust paths and variables as needed
    Try
        Log("Message arrived")
        Log($"Message data: ${Message.GetData}"$)
      
        Dim imageloader As BitmapsAsync
        imageloader.Initialize
        Dim n As NB6
        n.Initialize("default", Application.LabelName, "DEFAULT").AutoCancel(False).SmallIcon(Application.Icon)
        If Message.GetData.Get("image") <> "" Then
            Dim j As HttpJob
            j.Initialize("", Me)
            j.Download(Message.GetData.Get("image"))
            Wait For (j) JobDone (j As HttpJob)
            If j.Success Then
                Wait For (imageloader.LoadFromHttpJob(j, 500dip, 500dip)) Complete (bmp As B4XBitmap)
                Dim b As Bitmap = bmp
              
            End If
      
            n.BigPictureStyle(LoadBitmap(File.DirAssets,"icon.png"),b,Message.GetData.Get("title"),Message.GetData.Get("body"))
            n.Build(Message.GetData.Get("title"),Message.GetData.Get("body"),"noti", Main).Notify(2000)
        Else if Message.GetData.Get("image") = "" Then
            n.Build(Message.GetData.Get("title"),Message.GetData.Get("body"),"noti", Main).Notify(2000)
        End If
    Catch
        n.Build(Message.GetData.Get("title"),Message.GetData.Get("body"),"noti", Main).Notify(2000)
        Log(LastException)
    End Try
End Sub


Sub fm_TokenRefresh (Token As String)
    Log("TokenRefresh: " & Token)
  
    'Create a http job object
    Dim job As HttpJob
    job.Initialize("job1", Me)

    'Subscribe device
    Dim params As Map
    params.Initialize
  
    Dim r As Reflector
    r.Target = r.GetContext
    Dim secureSettings As Object = r.RunMethod("getContentResolver")
    Dim jo As JavaObject
    Dim device_id As String = jo.InitializeStatic("android.provider.Settings$Secure").RunMethod("getString", Array As Object(secureSettings, "android_id"))
  
    params.Put("rest_api_key", "xxxxxxxxxxxxxxxx")
    params.Put("device_uuid", device_id) 'Use the device uid from dgUID library
    params.Put("device_token", Token) 'Use the refreshed token
    params.Put("subscription", "your_subscription")
    params.Put("device_name", "your_device_name")
    params.Put("os_version", "your_os_version")

    'Post the parameters to the subscribe endpoint
    job.PostMultipart("https://www.yeseuropa.org/wp-json/fcm/pn/subscribe", params, Null)

    'Wait for the job to complete
    Wait For (job) JobDone(job As HttpJob)

    'Check the result
    If job.Success Then
        'Parse the JSON response
        Dim parser As JSONParser
        parser.Initialize(job.GetString)
        Dim root As Map = parser.NextObject
  
        'Get the error, message and subscription_id fields
        Dim hasError As Boolean = root.Get("error")
        Dim message2 As String = root.Get("message")
        Dim subscription_id As Int = root.Get("subscription_id")

        If hasError Then
            ' Handle the error
            Log(message2)
            Log("Subscription id: " & subscription_id)
        Else
            Log("Error: " & job.ErrorMessage)
        End If
    Else
        ' Handle the error
        Log(job.ErrorMessage)
    End If

    ' Release the job object
    job.Release
End Sub

Public Sub UnsubscribeFromTopics (Topics() As Object)
    Dim r As Reflector
    r.Target = r.GetContext
  
    Dim secureSettings As Object = r.RunMethod("getContentResolver")
    Dim jo As JavaObject
    Dim device_id As String = jo.InitializeStatic("android.provider.Settings$Secure").RunMethod("getString", Array As Object(secureSettings, "android_id"))
  
    ' Create a http job object
    Dim job As HttpJob
    job.Initialize("job2", Me)
  
    ' Unsubscribe device
    Dim params2 As Map
    params2.Initialize
  
    params2.Put("rest_api_key", "xxxxxxxxxxxxxxxxxx")
    params2.Put("device_uuid", device_id)

    'Post the parameters to the unsubscribe endpoint
    job.PostMultipart("https://www.yeseuropa.org/wp-json/fcm/pn/unsubscribe", params2, Null)

    'Wait for the job to complete
    Wait For (job) JobDone(job As HttpJob)

    'Check the result
    If job.Success Then
        'Parse the JSON response
        Dim parser2 As JSONParser
        parser2.Initialize(job.GetString)
        Dim root2 As Map = parser2.NextObject
      
        'Get the error and message fields
        Dim hasError As Boolean = root2.Get("error")
        Dim message2 As String = root2.Get("message")
        Dim subscription_id As Int = root2.Get("subscription_id")

        If hasError Then
            ' Handle the error
            Log(message2)
            Log("Subscription id: " & subscription_id)
        Else
            Log("Error: " & job.ErrorMessage)
        End If
    Else
        ' Handle the error
        Log(job.ErrorMessage)
    End If

    ' Release the job object
    job.Release
End Sub

y este es mi b4xmainpage;

B4X:
' Initialize WebView1 and load URL
    CallSubDelayed2(FirebaseMessaging, "SubscribeToTopics", Array("general"))
    'request notification permission
    #if B4A
    Wait For (CheckAndRequestNotificationPermission) Complete (HasPermission As Boolean)
    If HasPermission = False Then
        Log("no permission")
        ToastMessageShow("no permission", True)
    End If
    #Else If B4i
    Main.App.RegisterUserNotifications(True, True, True)
    Main.App.RegisterForRemoteNotifications
    #End If
End Sub

#if B4A
Private Sub CheckAndRequestNotificationPermission As ResumableSub
    Dim p As Phone
    If p.SdkVersion < 33 Then Return True
    Dim ctxt As JavaObject
    ctxt.InitializeContext
    Dim targetSdkVersion As Int = ctxt.RunMethodJO("getApplicationInfo", Null).GetField("targetSdkVersion")
    If targetSdkVersion < 33 Then Return True
    Dim NotificationsManager As JavaObject = ctxt.RunMethod("getSystemService", Array("notification"))
    Dim NotificationsEnabled As Boolean = NotificationsManager.RunMethod("areNotificationsEnabled", Null)
    If NotificationsEnabled Then Return True
    Dim rp As RuntimePermissions
    rp.CheckAndRequest(rp.PERMISSION_POST_NOTIFICATIONS)
    Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean) 'change to Activity_PermissionResult if non-B4XPages.
    Log(Permission & ": " & Result)
    Return Result
End Sub
#End If
 
Last edited:

fernando1987

Active Member
Licensed User
hola, la aplicacion esta dirigida para enviar notificaciones a apicaciones de android, bueno al parecer no lee el archivo donde eta el token o n es el correcto esto se puede debe a permisos para manejar el archivo si usas el nstalador no deberia habr problemas porque te pedira permisos de administrador, en caso de usar a version portable terecomiendo ponerla en una carpeta publica como mis documentos y asegurate de cargar elarchivo json correcto, que el nombre del proyecto sea el mismo reistrado en firebase y tambien el tema debe coincidir con el de tu aplicacion aunque al ser una app web no te recomiendo este programa es solo para aplicaciones moviles como ves en el tutorial.
 

Nino Caminiti

Member
Licensed User
Hola es un app Android y iOS ya publicada en en Google Play y Apple store no es una webapp utilizo funciones nativas de Android y iOS., utilizo javascripts y funciones nativas y cargo la web en una webview
 
Top