Push Notifications in Android with PHP CodeIgniter

Posted by

Push notifications are an essential tool for engaging users on mobile platforms. They allow you to send real-time updates, alerts, and messages directly to users’ devices, even when the app isn’t actively running. In this article, we’ll explore how to implement push notifications in an Android application using PHP and CodeIgniter.

Understanding Push Notifications

Push notifications are short messages or alerts that appear on the user’s mobile device. These notifications can include text, images, or actions and are designed to draw the user’s attention to something important. They are commonly used in various applications, including news apps, social media platforms, e-commerce, and more.

Prerequisites

Before diving into the implementation, ensure you have the following:

  1. Android Studio: For developing the Android application.
  2. Firebase Account: Google Firebase is a platform that provides tools for building high-quality apps, including Firebase Cloud Messaging (FCM) for sending push notifications.
  3. PHP with CodeIgniter Framework: CodeIgniter is a powerful PHP framework with a small footprint, which is ideal for building web applications, including the backend for push notifications.

Step 1: Setting Up Firebase Cloud Messaging (FCM)

Firebase Cloud Messaging (FCM) is the most popular service for sending push notifications to Android devices. Follow these steps to set up FCM:

  1. Create a Firebase Project:
  • Go to the Firebase Console.
  • Click on “Add Project” and follow the instructions to create a new project.
  1. Add Firebase to Your Android App:
  • After creating the project, click on “Add app” under the Android icon.
  • Register your app by providing the package name and other details.
  • Download the google-services.json file and place it in the app directory of your Android project.
  1. Integrate FCM in Your Android App:
  • Add the Firebase SDK dependencies in your build.gradle file:
    gradle dependencies { implementation platform('com.google.firebase:firebase-bom:26.1.0') implementation 'com.google.firebase:firebase-messaging' }
  • Initialize Firebase in your app by calling FirebaseApp.initializeApp(this); in the onCreate() method of your MainActivity.

Step 2: Building the Backend with CodeIgniter

The backend will handle sending push notifications to FCM. We will create an endpoint that the Android app can call to trigger a push notification.

  1. Create a Controller for Notifications:
  • In your CodeIgniter project, create a controller named Notification.php in the application/controllers directory.
  • Inside this controller, create a method called sendNotification() to handle the notification logic.
   <?php
   defined('BASEPATH') OR exit('No direct script access allowed');

   class Notification extends CI_Controller {

       public function sendNotification()
       {
           $this->load->helper('url');
           $this->load->library('curl');

           $token = $this->input->post('token'); // FCM token of the device
           $message = $this->input->post('message'); // Message to send

           // Prepare the notification payload
           $data = [
               'to' => $token,
               'notification' => [
                   'title' => 'New Notification',
                   'body' => $message,
                   'sound' => 'default'
               ],
               'data' => [
                   'extra_data' => 'This is some extra data'
               ]
           ];

           $headers = [
               'Authorization: key=' . 'YOUR_SERVER_KEY', // Replace with your server key from Firebase Console
               'Content-Type: application/json'
           ];

           // Send the notification using cURL
           $ch = curl_init();
           curl_setopt($ch, CURLOPT_URL, 'https://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($data));

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

           curl_close($ch);

           // Output the result
           echo $result;
       }
   }

In this code:

  • The token and message are received via POST requests.
  • The data array contains the notification payload sent to FCM, including the to field (the device’s FCM token) and the notification details.
  1. Configuring Routes:
  • In application/config/routes.php, add a route for the sendNotification() method:
   $route['send-notification'] = 'notification/sendNotification';

Step 3: Sending Push Notifications from the Android App

Now that the backend is set up, the Android app can send requests to trigger push notifications.

  1. Requesting the Notification:
  • In your Android app, use OkHttp or Retrofit to send a POST request to the sendNotification endpoint on your CodeIgniter server.
   OkHttpClient client = new OkHttpClient();

   RequestBody body = new FormBody.Builder()
       .add("token", FCM_TOKEN)
       .add("message", "This is a test message")
       .build();

   Request request = new Request.Builder()
       .url("https://your-domain.com/send-notification")
       .post(body)
       .build();

   client.newCall(request).enqueue(new Callback() {
       @Override
       public void onFailure(Call call, IOException e) {
           e.printStackTrace();
       }

       @Override
       public void onResponse(Call call, Response response) throws IOException {
           if (response.isSuccessful()) {
               Log.d("Notification", "Push notification sent successfully");
           }
       }
   });

Step 4: Testing Push Notifications

To test the setup:

  1. Ensure your Android device is connected to the internet.
  2. Run your Android app and make sure it obtains the FCM token.
  3. Trigger the sendNotification method from your Android app.
  4. Check if the push notification appears on the Android device.

Handling Notifications in the Android App

When a push notification is received, it will be handled by the FirebaseMessagingService class in your Android app. Override the onMessageReceived() method to customize how notifications are displayed and handled:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

   @Override
   public void onMessageReceived(RemoteMessage remoteMessage) {
       // Handle FCM messages here.
       if (remoteMessage.getNotification() != null) {
           // Display notification
           showNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
       }
   }

   private void showNotification(String title, String body) {
       NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "YOUR_CHANNEL_ID")
           .setSmallIcon(R.drawable.ic_notification)
           .setContentTitle(title)
           .setContentText(body)
           .setPriority(NotificationCompat.PRIORITY_HIGH);

       NotificationManagerCompat manager = NotificationManagerCompat.from(this);
       manager.notify(0, builder.build());
   }
}

Conclusion

Implementing push notifications in an Android app using PHP CodeIgniter and Firebase Cloud Messaging is straightforward and highly effective. By following this guide, you can set up a backend to send push notifications, integrate FCM into your Android app, and deliver real-time messages to your users. Push notifications can significantly enhance user engagement, making them a crucial feature in modern mobile applications.

More Post Like This :- PHP Display Errors

Leave a Reply

Your email address will not be published. Required fields are marked *