Android Question Firebase notifications but only for a specific user?

Dianzoa

Active Member
Licensed User
Hello mates! How are You doing?
Since the new android 8.1 keeps killing my app when the phone is not active for a certain time ( still don't know how much minutes before he kills it). I need to use push notifications to inform the user that He has a job to do, since the app is already killed, this can be my solution for that, as far as I know push notifications can call the app to start again.

Cheers, Diego.
 

FrankBerra

Active Member
Licensed User
Longtime User
Your idea can be a solution.
To send a push message to a specific user you must obtain the Token ID for that specific user and save it to your server to use later.

For example:
B4X:
Sub Process_Globals
    Public fm As FirebaseMessaging
End Sub

Sub Service_Start (StartingIntent As Intent)
    If StartingIntent.IsInitialized Then fm.HandleIntent(StartingIntent)
    Sleep(0)
    Service.StopAutomaticForeground 'remove if not using B4A v8+.


    dim Token as string = fm.Token
End Sub
 
Upvote 0

Dianzoa

Active Member
Licensed User
Frank! Indeed! I will read a little more of that token specific solution, I am still fresh in this firebase thing.
I will return with my experiments about this tomorrow.
EDIT: The problem I seem to note without reading the doc, still, is, If I have 40 users, I need to manually register those 40 tokens in the firebase server?
 
Upvote 0

FrankBerra

Active Member
Licensed User
Longtime User
Well, i prefere to save all the 40 tokens on my own server and then send a push notification to single user with a php script.
If you need to push a message to all users at same time i suppose it is better to subscribe the device to a specific Topic and then from firebase consolle send a message to all users that subscibed that specific topic.

Example code from the tutorial:
B4X:
Public Sub SubscribeToTopics
    fm.SubscribeToTopic("general") 'you can subscribe to more topics
End Sub
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
If you HAVE aserver, then upload the token with OKHttpUtils and PHP to your DB.

If not:

If every user can be identified in your app (like a fixed userid) then you can subscribe to different topics named like the users (any other unique value will do). You can't get a list of all available topics but as you know them, it's the same. So you send a FCM message to the topic "MichaelMiller" or "SteffBrown". Any other unique name will do.
 
Upvote 0

Dianzoa

Active Member
Licensed User
I think my poor english it's the issue hehe. Actually I don't have problems in saving the tokens of my app users in my DB, actually it will grow ,it's not a static number of users. But as far as I know, you have to register those tokens in the FMC itself or not?
EDIT: Or, firebase know all the tokens and associates to the phone automatically?
 
Upvote 0

Dianzoa

Active Member
Licensed User
When you obtain the token with dim Token as string = fm.Token and save it to your DB you can send a push message to that device/user with that token ID and a php script without do anything else.
For example this is a working php script: https://gist.github.com/MohammadaliMirhamed/7384b741a5c979eb13633dc6ea1269ce
Ohhh, I got it know, actually I use aspx scripts, but I already do this to most of my google api calls etc. So it's almost the same thing. Thanks guys! It's 4:25AM here, so I'm going to crush.
I will experiment with all this info in about 11 hours lol.

Cheers, Diego
 
Upvote 0

npsonic

Active Member
Licensed User
Ohhh, I got it know, actually I use aspx scripts, but I already do this to most of my google api calls etc. So it's almost the same thing. Thanks guys! It's 4:25AM here, so I'm going to crush.
I will experiment with all this info in about 11 hours lol.

Cheers, Diego

There is actually two tokens that shouldn't be mixed, so token ID how FrankBerra called it is somewhat misleading.

There is token that is more or less id, but it's identification of the device. You are not using it to send anything.
Token id is generated for that specific device and will never change. (Don't know about anonymous login)
Basically token ID can change when one of the next possibilities occur:
  • The app deletes Instance ID.
  • The app is restored on a new device
  • The user uninstall/reinstall the app
  • The user clears app data.

B4X:
Sub Process_Globals
    Public fa As FirebaseAuth
End Sub

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

Sub fa_TokenAvailable (User As FirebaseUser, Success As Boolean, TokenId As String)
    'Token id
End Sub

Message token is what you will be using for your notifications. When you design your app you should also notice that it can change.
Not frequently, but it can and after that if your app doesn't handle refreshed message token correctly your server will contain old token that doesn't work.

B4X:
Sub Process_Globals
    Public fm As FirebaseMessaging
End Sub

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

Sub fm_TokenRefresh (Token As String)
    'Message token
End Sub
 
Last edited:
Upvote 0

Dianzoa

Active Member
Licensed User
The problem I try to solve is that usually I used an asp script to check for DB changes, and if someone has a job to do, according to the DB value, I send it a notification to that phone, but, since android 8.1 kills the app after a while if the phone is not active, I try to resolve this with firebase notifications for the specific user that has changed his state en in DB. I don't know if this would work, since the app it's not running anyways. I probably need to write a script that check the DB changes in the server and then try to send the notification to the users that had changed their job state.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
EDIT: Or, firebase know all the tokens and associates to the phone automatically?

Firebase does know all token which they send out.
 
Upvote 0

Dianzoa

Active Member
Licensed User
SOLVED:
I just changed the tutorial code a little bit. For example, when a user login, I have a global variable with his ID, in the starter. Than I just subscribe to that ID in the firebaseservice like this:
B4X:
Public Sub SubscribeToTopics
    fm.SubscribeToTopic(Starter.idrepartidor) 'you can subscribe to more topics
End Sub
Than from the webapp that request a job for that driver, I just sent the message to starter.idrepartidor (or the equivalent id) like this:
B4X:
Sub AppStart (Args() As String)
    SendMessage(4, "Esto es una prueba", "Hello!!!!")
    StartMessageLoop
End Sub
Of course the "4" is actually a DB ID from my webapp. And works like a charm, so if android kills my app, but a client request a service from an specific driver, the phone attached to that user id will receive the notification.

I just now have to convert this b4J code to VB.NET code to send the message to Firebase.
 
Upvote 0

Dianzoa

Active Member
Licensed User
I can't do the json string the right way. is this correct, it keeps getting and error 400 bad request
B4X:
Dim strNJson As String = "{""notification"":{""title"":""EnviaPy - Nuevo Pedido"",""body"":""Nuevo Pedido de " + Trim(Session("nombre")) + "},""to"":/topics/" + idrepartidor.ToString + "}"
 
Upvote 0

Dianzoa

Active Member
Licensed User
UPDATE: After I left the phone for about 12 hours without activity, and then return and send the push messages, does not arrive any notification or message to the phone :( . So I have the same problem that I had before implementing this push notifications. The user can not know about a job because it get no notification at all :(
 
Upvote 0

Dianzoa

Active Member
Licensed User
how are you sending the pushnotification?
Make sure to use the B4J Code (or similar JSON-Output).
https://www.b4x.com/android/forum/t...-messages-firebase-cloud-messaging-fcm.67716/

Make sure to send DATA Notification.
Even the official example in b4J does not send the notification, now that the phone kills the app. If the firebaseService is runnig it works.
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)
    m.Put("data": data)
    Dim jg As JSONGenerator
    jg.Initialize(m)
    Job.PostString("https://fcm.googleapis.com/fcm/send", jg.ToString)
    Log(jg.ToString)
    Job.GetRequest.SetContentType("application/json")
    Job.GetRequest.SetHeader("Authorization", "key=" & API_KEY)
End Sub
 
Upvote 0

Dianzoa

Active Member
Licensed User
I jut run the app, and kill it, and now it works, it seems that if the phone is out of activity a long time the push notification does not work anymore. I thought it has to work all the time, since that the purpose of sendind push notifications to the device?
EDIT: You need to try this. Stop the app, or better, in the settings go and Force Stop. Then the push notifications won't arrive.
 
Upvote 0
Top