Thursday, 15 September 2016

Firebase Cloud Messaging FCM on Android device

Steps to integrate Firebase Cloud Messaging FCM with android.



1.open firebase.google.com
------------------------------------------------------
2.click on "go to console" which will be displayed on top right of the screen
------------------------------------------------------
3.now link will be directed to https://console.firebase.google.com/
------------------------------------------------------
4.click on create new project
------------------------------------------------------
5.now a pop up will come, asking to you to enter the project name and country. you can give any name. no restriction to the app name. enter the name of your country.
------------------------------------------------------
6.create project
------------------------------------------------------
7.click on firebase to your app(for android)
------------------------------------------------------
8.copy application id from(your android project which you want to integrate FCM) your app level gradle file and paste it to package name field in firebase. In the same package firebase(related) service classes should present.
------------------------------------------------------
9.copy debug key sha1 and paste it to debug key field in firebase.
Note: use this command to get sha1 key from windows
installed java path.....jdk/bin>keytool -list -v -keystore c:\users\systemname\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android
note down sha1 key and paste it.
------------------------------------------------------
10.now click add app, now google-services.json file will be downloaded. paste this file in app directory.
------------------------------------------------------
11.open your project level grade file. add this - classpath 'com.google.gms:google-services:3.0.0' line in dependencies
------------------------------------------------------
12.open app level gradle file , paste this line - apply plugin: 'com.google.gms.google-services' at the bottom of the file.
------------------------------------------------------
13.add following lines in the app level gradle file.
compile 'com.google.firebase:firebase-messaging:9.4.0'
    compile 'com.google.firebase:firebase-auth:9.4.0'
    compile 'com.google.firebase:firebase-core:9.4.0'
    compile 'com.firebase:firebase-client-android:2.5.2+'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
Note: always add updated dependencies.(https://firebase.google.com/docs/android/setup)
------------------------------------------------------
14.add FirebaseInstanceIDService.java file
Note: change ip address in the below file

import android.util.Log;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class FirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        String token = FirebaseInstanceId.getInstance().getToken();
        Log.d("token refresh =",token);
        registerToken(token);
    }
    private void registerToken(String token) {
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("Token",token)
                .build();

        Request request = new Request.Builder()
                .url("http://your-ip-address/fcm/register.php")
                .post(body)
                .build();

        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
------------------------------------------------------
15.now add FirebaseMessagingService.java

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.firebase.messaging.RemoteMessage;

public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService{

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d("msg=",remoteMessage.getNotification().getBody());
        showNotification(remoteMessage.getData().get("message"),remoteMessage.getNotification().getTitle());
    }

    private void showNotification(String message,String title) {
        Log.d("wht is msg=",message);
        Intent i = new Intent(this,MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentText(message)
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(0,builder.build());
    }
}
------------------------------------------------------
16.add the new two classes into android manifest file.(they are services , so service tags must be used to define them)
Note:this is how your manifest file look like this

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fcm.calcify.com.fcmexampple">
    <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=".FirebaseMessagingService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <service
            android:name=".FirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
    </application>
</manifest>

------------------------------------------------------

17.app level gradle file must look like this

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"

    defaultConfig {
        applicationId "fcm.calcify.com.fcmexampple"
        minSdkVersion 23
        targetSdkVersion 23
        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:23.0.0'
    compile 'com.google.firebase:firebase-messaging:9.4.0'
    compile 'com.google.firebase:firebase-auth:9.4.0'
    compile 'com.google.firebase:firebase-core:9.4.0'
    compile 'com.firebase:firebase-client-android:2.5.2+'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
}
apply plugin: 'com.google.gms.google-services'

------------------------------------------------------

18. project level gradle file

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
---------------------------------------------
19.run the android project. copy the token from the console. now it is very important to note that you get token only once(first run). if you didnt copy token file. uninstall app  clean and build it now note down token.
------------------------------------------------------
20.now open this link https://console.firebase.google.com/. if you are logged in, you will see your project created in firebase.
------------------------------------------------------
21.click on your project. now select notification from the list for left of the screen(scroll down if you cant see notification link).
------------------------------------------------------
22.now click on new message. enter message text and label. select delivery date as "send now".
------------------------------------------------------
23. select your app. now select target as single device.
------------------------------------------------------
24. after selecting single device , you will be asked to enter FCM registration token. here enter your token.
------------------------------------------------------

No comments:

Post a Comment