Skip to content

Instantly share code, notes, and snippets.

@swapnil20711
Last active June 29, 2021 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swapnil20711/c2d95c9767815047e48e5a6af9f52723 to your computer and use it in GitHub Desktop.
Save swapnil20711/c2d95c9767815047e48e5a6af9f52723 to your computer and use it in GitHub Desktop.
public class FCMReceiver extends FirebaseMessagingService {
private static final String CHANNEL_ID = "Notification_channel";
Random random = new Random();
/*
* This is automatically called when notification is being received
* */
@Override
public void onMessageReceived(@NonNull @NotNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
createNotificationChannel();
if (remoteMessage.getData().get("for") != null) {
if (remoteMessage.getData().get("for").equals(FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber())) {
showNotification(remoteMessage);
}
}
}
/*
* Method to show notification when received
* */
private void showNotification(RemoteMessage remoteMessage) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getString(R.string.app_name))
.setSmallIcon(R.drawable.ic_notification_icon)
.setContentText(remoteMessage.getData().get("body"))
.setColor(ContextCompat.getColor(this,R.color.notification_red));
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
// notificationId is a unique int for each notification that you must define
notificationManager.notify(random.nextInt() + 1000, builder.build());
}
/*
* Method to create notification channel
* */
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment