Wednesday, August 24, 2016

Firebase Messaging Service Example Android

Add gradle dependency,

dependencies {
    compile 'com.google.firebase:firebase-messaging:9.0.0'}

Create MyFirebaseInstanceIDService.java and MyFirebaseMessagingService.java


import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;


public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    private static final String TAG = "MyFirebaseIIDService";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        sendRegistrationToServer(refreshedToken);
    }
  
    private void sendRegistrationToServer(String token) {
        // here implement method that sends token to store somewhere to reuse.    }
}

and

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;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    /**     * Called when message is received.     *     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.     */
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO(developer): Handle FCM messages here.        // If the application is in the foreground handle both data and notification messages here.        // Also if you intend on generating your own notifications as a result of a received FCM        // message, here is where that should be initiated. See sendNotification method below.        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        sendNotification(remoteMessage.getNotification().getBody());
    }

    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 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

Add these to AndroidManifest.xml, 

<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>

That's it. Very Simple. Here is sample that is getting through RemoteMessage.

Log.d(TAG, "remoteMessage" + remoteMessage.getData());
Log.d(TAG, "APS: " + remoteMessage.getData().get("aps"));

private String id, title, msg, type, image, sound;
try { if (remoteMessage.getData() != null) { id = remoteMessage.getData().get("id"); title = remoteMessage.getData().get("title"); msg = remoteMessage.getData().get("msg"); type = remoteMessage.getData().get("type"); image = remoteMessage.getData().get("image"); sound = remoteMessage.getData().get("sound");

        sendNotification();
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

No comments:

Post a Comment