In this tutorial, we will learn “How to make Android Push Notifications using Firebase Cloud Messaging FCM”
First of all, you should know about the concept of Firebase, Cloud Messaging, and FCM.
Firebase:
Firebase is part of a growing trend known as “Backend as a service.” It is a technology that lets you compose the web or mobile applications without server-side programming so that development turns out to be quicker and easier.
What Can We Do With FireBase?
With Firebase, we don’t have to stress over servers or building REST APIs.
With this we just implement a little bit of configuration. We can also take every necessary step like ☟:
☑ Storing data.
☑ Verifying users
☑ Implementing access rules.
What technology does it support?
It supports:
- The web
- iOS
- OSX
- Android.
Benefits of Using FireBase:
- No need to do server side coding.
- Synced across connected devices in milliseconds, which is available when your app goes offline.
Google Cloud Messaging:
- Google Cloud Messaging (commonly referred to as GCM) is a mobile notification service developed by Google that supports third-party application developers to send notification message from developer-run servers to applications that target the Google Android Operating System, as well as applications/extension developed for the Google Chrome internet browser.
- It is free for developers.
- It has been replaced by Google’s Firebase Cloud Messaging (FCM).
Firebase Cloud Messaging:
In this, we basically send push messages and receive them as notification. It is basically a new version of cloud messaging now let’s discuss how it works:
Firebase push notification consists of two major processes
- Involvement of client registration.
- Broadcasting of the message from the FCM to all users.
Process:
- The user sends a request to firebase for registration.
- The Firebase will respond in a string containing the unique token that will be generated for the particular user.
- The token we obtain is supposed to be saved somewhere so we need a remote server that has installed database our remote server accepts the token and saves it into the database.
Tutorial:
Getting Started With FireBase:
1. Create a Project:
- Go to below link:
https://console.firebase.google.com/?pli=1
- Create new project. For creating a new project, you have to set the country name and project name.
- After that project will be created.
- Select “Add Firebase to your Android App.”
- A new popup will appear. We must provide a package name so go to your android studio app copy your package name and type it.
2. Adding Google-service file to Project:
☛ Click on “ADD App” button in order to create “google-services.json” file.
- You will get a popup to save “google-services.json.”
- ADD “google-services.json” file in app file of your project.
- By that, Google services which are a plugin for Gradle will load the google-services.json file that you just downloaded.
3. Adding Dependencies:
- Here, it says that we need to add some dependencies to our project so copy the selected portion then paste it in the version of build.gradle settings file.
- Click on below link ☟:
- Also add this ☟ dependency to your build.gradle (Module:app) apps version:
- compile ‘com.google.firebase:firebase-messaging:9.8.0‘
- Add the dependency ☟ for the firebase SDKs you want to use. I recommended starting with this one.
- compile ‘com.google.firebase:firebase-core:9.8.0’
- After that press on the upper left Sync Now option after that press FINISH button.
- We need to add service used to receive device token.
- For that, we have to make class
- In Android -> app -> java -> 1stfolder of
your package right clicks on New -> javaclass. - After that type class name: FirebaseInstanceIDService then do the coding.
4. Code For FireBase Instance ID Service:
import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; /** * Created by Habaiba Abbasi on 09/11/2016. */ //for background notifications //it receives the token from firebase when the device id registered public class FirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String registed_Token="registed_Token"; @Override public void onTokenRefresh() { String recent_token= FirebaseInstanceId.getInstance().getToken(); // get token from the server Log.d(registed_Token,recent_token); // show device token in Log cat View /* If you want to send messages to this application instance or succeed this application contributions on the server side, send the Instance ID token to your app server. */ sendRegistrationToServer(recent_token); } // this method is used to send token to your app server. private void sendRegistrationToServer(String token) { } }
5. Type Code For Message Service:
import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; /** * Created by Habaiba Abbasi on 09/11/2016. */ public class MessageService extends FirebaseMessagingService { @Override //this method is called when we received the message from Fcm public void onMessageReceived(RemoteMessage remoteMessage) { //used for notifying the user in the form of notification Intent intent=new Intent(this,MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pi = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder notificationBuilder=new NotificationCompat.Builder(this); // set notification properties notificationBuilder.setContentTitle("FCM Test"); //title of notification notificationBuilder.setContentText(remoteMessage.getNotification().getBody()); //in this method we pass extracted message to get actual message we pass parameter remotemessage which contain actual data. // tgetData returns the datatype of object that saves information in key value //to get value from our message we call method get with the key being message notificationBuilder.setAutoCancel(true); notificationBuilder.setSmallIcon(R.mipmap.ic_launcher); // change notification icon notificationBuilder.setContentIntent(pi); NotificationManager manager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); manager.notify(0,notificationBuilder.build()); }
6. Edit your AndroidManifest.xml file:
☛ Add this line.
<uses-permission android:name=“android.permission.INTERNET”></uses-permission>
- Now, open a browser then select Firebase then move to console select your application then click on manage.
- On left side select notification from the menu.
- Select new text then in message text type your message selects your delivery data and message label (optional) in target select user segment after that select your package name.
☞ Click on send a message.
Final Output:
Congratulations! You’ve received your notification of Android Push Notifications using Firebase Cloud Messaging FCM.
Dear HABIBA ABBASI,
Good tutorial thanks for your tutorial, its really helpful for new guys whom all looking for push notificastion.
I have one doubt on integrating push notification in my project which is “Can you tell me how to navigate to specific activity when click on notification. Default it’s open app. But I need to know how to open an specific activity. ”
Let me know. Thanks in advance.
Hi Viswanath Thanks!
In Message service class replace MainActivity.class with your specific activity you want to open in below intent .
Intent intent=new Intent(this,MainActivity.class);