Android Firebase notification have no sound - android

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.

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.

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());

FCM push notification not working on some devices

We have created an chat app with notifications using FCM my code is correct my device is getting the push notification data as well but some Chinese manufactured device like vivo, oppo, one plus, xiaomi are not allowing the notification to show unless i add app in protected app list of respective manufacturer. is their any solution for this.
https://hackernoon.com/notifications-in-android-are-horribly-broken-b8dbec63f48a
https://github.community/t5/Project-Development-Help-and/Firebase-Push-Notification-not-receiving-on-some-android-devices/td-p/5489
private NotificationManagerCompat notificationManager;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d("test","call");
notificationManager = NotificationManagerCompat.from(this);
sendNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
}
private void sendNotification(String title, String msg) {
Intent resultIntent = new Intent(this, ActivitySplashScreen.class);
String channelId = getString(R.string.chc);
String channelName = "Message Notification";
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(99, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(msg)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(pendingIntent)
.build();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager manager = getSystemService(NotificationManager.class);
NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
notificationManager.notify(10, notification);
}
I can confirm that this implementation works well with One Plus and Xiaomi devices (we have plenty of users using our app from this devices, and no crashes or issues are created from them regarding FCM Notifications).
Cannot confirm anything for Vivo or Oppo (so far, we do know we don't have users using this kind of devices).
The most important thing is that the notification feature is well implemented if regarding the app is either in foreground or background. If someone wants to do a zoom on this matter, this article explains it on a easy way.
Now, the code I use for FCM implementation in Android:
//MyMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
public static final String TAG = "Firebase Msg";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Map<String, String> data = remoteMessage.getData();
final LocalNotification localNotification = new LocalNotification();
//data --> entityId - entityType - pushNotificationType
// Check if message contains a data payload.
if (data.size() > 0) {
localNotification.setEntityId(data.get("entityId"));
localNotification.setEntityType(data.get("entityType"));
localNotification.setPushNotificationType(data.get("pushNotificationType"));
localNotification.setTitle(data.get("title"));
localNotification.setBody(data.get("body"));
localNotification.setIcon(data.get("icon"));
localNotification.setDate(new Date().getTime());
localNotification.setRead(false);
}
if (localNotification.getEntityId() != null) {
LocalNotification notificationRetrieved = FirebaseNotificationsHelper.insertLocalNotification(localNotification);
FirebaseNotificationsHelper.createNotificationInStatus(notificationRetrieved);
}
}
}
//Create notification status
static void createNotificationInStatus(LocalNotification localNotification) {
String notificationChannelId = App.getContext().getString(R.string.default_notification_channel_id);
String notificationChannelName = App.getContext().getString(R.string.default_notification_channel_name);
String notificationChannelDescription = App.getContext().getString(R.string.default_notification_channel_description);
NotificationCompat.Builder notificationBuilder;
NotificationCompat.Builder notificationBuilderPublicVersion;
notificationBuilder = new NotificationCompat.Builder(App.getContext(), notificationChannelId);
notificationBuilderPublicVersion = new NotificationCompat.Builder(App.getContext(), notificationChannelId);
notificationBuilder.setDefaults(NotificationCompat.DEFAULT_VIBRATE | NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.DEFAULT_SOUND)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_stat_push_notif)
.setTicker(localNotification.getTitle())
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setContentTitle(localNotification.getTitle())
.setContentText(localNotification.getBody())
.setStyle(new NotificationCompat.BigTextStyle().bigText(localNotification.getBody()))
.setPublicVersion(notificationBuilderPublicVersion.setSmallIcon(R.drawable.ic_stat_push_notif).setContentTitle(localNotification.getTitle()).
setWhen(System.currentTimeMillis()).setContentText(localNotification.getBody()).build())
.setGroup(NOTIFICATION_GROUP)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setAutoCancel(true);
int notificationId = SharedPreferencesUtils.getInstance(App.getContext()).getIntValue(PREF_KEY_NOTIFICATION_ID, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId, notificationChannelName, NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
notificationChannel.setDescription(notificationChannelDescription);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(notificationChannel);
notificationManager.notify(notificationId, notificationBuilder.build());
} else {
/* Kitkat and previous versions don't show notifications using NotificationManagerCompat */
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
NotificationManager notificationManager = (NotificationManager) App.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationId, notificationBuilder.build());
} else {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(App.getContext());
notificationManager.notify(notificationId, notificationBuilder.build());
}
}
notificationId++;
SharedPreferencesUtils.getInstance(App.getContext()).setValue(PREF_KEY_NOTIFICATION_ID, notificationId);
}
I donot think that there is a general solution for this since your app is based on google-FCM that means that the android device regularly comunicates with google-internet-services.
As far as i know google-FCM is blocked (= not reachable) in china

Android push notification not working when app is killed in OREO

I am using FCM along with PHP to send notification. It is working fine when,
App is in foreground, background and killed (below oreo )
App is in
foreground, background and not when killed(in oreo)
I even tried creating Notification Channel and tried removing 'notification' from php script too but nothing works.I have tried all the duplicate answers in SO but nothing works. Any help would be great. Thanks.
Here is my code,
#SuppressLint("NewApi")
private void sendNotification1(RemoteMessage remoteMessage) {
Log.e("remoteMessage", remoteMessage.getData().toString());
String title = remoteMessage.getNotification().getTitle();
String body = remoteMessage.getNotification().getBody();
Intent resultIntent = new Intent(getApplicationContext(), SplashActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
0 /* Request code */, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultsound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
OreoNotification oreoNotification = new OreoNotification(this);
Notification.Builder builder = oreoNotification.getOreoNotification(title, body, pendingIntent, defaultsound, String.valueOf(R.drawable.appicon3copy));
int i = 0;
oreoNotification.getManager().notify(i, builder.build());
}
Here is the OreoNotification Class,
public class OreoNotification extends ContextWrapper {
private static final String CHANNEL_ID = "Fcm Test";
private static final String CHANNEL_NAME = "Fcm Test";
private NotificationManager notificationManager;
public OreoNotification(Context base) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel();
}
}
#TargetApi(Build.VERSION_CODES.O)
private void createChannel() {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Fcm Test channel for app test FCM");
channel.enableLights(true);
channel.enableVibration(true);
channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
channel.setShowBadge(false);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
getManager().createNotificationChannel(channel);
}
public NotificationManager getManager() {
if (notificationManager == null) {
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
return notificationManager;
}
#TargetApi(Build.VERSION_CODES.O)
public Notification.Builder getOreoNotification(String title, String body, PendingIntent pendingIntent, Uri soundUri, String icon) {
return new Notification.Builder(getApplicationContext(), CHANNEL_ID)
.setAutoCancel(true)
.setSmallIcon(R.drawable.appicon3copy)
.setContentTitle(title)
.setContentText(body)
.setContentIntent(pendingIntent);
}
}
Here is the part of my PHP Script,
$msg = array
(
'body' => utf8_encode('Firebase Push Notification'),
'title' => utf8_encode('Anusha Kumar'),
'click_action' => ('.SplashActivity'),
);
$fields = array
(
'to' => $_REQUEST['token'],
'notification' => $msg , // tried removing this line too but doesn't work
'data'=>$msg,
);

FCM notification not receiving

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());
}

Categories

Resources