Hi Guys, Welcome to Proto Coders Point, In this android tutorial we will send firebase push notification using php function/php script.
In other words, The FCM notification will be sent to particular user who are subscribed to a topic in Firebase Cloud Messaging Service.
DEMO
So let’s begin implementing this Android FCM project.
Step 1: Create a new Android Project
As usual create a new android project in your android studio
File > New > New Project
Give a name to your project say Firebase push notification service.
Step 2: Connect new Project to firebase using firebase android studio assistant
Step 1: Add Firebase Analytic
tools > firebase > select analytics
1. Connect to firebase
Hit that connect to firebase Button under assistant, This will open default browser with a firebase url to add your android project to your firebase console.
Just agree all the steps on your browser, if you face any problem to connect to firebase console check out the above video
2. Add Analytics to your app
just click on the button suggested by assistant “add analytic to your app” this will add all the required dependencies & classes.
3. Add analytic code
open MainActivity.java basically you loading or first screen of your android app.
private FirebaseAnalytics mFirebaseAnalytics; //inside of onCreate mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Step 2: Add Cloud Messaging dependencies through assistant
under the android firebase assistant search for cloud messaging under that hit “Add FCM to your app”
This will add the FCM dependencies to your android project.
Step 3: Create a new Service class for FCM Services
Create a service java (Right Click) > New > Service > service and name it a anything your wish in my case i have named it as FirebaseCloudMessagingService.java
Then, Add the below links of notification service codes.
FirebaseCloudMessagingService.java
package com.protocoderspoint.sendingpushnotificationusingphpcode; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Build; import android.os.IBinder; import androidx.annotation.NonNull; import androidx.core.app.NotificationCompat; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; public class FirebaseCloudMessagingServices extends FirebaseMessagingService { public FirebaseCloudMessagingServices() { } @Override public void onMessageReceived(@NonNull RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); if (remoteMessage.getNotification() != null) { String title = remoteMessage.getNotification().getTitle(); // will hold FCM Title String message = remoteMessage.getNotification().getBody(); //will hold FCM message body sendNotification(title,message); } } private void sendNotification(String title, String message) { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String NOTIFICATION_CHANNEL_ID = "admin_channel_1"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX); // Configure the notification channel. notificationChannel.setDescription("Sample Channel description"); notificationChannel.enableLights(true); notificationChannel.setLightColor(Color.RED); notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000}); notificationChannel.enableVibration(true); notificationManager.createNotificationChannel(notificationChannel); } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); notificationBuilder.setAutoCancel(true) .setContentIntent(pendingIntent) .setDefaults(Notification.DEFAULT_ALL) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_launcher) //.setPriority(Notification.PRIORITY_MAX) .setContentTitle(title) .setContentText(message); notificationManager.notify(1, notificationBuilder.build()); } }
Step 4: Add Volley Library
As we gonna make a call to our php script to send notification in am making use of Volley library to make a call to my service side php code
open build.gradle(app level) and all the following volley dependencies.
implementation 'com.android.volley:volley:1.1.0'
Step 5: Register/ Subscribe to Topic in java code
This is how we make the user to register or subscribe to particular topic so that we can send notification to selected topic or subscriber using the topic that user are registered too.
Snippet code to make user subscribe to a topic in FCM.
FirebaseMessaging.getInstance().subscribeToTopic("Gadgets");
Now, open strings.xml and add the following array strings
strings.xml
<resources> <string name="app_name">Sending PushNotification using php code</string> <string name="topic_selection">Choose a category: </string> <string-array name="product_topics"> <item>PC</item> <item>Laptop</item> <item>Gadgets</item> </string-array> </resources>
ok Then, Let’s design the UI of the app
acitivity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/subscribe" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Subscribe on Topic" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.269" /> <Spinner android:id="@+id/spinner" android:layout_width="409dp" android:layout_height="80dp" android:layout_marginTop="64dp" android:entries="@array/product_topics" android:gravity="center" android:prompt="@string/topic_selection" app:layout_constraintBottom_toTopOf="@+id/subscribe" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.685" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="22dp" android:text="You will get notified on selected topic only" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/subscribe" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Select a Firebase topic to get subscribed on particular topic only" app:layout_constraintBottom_toTopOf="@+id/spinner" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/getnotified" android:layout_width="247dp" android:layout_height="51dp" android:layout_marginTop="276dp" android:text="Notify Me" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" app:layout_constraintVertical_bias="0.0" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="Below button will call the php code that sends notification \n to Cloud messaging service topic you are subscribed to" app:layout_constraintBottom_toTopOf="@+id/getnotified" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" app:layout_constraintVertical_bias="0.84" /> </androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.protocoderspoint.sendingpushnotificationusingphpcode; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Spinner; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.messaging.FirebaseMessaging; import java.util.HashMap; import java.util.Map; import java.util.Random; public class MainActivity extends AppCompatActivity { private FirebaseAnalytics mFirebaseAnalytics; Spinner spinnerTopic; Button subscribe,send_Pushnotification; // this link is my server where my php script for push notification exist String URL_NOTI="https://protocoderspoint.com/php/push_notification.php"; String topic; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mFirebaseAnalytics = FirebaseAnalytics.getInstance(this); spinnerTopic = (Spinner)findViewById(R.id.spinner); subscribe=(Button)findViewById(R.id.subscribe); send_Pushnotification=(Button)findViewById(R.id.getnotified); subscribe.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { topic = spinnerTopic.getSelectedItem().toString(); System.out.println(topic); //subscribing yourself to topic you have selected from spinner FirebaseMessaging.getInstance().subscribeToTopic(topic); Toast.makeText(MainActivity.this,"Subscribed successfully to: "+topic,Toast.LENGTH_SHORT).show(); Toast.makeText(MainActivity.this,"Now just Hit Notify me Button "+topic,Toast.LENGTH_SHORT).show(); } }); send_Pushnotification.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Send_Notification(topic); } }); } private void Send_Notification(final String topic) { StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_NOTI, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e("farmerorderdataresponse",response); try{ } catch (Exception e) { e.printStackTrace(); Toast.makeText(getApplicationContext(),"Login Error !1"+e,Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(),"Login Error !2"+error,Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { Map<String,String> params = new HashMap<>(); params.put("title","Order Received"); params.put("body","This is a notification"); params.put("topic",topic); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); requestQueue.add(stringRequest); } }
Step 5: network configuration for android version 9
then you need to add a network configuration xml file where you define the network that you will be using…Usually the domain
res (right click) > New > Directory
give new diretory name as “xml”
Then, right click “xml directory” > New > xml resource file and name it as network_security_config.xml
<?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> //replace the domain name with your server domain name <domain includeSubdomains="true">protocoderspoint.com</domain> </domain-config> </network-security-config>
Step 6: PHP script to send FCM push notification
<?php $user= $_POST['topic']; $title = $_POST['title']; $body = $_POST['body']; $url = "https://fcm.googleapis.com/fcm/send"; $topic = "/topics/$user"; //replace serverkey with your firebase console project server key $serverKey = "AAAADmPIVdUXXXXXXEbfiR9c5LyXRKgq1LAWhT6a-byFe7lPXXXXXXXTjJfhHTTIo7Q997PL-89KrKagTQz26FUmyhRmhmsxQXXXXXXXWBmOuJ4-wtY_uL1-si8l3hyr5zJ-2P"; //$body = '$_POST['body']'; // $intent_filter=$action; $notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1'); $arrayToSend = array('to' => $topic, 'notification' => $notification,'priority'=>'high'); $json = json_encode($arrayToSend); $headers = array(); $headers[] = 'Content-Type: application/json'; $headers[] = 'Authorization: key='. $serverKey; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_HTTPHEADER,$headers); //Send the request $response = curl_exec($ch); //Close request if ($response === FALSE) { die('FCM Send Error: ' . curl_error($ch)); } curl_close($ch); ?>
How to get serverkey of FCM service ?
Then, where you go your app is ready to subscribe to selected topic using Spinner and will be able to recieve push notification on particular topic the app user is subscribed too firebase cloud messaging service.