Visit https://firebase.google.com/docs/cloud-messaging/android/client for more details
1) Create your app and add it as a project in firebase https://console.firebase.google.com/
2) Add your projects package name while creating the project
3) Download the google-services.json (will be downloaded automatically) and save it in your app module (while opening the project in project tab)
4) Add the classpath dependency in project level gradle and apply plugin dependency in app level gradle
- classpath ‘com.google.gms:google-services:3.0.0’
- apply plugin: ‘com.google.gms.google-services’
5) Add the firebase dependency for fcm to support cloud messaging
- compile ‘com.google.firebase:firebase-messaging:9.0.2’
6) In your Manifest create two services which extend
- FirebaseMessagingService – to receive message (override its onMessageReceived function to get the remote message)
-
public class MyFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); } }
- FirebaseInstanceIdService – to refresh device token (override its onTokenRefresh function to get the new token)
-
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { @Override public void onTokenRefresh() { super.onTokenRefresh(); String refreshToken = FirebaseInstanceId.getInstance().getToken(); Log.d("refreshToken", "onTokenRefresh: " + refreshToken); } }
Add these two services in your manifest
<?xml version="1.0" encoding="utf-8"?> <manifest package="com.example.sanket.pocfcm" xmlns:android="http://schemas.android.com/apk/res/android"> <application ...> <activity ...> </activity> <service android:name=".MyFirebaseMessagingService"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service> <service android:name=".MyFirebaseInstanceIDService"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> </intent-filter> </service> </application> </manifest>
7) You can test notifications from the notification console of your app https://console.firebase.google.com/project/<YOUR_PROJECT_NAME_HERE>/notification