Firebase push Notification using curl command — Devoid Backend

Foram Shah
AndroidPub
Published in
6 min readMar 9, 2017

--

Why android developer have to depend on backend for everything? Well this might be no more a thing to deal with as we can remove the backend dependency in several ways. One such way is stated below.

So let’s vacant backend for push notification using firebase.

Firebase provides Firebase Cloud Messaging(FCM) to send push Notification. FCM implementation include an application server that send messages and a client application that receives it, along with it firebase also provides the facility to compose messages from the Notification Console itself. Now consider a scenario where you want to send notification after some event occurs. So, at runtime notification console can’t be used to send notification to a particular user. Now what?????

Don’t think much as we have a solution for that. So lets have a look of how it works.

Firstly to send push Notification, FCM token is required for every user so we need to store one for each user. Now consider a scenario where User can use application in multiple device for instance user can register from one device and login through other device. So we need to store a FCM token twice, first during the registration process and second at time of login where we need to update the same token.

To achieve this what we would require in the first place is : Set up the firebase.

As We have already discussed how to setup Firebase in my previous blog, follow this to see .

After setting up firebase project we need to store FCM token for all the users and to do this we’ve to first get the token, See how:

String FCMToken= null;
try {
FCMToken = FirebaseInstanceId.getInstance().getToken();
/** Store this token to firebase database along with user id **/
} catch (Exception e) {
e.printStackTrace();
}

Now basically there are two options are available to store FCM token, First in User table(where all of application user’s information has been stored) and second to maintain a separate table for user id and FCM token. Below is an example where I have used a separate table for user id and FCM token.

Now you have to add below classes in your project.

import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {private static final String TAG = "MyFirebaseIIDService";/**
Called if InstanceID token is updated. This may occur if the security of the previous token had been compromised. Note that this is called when the InstanceID token is initially generated so this is where you would retrieve the token.
*/
@Override
public void onTokenRefresh()
{
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token = " + refreshedToken);
// If you want to manage this apps subscriptions on the server side, send the Instance ID token to your app server. sendRegistrationToServer(refreshedToken);
}
/** Modify this method to associate the token with any server-side account maintained by your application.
*
@param token The new token.
*/
private void sendRegistrationToServer(String token)
{
// TODO: Implement this method to send token to your app server.
}
}
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

private static final String TAG = "MyFirebaseMsgService";

/** Called when message is received.
@param remoteMessage the message received from Firebase Cloud Messaging.
*/

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

// There are two types of messages data messages and notification messages. Data messages are handled here in onMessageReceived whether the app is in the foreground or background. Data messages are the type traditionally used with FCM. Notification messages are only received here in onMessageReceived when the app is in the foreground. When the app is in the background an automatically generated notification is displayed.When the user taps on the notification they are returned to the app. Messages containing both notification and data payloads are treated as notification messages.

Log.d(TAG, "From: " + remoteMessage.getFrom());

// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null)
{
Log.d(TAG, "Message Notification Body: " remoteMessage.getData().get("title"));
}

//Display notification in notification bar
sendNotification(remoteMessage.getData().get("title"));
}


/**Create and show a simple notification containing the received push Notification.
*
@param messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
Intent intent = new Intent(this,"Activity name where you want to redirect when user click on notification");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri=
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("FCM Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);

NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

}
}

Now to send a notification, we need to slam POST request so for that use OKHTTP. In order to use OKHTTP add gradle dependency in build.gradle file. Below is dependency for OKHTTP. Change to latest version (Try and find out the latest available version while integrating.)

compile 'com.squareup.okhttp3:okhttp:3.3.0'

Lets see how we can generate notification POST request.

A message request consists of two parts: (a). HTTP Header and (b). HTTP Body.

The HTTP header must contain the following headers:

  • Authorization: key=YOUR_SERVER_KEY
  • Make sure this is the server key, whose value is available in your Firebase project console under Project Settings > Cloud Messaging.
  • Content-Type: application/json for JSON; application/x-www-form-urlencoded;charset=UTF-8 for plain text.
  • If Content-Type is omitted, the format is assumed to be plain text.
  • Now we can frame below request.
curl -X POST --header "Authorization: key=<SERVER KEY>" \
--Header "Content-Type: application/json" \
https://fcm.googleapis.com/fcm/send \
-d "{\"to\":\"<FCM TOKEN>\",\"notification\":{\"body\":\"ENTER YOUR MESSAGE HERE\"}"

We can use GSON library to make this JSON request. To operate GSON include below dependency.(Try and find out the latest available version while integrating.)

compile 'com.google.code.gson:gson:2.8.0'

Below is complete code to frame above POST invocation.

Gson gson = new Gson();
Data data = new Data();
data.setTitle("Enter your message here");
PostRequestData postRequestData = new PostRequestData();
postRequestData.setTo("Enter receiver FCM token here");
postRequestData.setData(data);
String json = gson.toJson(postRequestData);
String url = "https://fcm.googleapis.com/fcm/send";

final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();


RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.header("Authorization", "key=YOUR SERVER KEY")
.post(body)
.build();


Callback responseCallBack = new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.v("Fail Message", "fail");
}

@Override
public void onResponse(Call call, Response response) throws IOException {
Log.v("response", response.toString());
}


};
okhttp3.Call call = client.newCall(request);
call.enqueue(responseCallBack);

Check out PostRequestData model class down.

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class PostRequestData {
@SerializedName("data")
@Expose
private Data data;
@SerializedName("to")
@Expose
private String to;

public Data getData() {
return data;
}

public void setData(Data data) {
this.data = data;
}

public String getTo() {
return to;
}

public void setTo(String to) {
this.to = to;
}

}

After sending message we should also be conversant with response.

There are two possible outcomes when trying to send a notification:

  • The message is processed successfully if the HTTP response has a 200 status code, and the body contains more information about the status of the message.
  • The FCM server rejects the request if the HTTP response contains a non-200 status code (such as 400, 401 or 5xx).

That’s all I apprised of firebase runtime push Notification without notification console.

If you have any query or suggestions you can reach out me at forampshahh@gmail.com.

Hope you liked this concept!!

--

--

Foram Shah
AndroidPub

Android developer @IndiaNIC| Always be the hardest worker in the room.