Android Question Send notification to single device with Firebase

FatihCubukcu

Member
Licensed User
Longtime User
I am trying to send notification to single device using firebase. I write the information I get with the Log("Token:" & GetToken) code to the Id section, but still all devices are notified. Where am I doing wrong?
[CODE lang="b4x" title="Single device notification"]
Private Sub SendMessage2(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
[/CODE]
For Example
[CODE lang="b4x" title="Single device notification"]
SendMessage2("eleYgmQySGCe9yJnZBcWpR:APA91bFtjyTHoVLTZo_w88JLrQhtbu5vsckhy..................", "title", "body")
[/CODE]
 
See the example B4J code from the Firebase Messaging tutorial. This sends the message to the TOPIC xy.
B4X:
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)
    If Topic.StartsWith("ios_") Then
        Dim iosalert As Map =  CreateMap("title": Title, "body": Body, "sound": "default")
        m.Put("notification", iosalert)
        m.Put("priority", 10)
    End If
    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

Your code sends to a specific token but i fear you are registering this token? with all devices?

please post your SubscribeToTopics sub.
I fear you are doing something weird?
 
Upvote 0
hello, thank you for your quick reply.
I have read the Firebase Messaging tutorial but I don't quite understand how can I send the token I bought to a single device? Do you have an example code?
 
Upvote 0
Just replace data with notification and add empty data value:
B4X:
Private Sub SendMessage2(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 notification As Map = CreateMap("title": Title, "body": Body)
    m.Put("notification", notification)
    m.Put("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
 
Upvote 0
Back
Top