Pages

Monday, 27 June 2016

Firebase Cloud Messaging Tutorial for Android


Hello everyone all we know Google Cloud Messaging which sends message from server to app,  Google has introduces Firebase that allows many features including Firebase Cloud Messaging which is much more easier than Google Cloud Messaging.

Create android project in Android Studio.

Get configuration file

Go to firebase console and create new project


Now Put app name and select country from drop down



Select Add firebase to android app as shown below


After this you will ask to enter package name, after that click on add app new file in .JSON format will be downloaded into your download location.


 

Copy  that  google-services.json file  and put in your android app's main root folder.

Configuring Android application with firebase

Now go to your root level build.gradle file and add the following code.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
        //Add this line
        classpath 'com.google.gms:google-services:3.0.0'
    }
}
allprojects {
    repositories {
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

Inside app level build.gradle file copy following lines

apply plugin: 'com.android.application'
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"
    defaultConfig {
        applicationId "com.fornfromgeeks.firebase"
        minSdkVersion 8
        targetSdkVersion 23
        versionCode 2
        versionName "1.1"
    }
    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:23.4.0'
    //Add this line
    compile 'com.google.firebase:firebase-messaging:9.0.0'
}
//Add this line
apply plugin: 'com.google.gms.google-services'

Start syncing the project

Create MyFirebaseInstanceIDService.java file and copy paste following code in it.

import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
/**
* Created by Geek on 6/27/2016.
*/
//Class extending FirebaseInstanceIdService
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
    private static final String TAG = "MyFirebaseIIDService";
    @Override
    public void onTokenRefresh() {
        
        //Getting registration token
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        
        //Displaying token on logcat
        Log.d(TAG, "Refreshed token: " + refreshedToken);
        
    }
    private void sendRegistrationToServer(String token) {
        //You can implement this method to store the token on your server
        //Not required for current project
    }
}

Create another  MyFirebaseMessagingService.java file and copy paste following code in it.


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;
/**
* Created by Geek on 6/27/2016.
*/
public class MyFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        //Displaying data in log
        //It is optional
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        
        //Calling method to generate notification
        sendNotification(remoteMessage.getNotification().getBody());
    }
    //This method is only generating push notification
    //It is same as we did in earlier posts
    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);
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Firebase Push Notification from fornfromgeeks")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
    }
}

We need to define and add services in our project's manifest file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.fornfromgeeks.firebase">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>
        <!--
            Defining and Adding Services
        -->
        <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>

Its time to run the app, when you run the app you will see token in logcat, Copy that token which will use to send message form Firebase console.

Send FCM

Go to Firebase console and select your app
Select notification from left panel.
Click on new message
Enter message, select single device and paste the token you copied.

You will receive message.

Thank You ! 

No comments:

Post a Comment