FCM notification not receiving - android

I have an application which will get FCM notifications.It recived fine on devices up to marshmellow.When I insatlled it on oreo device it getting toast which says notificaton channel is null.I searched on google and I found that Notification channels are required for receiving notifications on API above 26. I added a notification channel but it shows the toast again.No notification.
My AppFirebaseMessagingService
public class AppFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String title;
String description;
String click_action;
if(remoteMessage.getData()!=null) {
title = (remoteMessage.getData().get("title") == null || remoteMessage.getData().get("title").equals("")) ? "null" : remoteMessage.getData().get("title");
description = (remoteMessage.getData().get("body") == null || remoteMessage.getData().get("body").equals("")) ? "null" : remoteMessage.getData().get("body");
click_action = (remoteMessage.getData().get("click_action") == null || remoteMessage.getData().get("click_action").equals("")) ? "null" : remoteMessage.getData().get("click_action");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String id = "id_product";
// The user-visible name of the channel.
CharSequence name = "Product";
// The user-visible description of the channel.
description = "Notifications regarding our products";
int importance = NotificationManager.IMPORTANCE_MAX;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
notificationManager.createNotificationChannel(mChannel);
}
//Notification----------------------
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(AppFirebaseMessagingService.this);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle(title);
mBuilder.setContentText(description);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
SharedPreferences sharedpreferences = getSharedPreferences(Common.preferenceName, Context.MODE_PRIVATE);
String RoleCSV=sharedpreferences.getString(Common.roleCSV,"");
}
}
}
My Androidmanifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".AppFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".AppFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name=".Login"
android:configChanges="orientation|screenSize"
android:screenOrientation="portrait"
android:theme="#style/Theme.Design.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".HomeScreen"
android:configChanges="orientation|screenSize" />
<activity
</application>

I write the piece of code for checking if the device is oreo
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
NotificationManager notificationManager1 = (NotificationManager)
getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager1.createNotificationChannel(notificationChannel);
}
mNotification = builder
.setLargeIcon(image)/*Notification icon image*/
.setContentText(messageBody)
.setSmallIcon(R.drawable.dhlone)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image).bigLargeIcon(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent)
.setBadgeIconType(R.drawable.dhlone)
.setAutoCancel(true)
.setSmallIcon(getNotificationIcon())
.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext()
.getResources(),R.drawable.dhlone))
.build();
notificationManager1.notify(/*notification id*/0, mNotification);

private fun createNotification(title: String, message: String) {
val resultIntent = Intent(this, LoginActivity::class.java)
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val mBuilder = NotificationCompat.Builder(this)
mBuilder.setSmallIcon(R.drawable.ic_stat_name)
mBuilder.setContentTitle(title)
.setContentText(message)
.setAutoCancel(false)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(resultPendingIntent)
val mNotificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
val importance = NotificationManager.IMPORTANCE_HIGH
val notificationChannel = NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.enableVibration(true)
notificationChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID)
mNotificationManager.createNotificationChannel(notificationChannel);
}
mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
}

Related

Android 12 tap on notification not retrieve data payload on onNewIntent()

