Android Question Php + sql + notification push

luisro

Member
Licensed User
Hello ladies and gentlemen, I have a doubt for a couple of months, i'm developing a simple database query app, following the example of php and mysql, the only thing I want is that if someone inserts, deletes or modifies some data in our database that is in a personal domain, send a notification with the specific change to all who have the app installed, i am not an expert programmer, I have seen all the examples of both firebase and notification push, but I am not sure how to do it.

I was thinking of a server in the pc that makes constant queries and from there send notification if there is a change to the devices with the app

Any help will be very grateful. Greetings.
 

KMatle

Expert
Licensed User
Longtime User
Use firebase messages (search for it). There's an example how to send messages via php here, too. Use topics.

So if you update something via MySQL send a message to a topic and all devices which have registered to that topic will receive a message.

You need to check the docs and examples here
 
Upvote 0

luisro

Member
Licensed User
I will try again, I will review all the tutorials of firebase.

Likewise I will explain a little better what I need and my application.

I am developing an app that registers an internal work within the company that works there contains data (date, responsible and a list of spare parts).

My app connects to the database using a php script, and I use a phpmyadmin db on my company's domain server, I will also create it with visual basic a program to record jobs when it is on the desktop or laptop pc.

A single person can register the work, when a new job is registered, a notification will be sent to the bosses or managers that are 6. "A new job has been registered with the number X" "A job X has been requested."

I describe it in case you recommend something else

Sorry for my english (google translate)
 
Upvote 0

BillMeyer

Well-Known Member
Licensed User
Longtime User
Luisro,

Let me try to help. This is what I would do to resolve your problem.

1. Begin with MySQL and create a new table that holds the information for the messages that you want to send.
2. Now work with Triggers. Tutorial Here. Create a trigger to fire whenever a user loads a new job to insert the message data in the new table.
3. I use B4J for the next step but VB should work. Create a desktop "server" that looks every few minutes at the "New Table" and finds if a new job has been created. Use this to send a message then to Firebase to send a new Push Notification message.

Here is some sample code for sending the message (in B4J)
B4X:
Private Sub SendMessage(Topic As String, Title As String, Body As String)
    Dim Job As HttpJob
    Job.Initialize("SendMessage2", Me)
'   Dim m As Map = CreateMap("to": $"/topics/${Topic}"$)
'   Dim m As Map = CreateMap("to": $"${FBM.Token}"$) 'this will send the message to ONE device - you need to get this token from a specific device.
    Dim m As Map = CreateMap("to": $"${PrivToken}"$) 'this will send the message to All devices - PrivToken - you get from your Firebase Server
    Dim data As Map = CreateMap("title": Title, "body": Body)
    m.Put("data", data)
    Dim jg As JSONGenerator
    jg.Initialize(m)
    Log(Job.PostString("https://fcm.googleapis.com/fcm/send", jg.ToString))
    Job.GetRequest.SetContentType("application/json;charset=UTF-8")
    Job.GetRequest.SetHeader("Authorization", "key=" & "Your Key Here")
End Sub

4. In b4a, you will create an app to accept the incoming message and act on it. Remember you need a service called "FirebaseMessaging". Typically the code would look something like this (it is in the Firebase tutorial as well - forgive the duplication)

B4X:
Sub Process_Globals
    Private fm As FirebaseMessaging
End Sub

Sub Service_Create
    fm.Initialize("fm")
    LogColor("In Firebase Messaging Service",Colors.Red)
    SendMessage("general","app: job Monitor","Welcome to Job Monitor")
End Sub

Public Sub SubscribeToTopics
    fm.SubscribeToTopic("general") 'you can subscribe to more topics - this is case sensitive - See note below
    Log("Device Token: "&fm.token)
End Sub

Sub Service_Start (StartingIntent As Intent)
    If fm.HandleIntent(StartingIntent) Then Return
End Sub

Sub fm_MessageArrived (Message As RemoteMessage)
    Log("Message arrived")
    Log($"Message data Token: ${Message.GetData.Get("token")}"$)
    Dim n As Notification
    n.Initialize
    n.Icon = "icon"
    n.SetInfo(Message.GetData.Get("title"), Message.GetData.Get("body"), Main)
    n.Notify(1)
End Sub

Sub Service_Destroy

End Sub

Note: When you create your Firebase project and you wish to have several topics that your user can subscribe to - you will notice that you cannot create them in Firebase. Your first message might arrive saying "null, null" - this is OK - just send a message to each topic you want and give Firebase a day or so and they will magically appear as topics on your Firebase Console. If you now send a message to a specific topic it should be received correctly.

Now all you need to do is react to your message.

Remember from here you can decide what to do. You can load the job data in the message with JSON and then decode it when it arrives and display this in your app or you could react to your message that contains a job number and then via your php web service retrieve the data from your MySQL server and display that on your app.

I trust that this will give some pointers in the right direction.
 
Upvote 0

luisro

Member
Licensed User
Woow is exactly what I was looking for, after reading and reading the firebase tabs I think I'm starting to understand, I already configured the client application correctly (I already send messages from the firebase console), now I need to configure the B4J with Sql trigger(Probable solution to notify the changes in the database), then comment as I was.

Super grateful with your contributions, thank you very much.
 
Upvote 0

KMatle

Expert
Licensed User
Longtime User
Triggers is a goog idea but it's more technical. When there's more business logic I recommend doing the decision inside your php script (after the insert, update, delete, etc.) and sending the messages via php with this:

B4X:
print notify($devt, $m);


function notify ($devt, $m)
    {
    print 'In';
    // API access key from Google API's Console
        if (!defined('API_ACCESS_KEY')) define( 'API_ACCESS_KEY', 'AAAAMxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' );
        $tokenarray = array($devt);
        // prep the bundle
        $msg = array
        (
            'message'     => $m   
        );
        $fields = array
        (
            'to'     => $devt,
            'data'    => $msg
        );
        
        $headers = array
        (
            'Authorization: key=' . API_ACCESS_KEY,
            'Content-Type: application/json'
        );
        
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        curl_close( $ch );
       
        return $result;
    }
 
Upvote 0
Top