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,
);
Related
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
I am making MQTT client app using paho MQTT client dependency.
Implementing code in a Background Service. and everything works well except the Notification isn't working!
Service code snippet is here:
My Codes occurs inside the TimeDisplayTimerTask inner-class.
This code located at the callback function :
#Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
mIntent = new Intent(getApplicationContext(), MainActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, mIntent, 0);
createNotificationChannel();
Toast.makeText(getApplicationContext(),"A message received : "+ new String(message.getPayload()),Toast.LENGTH_SHORT).show();
vibrator.vibrate(500);
myRingtone.play();
mBuilder .setContentTitle("Message received at : " + mTopic)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setContentText("Message : "+ new String(message.getPayload()));
mNotificationManager.notify(0, mBuilder.build());
}
And this code creates a notification channel (as Google developers guide mentioned to write):
Posted with help of this answer.
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String chanel_id = "3000";
CharSequence name = "Mqtt message";
String description = "Message arrived";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel mChannel = new NotificationChannel(chanel_id, name, importance);
mChannel.setDescription(description);
mChannel.enableLights(true);
mChannel.setLightColor(Color.BLUE);
mNotificationManager = getSystemService(NotificationManager.class);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(mChannel);
}
mBuilder = new NotificationCompat.Builder(getApplicationContext(), chanel_id);
}
else
{
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(getApplicationContext());
}
}
When it receives a message, A toast message appears holding the message.
But it doesn't push notification.
Checked Apps and Notifications, All notifications are allowed.
SOLVED :
the setter method .setSmallIcon must be called to successfully build a notification.
Which was not important to me.
I am trying to make push notification using Firebase to my app. I tried it and it works perfectly in the background in Oreo, but when I try to open the app and send a notification from another account, the notification does not appear.
How do I solve this and where is the problem in my code?
This is part of the code of my service:
public class FirebaseMessagingService extends
com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(messageTitle)
.setContentText(messageBody);
Intent resultIntent = new Intent(this, MainAdsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
int id = (int) System.currentTimeMillis();
builder.setContentIntent(pendingIntent);
startForeground(id,builder.build());
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(id, builder.build());
}
}
Android manifest file:
<service
android:name=".FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
Cloud functions
const functions = require('firebase-functions');
const admin=require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const api = admin.firestore()
api.settings({timestampsInSnapshots: true})
exports.fuync=functions
.firestore.document("Users/{userid}/notification/{notification_id}")
.onWrite((change,context)=>{
const userid=context.params.userid;
const notification_id=context.params.notification_id;
return admin.firestore().collection('Users')
.doc(userid).collection('notification')
.doc(notification_id).get().then(queryRes
ult=>{
const fromuserid=queryResult.data().from;
const frommessage=queryResult.data().message;
const
fromdata=admin.firestore()
.collection('Users').doc(fromuserid).get();
const todata=admin.firestore()
.collection('Users').doc(userid).get();
return Promise.all([fromdata,todata]).then(result=>{
const fromname=result[0].data().name;
const toname=result[1].data().name;
const tokenid=result[1].data().token_id;
//return console.log("from :" +fromname + "TO: " +toname);
const payload= {
notification: {
title : "notification from" +fromname,
body : frommessage,
icon : "default"
}
};
return admin.messaging().sendToDevice(tokenid,payload).then(result=>{
return console.log("NOTIFICATION SENT.");
});
});
});
});
build gradle
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.example.amr.app"
minSdkVersion 18
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner
buildToolsVersion '27.0.3'
}
This is the solution I have done and works perfectly in foreground and background for Oreo version and higher versions.
Creating a notification channel is very crucial. The most important thing is the String id inside NotificationChannel channel = new NotificationChannel().
it must be the one provided by firebase which is : default_notification_channel_id
and the code will be like this:
private static final CharSequence NAME = "amro";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
//____ID _____
int id = (int) System.currentTimeMillis();
//_____NOTIFICATION ID'S FROM FCF_____
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
NotificationCompat.Builder builder =
new NotificationCompat
.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(messageTitle)
.setContentText(messageBody);
//_____REDIRECTING PAGE WHEN NOTIFICATION CLICKS_____
Intent resultIntent = new Intent(this, ProfileActivity.class);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(pendingIntent);
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ) {
int importance = NotificationManager.IMPORTANCE_HIGH;
String channelID = BuildConfig.APPLICATION_ID;
NotificationChannel channel = new NotificationChannel
(getString(R.string.default_notification_channel_id), BuildConfig.APPLICATION_ID, importance);
channel.setDescription(channelID);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
//assert notificationManager != null;
notificationManager.createNotificationChannel(channel);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(id, builder.build());
}
Since android oreo there is Channel
When you target Android 8.0 (API level 26), you must implement one or more notification channels. If your targetSdkVersion is set to 25 or lower, when your app runs on Android 8.0 (API level 26) or higher, it behaves the same as it would on devices running Android 7.1 (API level 25) or lower.
try to using support library 26 or later and check this Create and Manage Notification Channels
try to use this method to create NotificationCompat.Builder
public NotificationCompat.Builder initChannels() {
if (Build.VERSION.SDK_INT < 26) {
return new NotificationCompat.Builder(this);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = BuildConfig.APPLICATION_ID;
NotificationChannel channel = new NotificationChannel(id, BuildConfig.APPLICATION_ID, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(BuildConfig.APPLICATION_ID);
notificationManager.createNotificationChannel(channel);
return new NotificationCompat.Builder(this, id);
}
the create new instance from this method
NotificationCompat.Builder builder = initChannels();
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
try
String messageTitle = remoteMessage.getData().getTitle();
String messageBody = remoteMessage.getData().getBody();
First add logs in onMessageArrived()
Log.d("Firebase PM service", "onMessageArrived called");
and check if you are getting this log in LogCat.
If you don't, then something is not working properly on Firebase end.
If you are receiving it, then it means you are doing something wrong after getting push msg(i.e. not displaying notification properly). Also check LogCat whether any exception is thrown or not.
Then post your replay.
Use the below code in FirebaseMessagingService.
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = “Your channel name, It will be visible in app setting”;
String description =“Description for your channel”;
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(SOME_CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat
.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(messageTitle)
.setContentText(messageBody);
Intent resultIntent = new Intent(this, MainAdsActivity.class);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT
);
int id = (int) System.currentTimeMillis();
builder.setContentIntent(pendingIntent);
startForeground(id,builder.build());
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(id, builder.build());
}
}
Notifications are working for Oreo 8.0(Api 26) and below perfectly fine but they are not working with Oreo 8.1.0.
below is the stack trace of an error
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x40 color=0x00000000 actions=2 vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1768)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I am creating Notification channel for Oreo still it's not working for Oreo 8.1.0. I also refer other stack overflow link but not getting any clue why this error occuring in my case.
UpdateAlarmActivity.java
public class UpcomingAlarmReceiver extends BroadcastReceiver {
public static final String TAG = "UpcomingAlarmReceiver";
public static final String ACTION_DISMISS_NOW = "com.funswitch.funrooster.action.DISMISS_NOW";
public static final String ACTION_CANCEL_NOTIFICATION = "com.funswitch.funrooster.action.CANCEL_NOTIFICATION";
public static final String ACTION_SHOW_SNOOZING = "com.funswitch.funrooster.action.SHOW_SNOOZING";
public static final String EXTRA_ALARM = "com.funswitch.funrooster.extra.ALARM";
public static final String CHANNEL_NAME = "CHANNEL_NOTIFICATION";
String NOTIFICATION_CHANNEL_ID = "io.funswitch.funrooster.Channel";
#Override
public void onReceive(final Context context, final Intent intent) {
final byte[] alarmBytes = intent.getByteArrayExtra(EXTRA_ALARM);
// Un-marshall the bytes into a parcel and create our Alarm with it.
final Alarm alarm = ParcelableUtil.unmarshall(alarmBytes, Alarm.CREATOR);
if (alarm == null) {
throw new IllegalStateException("No alarm received");
}
final long id = alarm.getId();
final NotificationManager nm = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
final boolean actionShowSnoozing = ACTION_SHOW_SNOOZING.equals(intent.getAction());
if (intent.getAction() == null || actionShowSnoozing) {
// Prepare notification
// http://stackoverflow.com/a/15803726/5055032
// Notifications aren't updated on the UI thread, so we could have
// done this in the background. However, no lengthy operations are
// done here, so doing so is a premature optimization.
String title;
String text;
if (actionShowSnoozing) {
if (!alarm.isSnoozed()) {
throw new IllegalStateException("Can't show snoozing notif. if alarm not snoozed!");
}
title = alarm.getLabel().isEmpty() ? context.getString(R.string.alarm) : alarm.getLabel();
text = context.getString(R.string.title_snoozing_until,
formatTime(context, alarm.snoozingUntil()));
} else {
// No intent action required for default behavior
title = context.getString(R.string.upcoming_alarm);
text = formatTime(context, alarm.ringsAt());
}
Intent dismissIntent = new Intent(context, UpcomingAlarmReceiver.class)
.setAction(ACTION_DISMISS_NOW)
.putExtra(EXTRA_ALARM, ParcelableUtil.marshall(alarm));
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
PendingIntent piDismiss = PendingIntent.getBroadcast(context, (int) id,
dismissIntent, PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder
.setSmallIcon(R.drawable.ic_alarm_24dp)
.setContentTitle(title)
.setContentText(text)
.addAction(R.drawable.ic_dismiss_alarm_24dp,
context.getString(R.string.dismiss_now), piDismiss);
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, CHANNEL_NAME, importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setSound(null, null);
notificationChannel.setShowBadge(false);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
assert nm != null;
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
nm.createNotificationChannel(notificationChannel);
}
Objects.requireNonNull(nm).notify(TAG, (int) id, mBuilder.build());
} else if (ACTION_CANCEL_NOTIFICATION.equals(intent.getAction())) {
Objects.requireNonNull(nm).cancel(TAG, (int) id);
} else if (ACTION_DISMISS_NOW.equals(intent.getAction())) {
new AlarmController(context, null).cancelAlarm(alarm, false, true);
}
}
}
Above is my Java class where I am implementing the code for Notifications. Please help me out or give me some suggestions how can I resolve this error.
In api level 27 google changed the notification methods now in api 27 or upper level you need to create notification channel to send notification.
Channel is categories all types of notifications learn more about notification channel
check this for notification channel
**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.
String 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);
}**
Change your NotificationCompat.Builder constructor:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
adding the channel id:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
I want to send push notifications to user whenever a node gets updated to the FCM realtime DB. my FCM function triggers a notification . I can see this in the FCM logs. But I am not able to see the notification getting dicsplayed in my client app. Can some one help me?
My logs are below:
In the client side I have the below code to receive notification:
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String channelId = "1";
String channel2 = "2";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId,
"Channel 1",NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setDescription("This is BNT");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel);
NotificationChannel notificationChannel2 = new NotificationChannel(channel2,
"Channel 2",NotificationManager.IMPORTANCE_MIN);
notificationChannel.setDescription("This is bTV");
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setShowBadge(true);
notificationManager.createNotificationChannel(notificationChannel2);
}
// Get Firebase database reference
this.mDatabase = FirebaseDatabase.getInstance().getReference().child("masterSheet");
//FirebaseMessaging.getInstance().subscribeToTopic("pushNotifications");
//FirebaseMessaging.getInstance().subscribeToTopic("pushNotifications");
// Init user list
ListView list = (ListView) this.findViewById(R.id.dataList);
this.listAdapter = new DataListAdapter(this, R.layout.list_view_cell);
list.setAdapter(listAdapter);
}
MyFirebaseMessagingService.java
public void onMessageReceived(RemoteMessage remoteMessage) {
Intent notificationIntent = new Intent(this, MainActivity.class);
if(MainActivity.isAppRunning){
//Some action
}else{
//Show notification as usual
}
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(this,
0 /* Request code */, notificationIntent,
PendingIntent.FLAG_ONE_SHOT);
//You should use an actual ID instead
int notificationId = new Random().nextInt(60000);
Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("image-url"));
Intent likeIntent = new Intent(this,LikeService.class);
likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
likeIntent.putExtra(IMAGE_URL_EXTRA,remoteMessage.getData().get("image-url"));
PendingIntent likePendingIntent = PendingIntent.getService(this,
notificationId+1,likeIntent,PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
setupChannels();
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setLargeIcon(bitmap)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getData().get("title"))
.setStyle(new NotificationCompat.BigPictureStyle()
.setSummaryText(remoteMessage.getData().get("message"))
.bigPicture(bitmap))/*Notification with Image*/
.setContentText(remoteMessage.getData().get("message"))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.addAction(R.drawable.ic_favorite_true,
getString(R.string.notification_add_to_cart_button),likePendingIntent)
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId, notificationBuilder.build());
}
Node.js
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.pushNotification = functions.database.ref('/masterSheet/{pushId}').onWrite( event => {
console.log('Push notification event triggered');
const payload = {
notification: {
title: 'App Name',
body: "New message",
sound: "default"
},
data: {
title: "New Title",
message:"New message"
}
};
const options = {
priority: "high",
timeToLive: 60 * 60 * 24 //24 hours
};
return admin.messaging().sendToTopic("notifications", payload, options);
});
It doesn't look like you're subscriping to the topic "notification":
FirebaseMessaging.getInstance().subscribeToTopic("notifications");