Hello Developers I am doing Android Push Notification functionality in Android 12 Native. Currently I am facing issue with not retrieve data payload when application is in background or it was closed.
Here is my notification function in MyFirebase Messaging.
#SuppressLint("WrongConstant")
public void setNotificationBuilder(Context context, String remoteMessage) {
try {
JSONObject jsonObject = new JSONObject(remoteMessage);
Intent fullScreenIntent = new Intent(context, NavigationActivity.class);
fullScreenIntent.putExtra("data", jsonObject.toString());
fullScreenIntent.putExtra("key", "credence");
fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent fullScreenPendingIntent;
if (Build.VERSION.SDK_INT >= 31) {
fullScreenPendingIntent = PendingIntent.getActivity(context, 0, fullScreenIntent, PendingIntent.FLAG_MUTABLE);
} else {
fullScreenPendingIntent = PendingIntent.getActivity(context, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "message_channel_id_1";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Credence Message", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Sample Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_launcher)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.setContentIntent(fullScreenPendingIntent)
.setContentTitle(jsonObject.optString("title"))
.setContentText(jsonObject.optString("body"))
.setContentInfo(jsonObject.toString());
notificationManager.notify(1, notificationBuilder.build());
/* Intent intent1 = new Intent("intent_data");
intent1.putExtra("data", jsonObject.toString());
sendBroadcast(intent1);*/
} catch (Exception ex) {
ex.printStackTrace();
}
}
I am able to receive notification in notification tray but unable to receive data payload and perform action on it.
i refer articles and found some solution and implement another way to handle push notification.
private void openAndroid12Notification(RemoteMessage remoteMessage){
Intent TrampolineActivityIntent = new Intent(getApplicationContext(), NavigationActivity.class);
TrampolineActivityIntent.putExtra("data", "Hello World");
TrampolineActivityIntent.putExtra("key", "xyzzz");
TrampolineActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = TaskStackBuilder.create(getApplicationContext()).addNextIntentWithParentStack(TrampolineActivityIntent).getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "message_channel_id_1";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Credence Message", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Sample Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setPriority(Notification.PRIORITY_MAX)
.setSmallIcon(R.drawable.ic_launcher)
.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
.addAction(R.drawable.ic_launcher, "NOTIFICATION_CLICK", pendingIntent)
.setContentIntent(pendingIntent)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setContentInfo(remoteMessage.getData().toString());
notificationManager.notify(1, notificationBuilder.build());
}
and define action in manifest file.
<activity
android:name=".NavigationActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="#string/app_name"
android:launchMode="singleInstance"
android:exported="true"
android:screenOrientation="portrait"
android:theme="#style/MyThemeblue">
<intent-filter>
<action android:name="NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="NavigationActivity.RELOAD" />
</intent-filter>
</activity>
notification popes up but not received data payload on background, foreground or kill.
Here is my notification json format:
{
"notification": {
"title": "Test Message 1",
"body": "Test Body 1",
"click_action": "NOTIFICATION_CLICK"
},
"data": {
"requireInteraction": false,
"date": "26/12/2022",
"notificationId": "jshdsd0-dkncd-dcnkdnc-dnckdncd",
"title": "fbfbfbdk Notification",
"body": "Rdgdfer",
"content": "fgdgf.",
"click_action": "NOTIFICATION_CLICK"
},
"registration_ids": [
"token"
],
"priority": "high"
}
i want handle data payload in background and when application is closed.

Oreo failed to post notification on channel null

i am trying to make notification push using FCM but every time when i am trying to send notification my Emulator always toasting failed to post notification on channel null,
i have trying many ways about posting notification on channel, but none of it is correct
i am using 'com.google.firebase:firebase-messaging:10.2.0'
here is my code
private void sendMyNotification(String message) {
int NOTIFICATION_ID = 234;
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
String CHANNEL_ID = "my_channel_01";
CharSequence name = "my_channel";
String Description = "This is my channel";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
mChannel.setDescription(Description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mChannel.setShowBadge(false);
notificationManager.createNotificationChannel(mChannel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("LALALLA")
.setContentText(message);
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
notificationManager.notify(NOTIFICATION_ID, builder.build());
} else {
//On click of notification it redirect to this Activity
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);
Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("My Firebase Push notification")
.setContentText(message)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
notificationManager.notify(0, notificationBuilder.build());
}
my manifest.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>
i solved my problem by upgrading my 'com.google.firebase:firebase-messaging:10.2.0' to newer version
for example , now iam using : 'com.google.firebase:firebase-messaging:11.8.0'

Android Firebase notification have no sound

I'm getting Firebase notification sound while app runs and not getting notification sound while app is in background. I don't know why it is happening.
This is what I tried
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
// To Configure the notification channel.
notificationChannel.setDescription("Sample Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.gj512x512)
.setContentText(message)
.setSound(sound)
.setContentTitle(title)
.setAutoCancel(true)
.setContentIntent(pendingIntent);
notificationManager.notify(1, noBuilder.build());
}
Please help me with this.
Just do one thing say your backend developer to just send data payload in the notification, ask him to restrict and remove notification payload,
Because when you are getting a notification at that time if your app in the background and you are getting notification payload at that time system handle notification from their side and that's why problem arise,
So simply just remove notification payload from the server-side and it will work fine.
Add your php code like bellow for data
$title = 'Whatever';
$message = 'Lorem ipsum';
$fields = array
(
'registration_ids' => ['deviceID'],
'priority' => 'high',
'data' => array(
'body' => $message,
'title' => $title,
'sound' => 'default',
'icon' => 'icon'
)
);
notificationChannel.setSound(null,null); // remove this line
.setSound(sound) //replace this line with this
setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
if you're using FCM, you don't need to implement notification codes, unless you need to customize it for your app (for example special light, special sound, special vibration and...).
otherwise, you can just have a class like this and set manifest's things too
FCM Class:
public class FcmMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
showNotification(Objects.requireNonNull(remoteMessage.getNotification()).getTitle(), remoteMessage.getNotification().getBody());
}
private void showNotification(String title, String body) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "net.Test.id";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription("Description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableLights(true);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL).setWhen(System.currentTimeMillis()).setSmallIcon(R.drawable.ic_launcher_foreground).setContentTitle(title).setContentText(body).setContentInfo("Info");
assert notificationManager != null;
notificationManager.notify(new Random().nextInt(), notificationBuilder.build());
}
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.d("TOKEN", s);
}
}
manifest flie:
<service
android:name="arbn.rahyab.rahpayadmin.data.network.fcm.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/googleg_standard_color_18" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/colorAccent" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="001" />
if you want to customize it, write codes inside FCN class.

