Skip to content

Instantly share code, notes, and snippets.

@jirawatee
Last active July 14, 2022 20:58
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jirawatee/85d4b46a89b9ae821b63c31f5d5189de to your computer and use it in GitHub Desktop.
Save jirawatee/85d4b46a89b9ae821b63c31f5d5189de to your computer and use it in GitHub Desktop.
FCM - MyFirebaseMessagingService.java
package com.example.fcm;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(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.
RemoteMessage.Notification notification = remoteMessage.getNotification();
Map<String, String> data = remoteMessage.getData();
sendNotification(notification, data);
}
/**
* Create and show a custom notification containing the received FCM message.
*
* @param notification FCM notification payload received.
* @param data FCM data payload received.
*/
private void sendNotification(RemoteMessage.Notification notification, Map<String, String> data) {
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "channel_id")
.setContentTitle(notification.getTitle())
.setContentText(notification.getBody())
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setContentInfo(notification.getTitle())
.setLargeIcon(icon)
.setColor(Color.RED)
.setLights(Color.RED, 1000, 300)
.setDefaults(Notification.DEFAULT_VIBRATE)
.setSmallIcon(R.mipmap.ic_launcher);
try {
String picture_url = data.get("picture_url");
if (picture_url != null && !"".equals(picture_url)) {
URL url = new URL(picture_url);
Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
notificationBuilder.setStyle(
new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(notification.getBody())
);
}
} catch (IOException e) {
e.printStackTrace();
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Notification Channel is required for Android O and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"channel_id", "channel_name", NotificationManager.IMPORTANCE_DEFAULT
);
channel.setDescription("channel description");
channel.setShowBadge(true);
channel.canShowBadge();
channel.enableLights(true);
channel.setLightColor(Color.RED);
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500});
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
}
@idurucz
Copy link

idurucz commented Dec 27, 2018

This more or less aligns with all the implementations of FCM I can find on the internet, but I think there are issues with it.
(I am testing this on a Galaxy S9 real device)

  • the Lights/Vibration isn't happening upon recieving the notification. Only system default vibration/sound occurs.
  • the NotificationChannel created does not appear in the Settings/Apps/$App/Notification ->Categories subsection (only Miscellaneous appears)

I think the major issue, or what really bothers me is that why would a notification channel need be defined and created upon every single notification recieved. I think the channel creaton should sit outside the service and the service should just assign the right channel to each notification.
When I moved the createNotificationChannel method outside the service (moved to MainActivity onCreate) the notification channel category appeared alongside with Misc as expected, however I can't think of a good or better place for the createNotificationChannel method, since there is no gurantee anything gets created...
Any thoughts?

@EMAD-ABD
Copy link

Thank you, I searched for a long time and this was a perfect lines. you just have to add a function that create a random no. and add it instead of id(0), this will make you receive more than on not. in same time.
I've a question if you doesn't matter is there a way to show the notifications (title & body ) in unique activity as a textview

@asrafulattare
Copy link

asrafulattare commented Aug 26, 2019

I want to be set in my app custom sounds play when I get notifications!
Where i set sound can you help me please!

I will try to

Uri uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.diciri1);
notificationBuilder.setSound(uri);
But when i send notification my app will be crash

Here logcat report

Process: com.example.ciyashop, PID: 13336
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at com.example.ciyashop.fcm.MyFirebaseMessagingService.sendNotification(MyFirebaseMessagingService.java:96)
at com.example.ciyashop.fcm.MyFirebaseMessagingService.onMessageReceived(MyFirebaseMessagingService.java:47)

@jirawatee
Copy link
Author

Sorry, as I know you cannot set custom notification sound by programming.

@iyxan23
Copy link

iyxan23 commented Jul 14, 2020

Nice example! Thanks a bunch!

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