Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Firebase Android Sample for managing notification
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
/**
* This is called whenever app receives notification
* in background/foreground state so you can
* apply logic for background task, but still Firebase notification
* will be shown in notification tray
*/
public class FirebaseDataReceiver extends WakefulBroadcastReceiver {
private final String TAG = "FirebaseDataReceiver";
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "I'm in!!!");
if (intent.getExtras() != null) {
for (String key : intent.getExtras().keySet()) {
Object value = intent.getExtras().get(key);
Log.e("FirebaseDataReceiver", "Key: " + key + " Value: " + value);
}
}
}
}
<!-- [START firebase_service] -->
<service android:name=".fcm.MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_service] -->
<!-- [START firebase_iid_service] -->
<service android:name=".fcm.MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<!-- [END firebase_iid_service] -->
<receiver
android:name=".fcm.FirebaseDataReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</receiver>
<!-- [START FCM notification icons] -->
<!--
Set custom default icon. This is used when no icon is set for incoming notification messages.
See README(https://goo.gl/l4GJaQ) for more.
-->
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_stat_notification" />
<!--
Set color used with incoming notification messages. This is used when no color is set for the incoming
notification message. See README(https://goo.gl/6BKBk7) for more.
-->
<!--<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/accent" />-->
<!-- [END FCM notification icons] -->
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Logcat.e(TAG, "Refreshed token: " + refreshedToken);
PreferenceData.setStringPref(PreferenceData.KEY_GCM_ID,this,refreshedToken);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]
/**
* Persist token to third-party servers.
*
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
// TODO: Implement this method to send token to your app server.
}
}
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
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;
import java.util.Random;
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.
*/
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// [START_EXCLUDE]
// There are two types of messages data messages and notification messages. Data messages are handled
// here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
// traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
// is in the foreground. When the app is in the background an automatically generated notification is displayed.
// When the user taps on the notification they are returned to the app. Messages containing both notification
// and data payloads are treated as notification messages. The Firebase console always sends notification
// messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
// [END_EXCLUDE]
//"Title","Message","NotyType", "hotelStatus"
String title = "";
if (remoteMessage.getNotification().getTitle() != null){
title = remoteMessage.getNotification().getTitle();
}
String message = "";
if (remoteMessage.getNotification().getBody() != null){
message = remoteMessage.getNotification().getBody();
}
Log.e("notification","recieved");
sendNotification(title, message);
// 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.
}
// [END receive_message]
/**
* Create and show a simple notification containing the received GCM message.
*
* @param message GCM message received.
*/
private void sendNotification(String title, String message) {
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_notification)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(getRequestCode(), notificationBuilder.build());
}
private static int getRequestCode() {
Random rnd = new Random();
return 100 + rnd.nextInt(900000);
}
}
@neeraj87

This comment has been minimized.

Copy link

@neeraj87 neeraj87 commented Sep 21, 2017

In the new API 26 for Oreo, the NotificationCompat.Builder() constructor takes context and channelId as the second param. Can you also show how to do it using channel id?

@afarber

This comment has been minimized.

Copy link

@afarber afarber commented Nov 23, 2017

For the new constructor check my answer to the NotificationCompat.Builder deprecated in Android O question

@Rakshithkhatokar

This comment has been minimized.

Copy link

@Rakshithkhatokar Rakshithkhatokar commented Feb 26, 2018

HI have implemented, as per the above steps, and it is working fine,But sometimes the notification is getting duplicated and getting all messages in one single flush, please help in resolving this issue

@samirmangroliya

This comment has been minimized.

Copy link

@samirmangroliya samirmangroliya commented Feb 27, 2018

Android Oreo > kill your application and send push notification with data messages it will not work.

@shubhamkhuva

This comment has been minimized.

Copy link

@shubhamkhuva shubhamkhuva commented Mar 27, 2018

Its working but it will not work on Oreo

@raja-arumugam

This comment has been minimized.

Copy link

@raja-arumugam raja-arumugam commented Jul 6, 2018

How to display the string value from the FCM?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment