receiving push notification after realtime database value changes - android

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

Related

Notifications not pushed with android 10

I am working on Android App with Firebase notification service FCM. and I recives notification successfully. but after I recive it is not showin in Android 10 (it work in 9 and 8 and smaller versions).
This is my showing notification code, I dont know what I missed. I check about if there is any changed with 10 but I dont see that...
My method:
private void sendNotification(String messageBody, String title) {
Intent intent;
if(type.equals("order_pending") || type.equals("order_declined")){
intent = new Intent(this, myOrdersActivity.class);
}else { intent = new Intent(this, MainActivity.class); }
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.logo)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int f =0;
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
// EventBus.getDefault().post(eventObject);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isActive", true)) {
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
Intent dialogIntent = new Intent(this, MainActivity.class)
.putExtra("ac", "1");
// sendBroadcast(dialogIntent);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
f =1;
// startActivity(dialogIntent);
}
if(f==0) {
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
Any help please?
and Thanks
The ship has sailed, but:
worked skeleton (Java):
void sendNotif(int icon, String sText) {
String channel_id = "1002";
String sTitle = getString(R.string.app_name);
Intent notificationIntent = new Intent(this, activityMain.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Android 8.0 (API level 26) and higher
// https://developer.android.com/training/notify-user/build-notification
CharSequence name = "statusbar";
String description = getString(R.string.app_name);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channel_id, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channel_id)
.setSmallIcon(icon)
/*.setContentTitle(sTitle)*/
.setContentText(sText)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
// Set the intent that will fire when the user taps the notification
.setContentIntent(contentIntent)
.setAutoCancel(false);
// notificationId is a unique int for each notification that you must define
// and remember for delete notification
notificationManager.notify(0, builder.build());
}
else {
// Android 7.1 (API level 25) and lower
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(getApplicationContext())
.setTicker(sTitle)
.setContentTitle(sTitle)
.setContentText(sText)
.setSmallIcon(icon)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.build();
notification.flags |= Notification.FLAG_NO_CLEAR;
// for BIG icon:
//notification.contentView.setImageViewResource(android.R.id.icon, R.drawable.icon);
mNotificationManager.notify(0, notification);
}
}

Xamarin forms: Push notification is not working on Android 7.1.2

Push notification is not working on Android device having a version number 7.1.2, but working fine on version 9. Following is my code for showing the notification.
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Android.App.Notification.Builder(this, Utils.CHANNEL_ID)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = NotificationManager.FromContext(this);
notificationManager.Notify(0, notificationBuilder.Build());
}
else
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Android.App.Notification.Builder(this, Utils.CHANNEL_ID)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.SetChannelId(Utils.CHANNEL_ID);
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
return;
}
var channel = new NotificationChannel(Utils.CHANNEL_ID, "FCM Notifications", NotificationImportance.High)
{
Description = "Firebase Cloud Messages appear in this channel"
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
notificationManager.Notify(0, notificationBuilder.Build());
}
Can anyone please suggest a solution for this?
I following this sample
https://learn.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm
I post my SendNotification method from my production project.
Following my working code and change your method.
void SendNotification (string messageBody, string title)
{
var intent = new Intent (this, typeof (SplashActivity));
intent.AddFlags (ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity (this, 0, intent, PendingIntentFlags.OneShot);
//if i want more than one notification ,different unique value in every call
Random u = new Random ();
if (Build.VERSION.SdkInt >= BuildVersionCodes.O) {
string channelName = Resources.GetString (Resource.String.channel_name);
NotificationCompat.Builder notificationBuilder;
notificationBuilder = new NotificationCompat.Builder (this, channelName)
.SetContentTitle (title)
.SetSmallIcon (Resource.Drawable.ic_stat_g)
.SetContentText (messageBody)
.SetAutoCancel (true)
.SetContentIntent (pendingIntent);
var notificationManager = GetSystemService (Context.NotificationService) as NotificationManager;
NotificationChannel channel = new NotificationChannel (channelName, "notification channel", NotificationImportance.Default);
notificationManager.CreateNotificationChannel (channel);
notificationManager.Notify (u.Next(), notificationBuilder.Build ());
}
else
{
NotificationCompat.Builder notificationBuilder;
notificationBuilder = new NotificationCompat.Builder (this)
.SetContentTitle (title)
.SetSmallIcon (Resource.Drawable.ic_stat_g)
.SetContentText (messageBody)
.SetAutoCancel (true)
.SetContentIntent (pendingIntent);
var notificationManager = GetSystemService (Context.NotificationService) as NotificationManager;
notificationManager.Notify (u.Next(), notificationBuilder.Build ());
}
}
First of all don't use Android.App.Notification.Builder is deprecated. The NotificationCompat.Builder is the new one.
Maybe this one is your new code
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
var notificationBuilder = new NotificationCompat.Builder(this)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = GetSystemService (Context.NotificationService) as NotificationManager;
notificationManager.Notify(0, notificationBuilder.Build());
}
else
{
var notificationBuilder = new NotificationCompat.Builder(this, Utils.CHANNEL_ID)
.SetContentTitle(Header)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentText(body)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = GetSystemService (Context.NotificationService) as NotificationManager;
NotificationChannel channel = new NotificationChannel (Utils.CHANNEL_ID, "FCM Notifications", NotificationImportance.Default);
notificationManager.CreateNotificationChannel (channel);
notificationManager.Notify (0, notificationBuilder.Build ());
}
Firebase notifications behave differently depending on the foreground/background state of the receiving app.
Notification messages delivered when your app is in the background. In this case, the notification is delivered to the device’s system tray. A user tap on a notification opens the app launcher by default.
Messages with both notification and data payload, when received in the background. In this case, the notification is delivered to the device’s system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.
For more information, visit https://firebase.google.com/docs/cloud-messaging/android/receive
I also have this sample code for you to try:
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
NotificationChannel notificationChannel = new NotificationChannel("my_channel", "This is my Notification Channel", NotificationImportance.High);
builder.SetChannelId("my_channel");
notificationManager.CreateNotificationChannel(notificationChannel);
}
var notification = builder.SetContentIntent(PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.Immutable))
.SetSmallIcon(Resource.Drawable.icon)
.SetContentTitle(Header)
.SetContentText(body)
//Set vibrate
.SetVibrate(new long[] { 200, 200, 200, 200 })
//LED
.SetLights(Android.Graphics.Color.Blue, 1000, 1000)
//Auto cancel will remove the notification once the user touches it
.SetAutoCancel(true).Build();
notificationManager.Notify(0, notification);

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 click_action should redirect to open browser

I have a problem with fcm click operation, after receiving a notification, when I click on it, it should open browser which goes to "www.google.co.in", but when I click on notification it opens the default MainActivity.
Here is my onMessageReceived() :
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "Message Data Payload:" + remoteMessage.getData());
Log.d(TAG, "Message notification body: " + remoteMessage.getNotification().getBody());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("www.google.co.in"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("FCM Message")
.setContentText("FCM MessageBody")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}
Does anyone know what is the exact implementation or anything wrong in this code ?
Thanks in advance.
For a better understanding of this topic, I suggest that you read this article
firebase cloud messaging
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.i(TAG, "Message Data Payload:" + remoteMessage.getData());
Log.i(TAG, "Message notification body: " + remoteMessage.getNotification().getBody());
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
switch (remoteMessage.getNotification().getBody()) {
case "openUrlGoogle":
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("www.google.co.in"));
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
break;
case "openUrlOtherSite":
break;
default:
Log.v("TAG", "error");
break;
}
}
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle("FCM Message")
.setContentText("FCM MessageBody")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0, notificationBuilder.build());
}

Firebase notification works in background but doesn't appear in Foreground in Oreo

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

Categories

Resources