How Should I Change My Pushnotification Icon For My app

I want to change my push notification icon.
Code Snippet :
public class Mymessagingservice extends FirebaseMessagingService {
public void onMessageReceived(RemoteMessage remoteMessage){
super.onMessageReceived(remoteMessage);
getimage(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
public void getimage(String title,String message){
NotificationCompat.Builder builder=new NotificationCompat.Builder(this,"mynotification")
.setContentTitle(title)
.setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
R.drawable.otplogo
))
.setSmallIcon(R.drawable.otplogo)
.setAutoCancel(true)
.setContentText(message);
NotificationManagerCompat manager =NotificationManagerCompat.from(this);
manager.notify(999,builder.build());
}
}
Unfortunately this was a limitation of Firebase Notifications in SDK 9.0.0-9.6.1. When the app is in the background the launcher icon is use from the manifest (with the requisite Android tinting) for messages sent from the console.
With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/google_blue" />
Note that if the app is in the foreground (or a data message is sent) you can completely use your own logic to customise the display. You can also always customise the icon if sending the message from the HTTP/XMPP APIs.
You have to put this tag inside Application tag of manifest
Official doc- https://firebase.google.com/docs/cloud-messaging/android/client
Thanks to this guy - https://stackoverflow.com/a/37332514/4741746
Bro its too simple but you have to do it carefully.
First, make a black & white icon for your notification.
Now set it in your notification as a small icon like below.
mBuilder.setSmallIcon(R.mipmap.notification_icon);
now you can set a color but if I am right so you can set only predefined color instead of custom. For custom color you can try with your logic I am giving you a code of a predefined color.
mBuilder.setColor(Color.GREEN);
It will make your notification icon Color green.
Happy Coding!!!
UPDATE
Code for custom notification.
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
0 /* Request code */, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri soundUri = Uri.parse("android.resource://" + mContext.getApplicationContext()
.getPackageName() + "/" + R.raw.sniper_gun);
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.notification_icon);
mBuilder.setSound(soundUri);
if (image!=null) {
mBuilder.setContentTitle(title)
.setContentText(message)
.setAutoCancel(false)
.setLargeIcon(image)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image).setSummaryText(message).bigLargeIcon(null))
.setColor(Color.GREEN)
.setContentIntent(resultPendingIntent);
}
// else {
// mBuilder.setContentTitle(title)
// .setContentText(message)
// .setAutoCancel(false)
// .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
// .setContentIntent(resultPendingIntent);
// }
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
// set custom soundUri
if(soundUri != null){
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
notificationChannel.setSound(soundUri,audioAttributes);
}
assert mNotificationManager != null;
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify(0 /* Request Code */, mBuilder.build());

Push notification onMessageReceived method in FirebaseMessagingService is not called?

I already Implemented the service in android manifest and still no response from the FirebaseMessagingService service. The weird thing is that the notification is successfully sent. When I tried to debug and add the breakpoint to the onMessageReceived method I can received the notification but when I install it first without attaching the debug the service is not called so no callback response from the FirebaseMessagingService. So basically FirebaseMessagingService will work if I debug the app but when it is not in debug no callback is called from the FirebaseMessagingService.
The phone that I used is Samsung galaxy J7pro android version OREO(API 27).
AndroidManifest.xml
added the following in the manifest file.
<service android:name=".services.InstanceIDListenerService"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".services.NotificationService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
build.gradle(app)
added the following in the build.gradle file.
implementation 'com.google.firebase:firebase-messaging:17.3.4'
implementation 'com.google.firebase:firebase-core:16.0.5'
}
apply plugin: 'com.google.gms.google-services'
NotificationService.java
public class NotificationService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// dbManagerPushNotification.DBManagerPushNotification(this);
if (remoteMessage.getData().size() > 0) {
Map<String, String> remoteMessage_getData = remoteMessage.getData();
String community_slug = remoteMessage_getData.get("community_slug");
String conversation_id = remoteMessage_getData.get("conversation_id");
String sender_id = remoteMessage_getData.get("sender_id");
final String message_id = remoteMessage_getData.get("message_id");
String message = remoteMessage_getData.get("message");
String convo_type = remoteMessage_getData.get("convo_type");
String created_at = remoteMessage_getData.get("created_at");
String title = remoteMessage_getData.get("title");
Log.i("push_notification", "onMessageReceived: " + message);
final String channel_id = title + community_slug;
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("message", message);
intent.putExtra("message_id", message_id);
intent.putExtra("conversation_id", conversation_id);
intent.putExtra("sender_id", sender_id);
intent.putExtra("community_slug", community_slug);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), message_id.hashCode(), intent, 0);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
SpannableStringBuilder spannableStringBuilder_title = new SpannableStringBuilder(title);
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
spannableStringBuilder_title.setSpan(boldSpan, 0, title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(channel_id, title, NotificationManager.IMPORTANCE_HIGH);
AudioAttributes attributes = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build();
mChannel.enableLights(true);
mChannel.setLightColor(Color.WHITE);
assert notificationManager != null;
notificationManager.createNotificationChannel(mChannel);
}
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), channel_id)
.setSmallIcon(R.drawable.ic_notif_logo)
.setColor(0xECEFF1)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setGroup(convo_type)
.setGroupAlertBehavior(GROUP_ALERT_CHILDREN)
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.selection_orange))
.setPriority(NotificationCompat.PRIORITY_MAX);
String community_notif = " " + community_slug + ": ";
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(community_notif);
spannableStringBuilder.setSpan(new ForegroundColorSpan(getApplicationContext().getResources().getColor(R.color.selection_orange)), 0, community_notif.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
NotificationCompat.Builder summaryNotification = new NotificationCompat.Builder(getApplicationContext(), channel_id)
.setContentTitle(title)
.setSmallIcon(R.drawable.ic_notif_logo)
.setStyle(new NotificationCompat.InboxStyle().setSummaryText(TextUtils.concat(spannableStringBuilder, title)).setBigContentTitle(TextUtils.concat(spannableStringBuilder, title)))
.setGroup(convo_type)
.setAutoCancel(true)
.setGroupAlertBehavior(GROUP_ALERT_CHILDREN)
.setColor(ContextCompat.getColor(getApplicationContext(), R.color.selection_orange))
.setGroupSummary(true)
.setPriority(NotificationCompat.PRIORITY_MAX);
assert notificationManager != null;
notificationManager.notify(message_id.hashCode(), mBuilder.build());
notificationManager.notify(channel_id.hashCode(), summaryNotification.build());
}
}
}

Categories

Resources