raj
raj

Reputation: 103

Send push notification to Android app after database insert or update

I'm working with SQL Server 2008 and PHP. Whenever data is inserted or updated on the database I have to send a push notification to an Android app.

The Android device token is stored in a database table. Inserted or updated data in any table send a push notification using PHP on the device token.

I have the Android code and I have wrote Firebase.php and Push.php but I don't know how to send the push notification using PHP

Firebase.php

<?php

class Firebase {

    // sending push message to single user by firebase reg id
    public function send($to, $message) {
        $fields = array(
            'to' => $to,
            'data' => $message,
        );
        return $this->sendPushNotification($fields);
    }

    // Sending message to a topic by topic name
    public function sendToTopic($to, $message) {
        $fields = array(
            'to' => '/topics/' . $to,
            'data' => $message,
        );
        return $this->sendPushNotification($fields);
    }

    // sending push message to multiple users by firebase registration ids
    public function sendMultiple($registration_ids, $message) {
        $fields = array(
            'to' => $registration_ids,
            'data' => $message,
        );

        return $this->sendPushNotification($fields);
    }

    // function makes curl request to firebase servers
    private function sendPushNotification($fields) {

        require_once __DIR__ . '/config.php';

        // Set POST variables
        $url = 'https://fcm.googleapis.com/fcm/send';

        $headers = array(
            'Authorization: key=' . FIREBASE_API_KEY,
            'Content-Type: application/json'
        );
        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        // Execute post
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }

        // Close connection
        curl_close($ch);

        return $result;
    }
}
?>

Push.php

 <?php

class Push {

    // push message title
    private $title;
    private $message;
    private $image;
    // push message payload
    private $data;
    // flag indicating whether to show the push
    // notification or not
    // this flag will be useful when perform some opertation
    // in background when push is recevied
    private $is_background;

    function __construct() {

    }

    public function setTitle($title) {
        $this->title = $title;
    }

    public function setMessage($message) {
        $this->message = $message;
    }

    public function setImage($imageUrl) {
        $this->image = $imageUrl;
    }

    public function setPayload($data) {
        $this->data = $data;
    }

    public function setIsBackground($is_background) {
        $this->is_background = $is_background;
    }

    public function getPush() {
        $res = array();
        $res['data']['title'] = $this->title;
        $res['data']['is_background'] = $this->is_background;
        $res['data']['message'] = $this->message;
        $res['data']['image'] = $this->image;
        $res['data']['payload'] = $this->data;
        $res['data']['timestamp'] = date('Y-m-d G:i:s');
        return $res;
    }

}

Those two scripts should be ok as is, but I don't know how to send the notification to the Android app after the data has been inserted (or updated) on the database.

Upvotes: 3

Views: 6728

Answers (1)

iamnaran
iamnaran

Reputation: 1964

First connect to database

init.php

<?php 

$host = "localhost";
$db_user = "root";
$db_password = "";
$db_name = "notification";

$con = mysqli_connect($host, $db_user, $db_password, $db_name);
 ?>

Then send notification using curl method

  <?php 

    if($_SERVER['REQUEST_METHOD']=='POST'){
     $full_name = $_POST['full_name'];
     $contact_number = $_POST['contact_number'];

     require_once('dbConnect.php');
     $sql = "INSERT INTO notification (full_name,,contact_number) VALUES (
         '$full_name'
         '$contact_number')";



    $check = "SELECT * from notification where full_name='$full_name' AND contact_number='$contact_number'";
         $checkData = mysqli_query($con,$check);
         if (mysqli_num_rows($checkData) > 0) {
          echo "Request already posted";
         }else{

        if(mysqli_query($con,$sql)){


                   $notiTitle = "notification request";
                   $notiMessage ="by".$full_name;

                        sendNotification($notiTitle, $notiMessage); 
            echo "sucessfully added";

            }else{
            echo "error in sending request";
            }
        }

    }else{
    echo 'error';
}


