Tuesday 16 August 2016

Android Firebase Cloud Messaging(FCM)

Hi,  In this post we will use FCM (Firebase Cloud Messaging). So today in this Firebase Cloud Messaging Tutorial I will teach you how to send push notification to single and multiple android devices using Firebase Cloud Messaging. So lets begin.

In AndroidManifest.xml file Register FCM service

<!-- [START firebase_service] -->
        <service
            android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <!-- [END firebase_service] -->
        <!-- [START firebase_id_service] -->
        <service
            android:name=".MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
        <!-- [END firebase_id_service] --> 

In Builde.gradle

apply plugin: 'com.android.application'

android {
  // ...
}

dependencies {
  // ...
  compile 'com.google.firebase:firebase-core:9.4.0'
}

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services' 

In Two Class Files

1. public class FcmNotifyReceiverService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        if (null != remoteMessage.getData()) {

            sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message"));

        } else {
            sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
    }

    private void sendNotification(String tittleStr, String messageBody) {

        Log.w("fcm", "messageBody " + messageBody);

        Intent mIntent = new Intent(this, SplashScreenActivity.class);
        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        android.support.v7.app.NotificationCompat.Builder b = new android.support.v7.app.NotificationCompat.Builder(this);
        b.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_notify)
                .setTicker("Tittle")
                .setContentTitle(tittleStr)
                .setContentText(messageBody)
                .setAutoCancel(false)
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
                .setContentIntent(contentIntent)
                .setContentInfo("Tittle Info");

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1, b.build());
    }

2.  public class FcmTokenService extends FirebaseInstanceIdService {

        private String serverUrl = null;

        private final String log = "TokenService ";

        // private final String ServerKey = "AIzaSyDgnQHpIPYwGxmcOFBQ2H93ClZPrHrjv_g"; // AIzaSyCwPKoCwWkjui8STXdmORZQAnFdo_otpiA";

        @Override
        public void onTokenRefresh() {

            // Get updated InstanceID token.
            String refreshedToken = FirebaseInstanceId.getInstance().getToken();
            Log.w("fcm refreshedToken ", refreshedToken);

            sendRegistrationToServer(refreshedToken);
        }

        /**
         * Register new token key to server
         *
         * @param token unique token key
         */
        private void sendRegistrationToServer(final String token) {

        }
    }

Download JSON File from firebase console and add to your project property 
More Refer this link : https://firebase.google.com/docs/cloud-messaging/android/client and 
https://www.simplifiedcoding.net/firebase-cloud-messaging-tutorial-android/