B4A Library FirebaseNotifications - Push messages / Firebase Cloud Messaging (FCM)

Discussion in 'Additional libraries, classes and official updates' started by Erel, Jun 9, 2016.

Thread Status:
Not open for further replies.
  1. luke2012

    luke2012 Well-Known Member Licensed User

    Hi all,
    How to implement / call the "SendMessage" code within a UI (desktop) B4J Application ?
     
    Last edited: Jul 24, 2017
  2. Erel

    Erel Administrator Staff Member Licensed User

    See the code in the first post. Just don't call StopMessageLoop in JobDone.
     
    luke2012 likes this.
  3. An Schi

    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.
     
  4. Alpandino

    Alpandino Member Licensed User

    What is "StopMessageLoop" in the JobDone? I don't see it... and I have coded an App in B4A that send and receive msgs using Firebase.
    I'm missing something?
     
  5. luke2012

    luke2012 Well-Known Member Licensed User

    My target is to call the SendMessage sub from a B4J UI App.
    if I try to do this I got an error that says "java.lang.RuntimeException: StartMessageLoop should only be called in non-UI applications."

    Code:
    Sub AppStart (Form1AsForm, Args() AsString)
         SendMessage(
    "general""Title""message...")
         StartMessageLoop
    End Sub
    @Erel ignore this post. I got it...
    I did a better check of the code and I understood what you told me ;)
     
  6. Erel

    Erel Administrator Staff Member Licensed User

    Remove any call to StartMessageLoop or StopMessageLoop. They are not needed in a UI app.
     
    luke2012 likes this.
  7. Claudio Oliveira

    Claudio Oliveira Active Member Licensed User

    Hi,
    Is it possible to send JSON arrays through FCM?
    I've been searching this forum and FCM documentation but haven't found any information on this whatsoever.

    I've made an adaptation of Erel's code on Post #1

    I'm trying to post this message through FCM:
    Code:
    {"to":"XXXXXXX","data":[{"col":"Testing","value":"Test #1"},{"col":"Testing","value":"Test #2"},{"col":"Testing","value":"Test #3"}]}
    JSONGenerator pretty string is this:
    Code:
    {
       
    "to":XXXXXXX",
       "data": [
          {
             
    "col""Testing",
             
    "value""Test #1"
          
    },
          {
             "col": "Testing",
             "value": "Test #2"
          },
          {
             "col": "Testing",
             "value": "Test #3"
          }
       ]
    }
    This is my code:

    Code:
    Private Sub SendMessage(Topic As String, ColName As String, ColValue As String)
        
    Dim m As Map
        
    Dim Job As HttpJob
        
    Dim data As Map
        
    Dim l As List
       
        l.Initialize
       
        Job.Initialize(
    "fcm", Me)
        m = CreateMap(
    "to": *****)
        
    For j=1 To 3
            data = CreateMap(
    "col": ColName, "value": ColValue & J)
            l.Add(data)
        
    Next
        m.Put(
    "data", l)
        
    Dim jg As JSONGenerator
        jg.Initialize(m)   
        
    Log(jg.ToPrettyString(3))
        
    Log(jg.ToString)
        Job.PostString(
    "https://fcm.googleapis.com/fcm/send", jg.ToString)
        Job.GetRequest.SetContentType(
    "application/json;charset=UTF-8")
        Job.GetRequest.SetHeader(
    "Authorization""key=" & "*****")

    End Sub


    Sub JobDone(job As HttpJob)
        
    Log(job)
        
    If job.Success Then
            
    Log(job.GetString)
        
    End If
        job.Release
    End Sub
    FCM returns this error message:

    Field "data" must be a JSON array: [{"col":"Testing","value":"Test #1"},{"col":"Testing","value":"Test #2"},{"col":"Testing","value":"Test #3"}]
    [errormessage=Bad Request, httputils2service=null, jobname=fcm
    , password=, req=anywheresoftware.b4a.http.HttpClientWrapper$HttpUriRequestWrapper@3b5da6c, success=false
    , tag=java.lang.Object@8831835, target=class com.ceosoft.tstlist.main, taskid=1
    , username=]

    As far as I know and according to JSON documentation, my array is absolutely fine.
    Any ideas?

    Thanks
     
  8. DonManfred

    DonManfred Expert Licensed User

    I suggest to base64 encoded the Json and send the base64 string.
    On receiverside you base64 Decode it and then you parse the resulting json
     
    Claudio Oliveira likes this.
  9. Claudio Oliveira

    Claudio Oliveira Active Member Licensed User

    Good one, Don!
    I'll try this.
    Thank you indeed!
     
  10. Claudio Oliveira

    Claudio Oliveira Active Member Licensed User

    Worked perfectly!

    Thanks again, @DonManfred
     
    DonManfred likes this.
  11. biometrics

    biometrics Active Member Licensed User

    I've followed the instructions here (https://www.b4x.com/android/forum/threads/integrating-firebase-services.67692/) to register a project with Firebase and have copied the manifest code. I haven't added any of the code in the OP yet.

    When I compile my project I now get the following error, please advise:

    Code:
    AndroidManifest.xml:35: error: Error: No resource found that matches the given name (at 'value' with value '@integer/google_play_services_version').
    AndroidManifest.xml:123: error: Error: No resource found that matches the given name (at 'theme' with value '@style/Theme.IAPTheme').
    I have the following added in SDK Manager:

    - Android Support Repository
    - Google Repository
    - Google Play Services (wasn't sure so added this just in case)
     
  12. Erel

    Erel Administrator Staff Member Licensed User

  13. biometrics

    biometrics Active Member Licensed User

    I followed the instructions and downloaded the recommended options. (I renamed my current C:\Android directory and started a new one). I updated the paths (I was at SDk platform 25 and your tool recommended 24).

    I'm still getting this error when trying to compile (note I only included the manifest changes, have not included any code yet):

    Code:
    AndroidManifest.xml:35: error: Error: No resource found that matches the given name (at 'value' with value '@integer/google_play_services_version').
    AndroidManifest.xml:123: error: Error: No resource found that matches the given name (at 'theme' with value '@style/Theme.IAPTheme').
    My manifest file:

    Code:
    'This code will be applied to the manifest file during compilation.
    'You do not need to modify it in most cases.
    'See this link for for more information: http://www.b4x.com/forum/showthread.php?p=78136
    AddManifestText(
    <uses-sdk android:minSdkVersion=
    "5" android:targetSdkVersion="14"/>
    <supports-screens android:largeScreens=
    "true"
      android:normalScreens=
    "true"
      android:smallScreens=
    "true"
      android:anyDensity=
    "true"/>)
    SetApplicationAttribute(android:icon, 
    "@drawable/icon")
    SetApplicationAttribute(android:
    label"$LABEL$")
    SetApplicationAttribute(android:theme, 
    "@android:style/Theme.Holo")
    'End of default text.

    '************ Google Play Services Base ************
    AddApplicationText(
      <
    activity android:name="com.google.android.gms.common.api.GoogleApiActivity"
      android:theme=
    "@android:style/Theme.Translucent.NoTitleBar"
      android:exported=
    "false"/>
      <meta-data
      android:name=
    "com.google.android.gms.version"
      android:value=
    "@integer/google_play_services_version" />
    )
    '************ Google Play Services Base (end) ************

    '************ Firebase Base ************
    CreateResourceFromFile("google-services""google-services.json")
    AddPermission(android.permission.ACCESS_NETWORK_STATE)
    AddPermission(android.permission.INTERNET)
    AddPermission(android.permission.WAKE_LOCK)
    AddPermission(com.google.android.c2dm.permission.RECEIVE)
    AddPermission(${applicationId
    }.permission.C2D_MESSAGE)
    AddManifestText( <permission android:name="$
    {applicationId}.permission.C2D_MESSAGE"
      android:protectionLevel="signature" />)
    AddApplicationText(
    <receiver
      android:name="com.google.android.gms.measurement.AppMeasurementReceiver"
      android:enabled="true">
      <intent-filter>
      <action android:name="com.google.android.gms.measurement.UPLOAD"/>
      </intent-filter>
      </receiver>

      <service
      android:name="com.google.android.gms.measurement.AppMeasurementService"
      android:enabled="true"
      android:exported="false"/>
      <provider
      android:authorities="$
    {applicationId}.firebaseinitprovider"
      android:name="com.google.firebase.provider.FirebaseInitProvider"
      android:exported="false"
      android:initOrder="100" />
      <receiver
      android:name="com.google.android.gms.measurement.AppMeasurementReceiver"
      android:enabled="true">
      <intent-filter>
      <action android:name="com.google.android.gms.measurement.UPLOAD"/>
      </intent-filter>
      </receiver>

      <service
      android:name="com.google.android.gms.measurement.AppMeasurementService"
      android:enabled="true"
      android:exported="false"/>
      <receiver
      android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver"
      android:exported="true"
      android:permission="com.google.android.c2dm.permission.SEND" >
      <intent-filter>
      <action android:name="com.google.android.c2dm.intent.RECEIVE" />
      <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
      <category android:name="$
    {applicationId}" />
      </intent-filter>
      </receiver>
      <receiver
      android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver"
      android:exported="false" />


      <service
      android:name="com.google.firebase.iid.FirebaseInstanceIdService"
      android:exported="true">
      <intent-filter android:priority="-500">
      <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
      </intent-filter>
      </service>
    )
    '************ Firebase Base (end) ************

    '************ Firebase Notifications ************
    AddApplicationText(
      <service
      android:name="com.google.firebase.messaging.FirebaseMessagingService"
      android:exported="true">
      <intent-filter android:priority="-500">
      <action android:name="com.google.firebase.MESSAGING_EVENT" />
      </intent-filter>
      </service>
      <service android:name="anywheresoftware.b4a.objects.FirebaseNotificationsService">
      <intent-filter>
      <action android:name="com.google.firebase.MESSAGING_EVENT"/>
      </intent-filter>
      </service>
    )
    '************ Firebase Notifications (end)************

    '************ Firebase Analytics ************
    AddApplicationText(
      <receiver
      android:name="com.google.android.gms.measurement.AppMeasurementReceiver"
      android:enabled="true">
      <intent-filter>
      <action android:name="com.google.android.gms.measurement.UPLOAD"/>
      </intent-filter>
      </receiver>

      <service
      android:name="com.google.android.gms.measurement.AppMeasurementService"
      android:enabled="true"
      android:exported="false"/>

      <service android:name="com.google.firebase.crash.internal.service.FirebaseCrashReceiverService"
      android:process=":background_crash"/>

      <service android:name="com.google.firebase.crash.internal.service.FirebaseCrashSenderService"
      android:process=":background_crash"/>
    )
    '************ Firebase Analytics (end) ************

    '************ Firebase Ads ************
    AddApplicationText(
      <activity
      android:name="com.google.android.gms.ads.AdActivity"
      android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
      android:theme="@android:style/Theme.Translucent" />
      <activity android:name="com.google.android.gms.ads.purchase.InAppPurchaseActivity"
      android:theme="@style/Theme.IAPTheme"/>
    )
    '************ Firebase Ads (end) ************

    '************ Firebase Auth ************
    AddApplicationText(
      <activity android:name="com.google.android.gms.auth.api.signin.internal.SignInHubActivity"
      android:theme="@android:style/Theme.Translucent.NoTitleBar"
      android:excludeFromRecents="true"
      android:exported="false" />

      <service
      android:name="com.google.android.gms.auth.api.signin.RevocationBoundService"
      android:exported="true"
      android:permission="com.google.android.gms.auth.api.signin.permission.REVOCATION_NOTIFICATION" />
    )
    '************ Firebase Auth (end) ************
    My paths:

    Capture.JPG
     
  14. An Schi

    An Schi Well-Known Member Licensed User

    Did you include the google-service.json into your project?
     
  15. biometrics

    biometrics Active Member Licensed User

    I copied it to the project folder:

    Capture1.JPG
    Capture2.JPG
    Capture3.JPG
     
  16. Erel

    Erel Administrator Staff Member Licensed User

    Can you upload your project?
     
  17. biometrics

    biometrics Active Member Licensed User

    See attached zip file.

    I've created a new project and all I did is add the manifest entries from https://www.b4x.com/android/forum/threads/integrating-firebase-services.67692/ and copied the google-services.json to the project folder (where the .b4a file is located). I've got a clean & recommended Android installation as per https://www.b4x.com/android/forum/t...ewer-versions-of-android-tools.80090/#content. I'm running B4A 7.01.

    Still gives me this error:

    Code:
    AndroidManifest.xml:28: error: Error: No resource found that matches the given name (at 'value' with value '@integer/google_play_services_version').
    AndroidManifest.xml:116: error: Error: No resource found that matches the given name (at 'theme' with value '@style/Theme.IAPTheme').
    I've changed the unique ids in google-services.json for the zip upload (it gives the error with my ids and with the anonymised ids).
     

    Attached Files:

  18. DonManfred

    DonManfred Expert Licensed User

    Make sure you are using alle the firebase libraries which you are including in the manifest.
    For example you are including the manifestentry for Firebasemessaging but you are NOT using the lib and even you did not added the lib to your project.
    You are not adding firebase messaging (and setup it correctly in code)
    You are not using Firebase Auth, not firebase Anylytics, not Firebase Ads (the ladder is using the Theme.IAPTheme (second error)

    Add Firebase Auth library to your project.

    Use this manifestcontent

    It compiles fine here
     
  19. biometrics

    biometrics Active Member Licensed User

    Thanks, I got it working now!

    It wasn't clear to me that some of the manifest entries are optional. I've added these:

    Google Play Services Base
    Firebase Base
    Firebase Notifications

    And I only noticed now that the library was in this thread. Added it and it's working. Thanks Manfred! :)
     
    DonManfred likes this.
  20. DonManfred

    DonManfred Expert Licensed User

    It is clear.

    I marked it bold here...
     
Thread Status:
Not open for further replies.
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice