Firebase is a powerful platform for building mobile and web based applications. It helps developer to build high-quality apps and games. Firebase provides facilities of real time database and synchronization, user authentication service, analytical tools, hosting web site, send notification and many more. Before the Google I/O 2016 event, we had worked with Google Cloud Messaging service to send messages or notifications from the server to the clients or mobile app users. In Google I/O 2016, Google introduced the firebase cloud messaging.
Steps for sending message using firebase.
Step 1:
First of All, we create project on google firebase console, Here is the link of it: https://console.firebase.google.com/
Add project name and country name in new project. After the firebase dashboard is visible to you, select appropriate technology. We needed for android so we clicked android app icon.
After that, below screen will be visible. Add package name of new project and SHA-1 key to the Project.
Once you submit all the information, firebase gives you google-services.json which contains all information regarding your project. Copy this file and paste this file into your app directory e.g. //app/(paste here).
Step 2:
Now let us start the coding part. After creating new project, copy google-service.json file. Add google play services. Open project level build.gradle file and place below line and sync project.
// google services
classpath ‘com.google.gms:google-services:3.0.0’
Example:
dependencies { classpath 'com.android.tools.build:gradle:2.1.0' classpath 'com.google.gms:google-services:3.0.0' }
Step 3:
Now open your app level build.gradle file and paste below line
- add apply plugin: ‘com.google.gms.google-services’
- compile ‘com.google.firebase:firebase-messaging:9.0.2’
press Sync now.
Example:
fdR88blS-wU:APA91bETjBJCZD-MGf5F7LUl58_x4OP9ilQa0YZ3vcEs8Bwt15_CderfFtHA7cEWPGH5WmkS0C77hyVYIG-zUlmhZK9eSk4zvY5TzaCZYnMySgMZm4WCIDFEG19P5xt-qy6bibY2m9x- apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' android { compileSdkVersion 24 buildToolsVersion "24.0.1" defaultConfig { applicationId "firebase.sample.yudiz.firebasesample" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:24.2.1' compile 'com.google.firebase:firebase-messaging:9.0.2' }
Step 4:
Create user registration service that extends by FirebaseInstanceIdService and override onTokenRefresh method which fire when new token is generated. It contains token and token helps to send notification. If we want to send a particular notification to a particular user then token will help to identify users.
Sample code is below :
public class FirebaseRegistation extends FirebaseInstanceIdService { private static final String TAG = "FirebaseApp"; @Override public void onTokenRefresh() { //Getting registration token of FCM String refreshedToken = FirebaseInstanceId.getInstance().getToken(); //Displaying token on your logcat Log.d(TAG, "Refreshed token: " + refreshedToken); //send FCM token to web service sendRegistrationToServer(refreshedToken); } private void sendRegistrationToServer(String token) { //You can implement this method to store the token on your server for your further implementation //Not required for current project } }
Step 5:
Create message service that extends FirebaseMessagingService which received message from firebase and display to the user. It is required to override onMessageReceived method with RemoteMessage object. So RemoteMessage give notification object for accessing notification in App.
Sample code is below :
public class FirebaseMessaging extends FirebaseMessagingService { private static final String TAG = "FireBaseMessage"; @Override public void onMessageReceived(RemoteMessage remoteMessage) { RemoteMessage.Notification notification = remoteMessage.getNotification(); Log.d(TAG, "Notification Message Body: " + notification.getBody()); //Calling method to generate notification sendNotification(notification.getBody()); } //This method is only for generating push notification private void sendNotification(String messageBody) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Firebase Notification") .setContentText(messageBody) .setAutoCancel(true) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, notificationBuilder.build()); } }
Step 6:
Declare all services in manifest file with permissions.
Sample code is below :
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="firebase.sample.yudiz.firebasesample"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".services.FirebaseMessaging"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> <service android:name=".services.FirebaseRegistation"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service> </application> </manifest>
Step 7:
Now run application and test notification message. For Testing purpose, Firebase provided facilities of it. Look in the below screen, click it is your project structure in firebase. Click Notifications and get console of sending notification for testing. Just type message, Select App and send it. Enjoy…!
Step 8:
Finally got Notification in Application . Yuppy ….!!!