function sendNotification($title, $msg) {
    require 'init.php';
    $titlee = $title;
    $message = $msg;
    $path_to_fcm = 'https://fcm.googleapis.com/fcm/send';
    $server_key = "your_server_key";
    $sql = "SELECT app_id FROM user_app_id";
    $result = mysqli_query($con,$sql);


    // fetch all key of devices 

$finalKey=array();
while($row= mysqli_fetch_array($result)){
$finalKey[]=$row['app_id'];
}
    $headers = array(
        'Authorization:key=' .$server_key, 
                'Content-Type : application/json');

    $fields = array('registration_ids'=>$finalKey, 'notification'=>array('title'=>$title, 'body'=>$message));

    $payload = json_encode($fields);


    $curl_session = curl_init();
    curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
    curl_setopt($curl_session, CURLOPT_POST, true);
    curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
    $result = curl_exec($curl_session);
    curl_close($curl_session);
    echo $result;
    mysqli_close($con);

}
 ?>

Now in your android create two class FirebaseInstantIdService

public class FirebaseInstantIdService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
        String token = FirebaseInstanceId.getInstance().getToken();
        SharedPreferences.Editor editor = ReversifyApplication.getSharedPreference().edit();
        editor.putString(Utils.FCM_TOKEN, token);
        editor.apply();

    }
}

FirebaseMessagingServices

public class FirebaseMessagingServices extends FirebaseMessagingService {

    public static NotificationManager notificationManager;

    private String id = "";
    private String ji = "";
    private String badge = "";
    private String image = "";
    private String title = "";
    private String video = "";
    private String message = "";
    private String name = "";


    @SuppressLint("ApplySharedPref")
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.e("onMessageReceived: ", remoteMessage.getData().toString());
        for (Map.Entry<String, String> entry : remoteMessage.getData().entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            switch (key) {
                case "ji":
                    ji = determinePushNotificationSource(value);
                    break;

                case "title":
                    title = value;
                    break;

                case "message":
                    message = value;
                    break;

                case "id":
                    id = value;
                    break;
                case "badge":
                    badge = value;
                    break;
                case "image":
                    image = value;
                    break;
                case "video":
                    video = value;
                    break;
                case "name":
                    name = value;
                    break;


            }
            Utils.saveNotificationCount(badge);
        }
        if (ReversifyApplication.isActivityVisible()) {
            Intent intent = new Intent("1000");
            intent.putExtra("title", title);
            intent.putExtra("message", message);
            intent.putExtra("image", image);
            intent.putExtra("videoid", video);
            intent.putExtra("ji", ji);
            intent.putExtra("id", id);
            intent.putExtra("notification_count", badge);
            LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        } else {
            int idCurrentTime = (int) System.currentTimeMillis();
            sendNotification(idCurrentTime, title, message, ji, video, image, name, id);
            //set up badge count for supported devices
            if (ShortcutBadger.isBadgeCounterSupported(getApplicationContext())) {
                ShortcutBadger.applyCount(getApplicationContext(), Integer.parseInt(getSharedPreference().getString(Utils.NOTIFICATION_COUNT, null)));
            }
        }
    }

    /**
     * generating push notification
     */
    private void sendNotification(int id, String title, String messageBody, String type, String openID, String image, String name, String notificaiton_id) {
        Intent broadcastIntent = new Intent(this, SplashScreen.class);
        broadcastIntent.putExtra("type", type);
        broadcastIntent.putExtra("image", image);
        broadcastIntent.putExtra("message", messageBody);
        broadcastIntent.putExtra("id", notificaiton_id);
        broadcastIntent.putExtra("openID", openID);
        broadcastIntent.setAction(Intent.ACTION_MAIN);
        broadcastIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        broadcastIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        broadcastIntent.putExtra("name", name);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.push_notification)
                .setContentTitle(title)
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setPriority(Notification.PRIORITY_HIGH)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(id, notificationBuilder.build());
    }


    }

Upvotes: 2

Related Questions