Android Question Firebase msg to devices that choose one or more topics

stanks

Active Member
Licensed User
Longtime User
Hi

Scenario: first time app runs, user choose (checkbox) one or more topics from preference activity. when pref activity closes, app should subscribe/unsubscribe from topic(s) and receive only he choosed. now code to subscribe to all topics is from Erel's example.
i tried with diff code in starter service and diff code in firebasemessaging service. in starter i have smthg like:
B4X:
Sub Service_Create
    If Main.manager.GetBoolean("check1") Then
        CallSubDelayed(FirebaseMessaging, "SubscribeToTopic_1")
    ...
    End If
End Sub
in firebasemessaging service i tried this:
B4X:
Sub Process_Globals
    Private fm As FirebaseMessaging
    Dim token As String
End Sub

Public Sub SubscribeToTopic_1
    token = fm.Token
    fm.SubscribeToTopic("topic1") 'you can subscribe to more topics
End Sub

Public Sub SubscribeToTopic_2
    token = fm.Token
    fm.SubscribeToTopic("topic2") 'you can subscribe to more topics
End Sub
...
ofc it does not work. i get only log from Public Sub SubscribeToTopic_1 (when i put log).
and in send message i have this (code from DonManfred):
B4X:
Private Sub SendMessage(id As String, Title As String, Body As String)
    Dim Job As HttpJob
    Job.Initialize("fcm", Me)
    Dim m As Map = CreateMap("to": $"${id}"$)
    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;charset=UTF-8")
    Job.GetRequest.SetHeader("Authorization", "key=" & API_KEY)
End Sub
and in main activity when i tap button i have this:
B4X:
        Select index
            Case 0
               SendMessage(FirebaseMessaging.token, "topic1", "loc: " & addr)
            Case 1
               SendMessage(FirebaseMessaging.token, "topic2", "loc: " & addr)
             ...
        End Select

If i understand this right, first problem is that pref activity is initialized in main, and starter and firebase services are called before main. second problem is probably in subscribing to topics which can be done only from one sub? (???) i don't know. just guessing. any help on this,

Thanks in advance
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
second problem is probably in subscribing to topics which can be done only from one sub? (???)
It doesn't matter how you call fm.SubscribeToTopic.

Don't use PreferenceActivity at all. There are better and simpler ways.
Store the configuration in a file with KVS2 and load it in the Starter service.
 
Upvote 0
Top