FCM Push Notifications Stop Sounding In Android Device - android

Since I got to have push notifications working as required when app was in both background and foreground, I have executed 30-40 notifications while testing (in 2 days), all of them sounding properly when arrived to android device (my custom notification channel also appeared in device settings as expected).
Suddenly, notifications continue arriving but without the sound (and custom notification channel does not appear in settings as before did). Since this, it is impossible for me to have sound back on notifications (neither background nor foreground).
Have not changed any involved code. I think sound has stopped because the notification channel is not being created for some reason. Have anyone experienced this or can help me?
Key code for case 'App in background':
1. Manifest.
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="my_fcm_default_channel" />
2. Launching activity - onCreate():
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create channel to show notifications.
val channelName = "Custom notification channel"
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationManager = getSystemService(NotificationManager::class.java)
val channel = NotificationChannel("my_fcm_default_channel",
channelName,
NotificationManager.IMPORTANCE_HIGH)
channel.setSound(defaultSoundUri, AudioAttributes.Builder().build()) // Not working
channel.enableLights(true)
channel.lightColor = Color.WHITE
channel.enableVibration(true)
channel.vibrationPattern = longArrayOf(100, 200, 100, 200, 100, 200, 100)
notificationManager.createNotificationChannel(channel)
}
3. Cloud function node.js snippet code:
// Notification details.
const payload = {
notification: {
title: 'Some title',
body: 'Some message',
sound: 'default',
click_action: "OPEN_ACTIVITY_3"
},
data: {
name: 'notification_3'
}
};
UPDATE:
Key code for case 'App in foreground':
1. MyFirebaseMessagingService - onMessageReceived():
val name = remoteMessage.data["name"] ?: ""
var intent: Intent? = null
when (name) {
"notification_1" -> {
intent = Intent(this, Activity1::class.java)
}
"notification_2" -> {
intent = Intent(this, Activity2::class.java)
}
"notification_3" -> {
val clickAction = remoteMessage.notification?.clickAction
clickAction?.let {
intent = Intent(clickAction)
intent?.putExtra("name", name)
}
}
"notification_4" -> {
intent = Intent(this, Activity4::class.java)
}
}
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT)
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val notificationBuilder = NotificationCompat.Builder(this, "my_fcm_default_channel")
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark) // Dummy icon
.setContentTitle(remoteMessage.notification?.title ?: "")
.setContentText(remoteMessage.notification?.body ?: "")
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setVibrate(longArrayOf(100, 200, 100, 200, 100, 200, 100))
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL) // this line sets the default vibration and sound for notification
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel("my_fcm_default_channel",
"Custom notification channel",
NotificationManager.IMPORTANCE_HIGH)
channel.setSound(defaultSoundUri, AudioAttributes.Builder().build()) // Not working
channel.enableLights(true)
channel.lightColor = Color.WHITE
channel.enableVibration(true)
channel.vibrationPattern = longArrayOf(100, 200, 100, 200, 100, 200, 100)
notificationManager.createNotificationChannel(channel)
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())

Related

How to check floating notifications permission on MIUI

this permission screen At the moment, when notifications are shown on MIUI, notifications do not pop up . When viewing the settings, I found that on some XIOMI devices, this setting is disabled. Is there any way to enable it by default, or check if it is enabled
NotificationCompat.Builder(context, SOME_CHANNEL_ID).apply {
setupNotificationData(newRide)
setTimeoutAfter(1000* someTimeout.toLong())
setContentTitle(context.getString(R.string.offer_description))
setContentText(context.getString(R.string.offer_new_event))
setCustomHeadsUpContentView(createHeadsUpContentView())
setSmallIcon(R.drawable.logo_notification)
setContentIntent(pendingIntent)
setSound(getSoundUri())
setStyle(NotificationCompat.DecoratedCustomViewStyle())
priority = NotificationCompat.PRIORITY_MAX
setDeleteIntent(getDeleteAction())
setVibrate(longArrayOf(500, 500, 500, 500, 500))
setOngoing(true)
}
private fun getNotificationChannelForOffer() =
NotificationChannel(
SOME_CHANNEL_ID, OSOME_CHANNEL_ID,
NotificationManager.IMPORTANCE_HIGH
).apply {
setSound(
getOfferSoundUri(),
audioAttributes
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
canBubble()
}
shouldVibrate()
setBypassDnd(true)
enableVibration(true)
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
vibrationPattern = longArrayOf(500, 500, 500, 500, 500)
}
I've tried to use
setCustomHeadsUpContentView(createHeadsUpContentView())
but notifications do not overlay without this permission .
Add this
permission to Manifest

Custom notification sound does not work on Android 26+

I am trying to get custom notification sounds working for my flutter based Android app that uses Android version 26 with notification channels.
I have configured both the node.js server code, and the android app to use a notification channel with a custom sound.
My android code that initialises the channel looks as follows...
class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(#NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val sound: Uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.packageName + "/" + R.raw.app_alert)
val mChannel = NotificationChannel("app_alerts", "app_alerts_2", NotificationManager.IMPORTANCE_HIGH)
val audioAttributes: AudioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
mChannel.setSound(sound , audioAttributes)
mChannel.description = "Important app Notifications"
val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(mChannel)
}
}
}
And my node.js code is as follows...
const { messaging } = require('firebase-admin');
var admin = require('firebase-admin');
console.log(process.cwd());
var serviceAccount = require("path to my credentials");
const topic = 'all';
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
const payload = {
notification: {
title: "Test Notification",
body: "This is just a test",
},
android: {
notification: {
channelId: "app_alerts",
sound: 'app_alert'
},
},
apns: {
payload: {
aps: {
sound: 'app_alert.wav'
},
},
},
topic: 'all'
};
admin.messaging().send(payload).then(response => {
console.log("Successfully sent message:", response);
})
I have gone into my Android settings and confirmed that the notification channel has been created as expected...yet the custom sound does not play.

firebase cloud messaging notification Not Working

i'm new to firebase cloud function and fcm, My situation is Whenever a new article is published in the database, I need to show the notification to my app user.
firebase cloud function worked perfectly but notification not received by device android.
cloud function
var functions = require('firebase-functions');
var admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/Vacancy/{articleId}')
.onWrite((event: { after: any; }) => {
console.log("Successfully sent message:2");
var eventSnapshot = event.after;
var str1 = "Author is ";
var str = str1.concat(eventSnapshot.child("author").val());
console.log(str);
var topic = "android";
var payload = {
data: {
title: eventSnapshot.child("title").val(),
author: eventSnapshot.child("author").val()
}
};
return admin.messaging().sendToTopic(topic, payload)
.then(function (response: any) {
console.log("Successfully sent message:", response);
})
.catch(function (error: any) {
console.log("Error sending message:", error);
});
});
manifess code
<service
android:name=".ServiceNotification.NotificationMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
NotificationMessagingService class code
public class NotificationMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
FirebaseMessaging.getInstance().subscribeToTopic("android");
if (remoteMessage.getData().size() > 0) {
showNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("author"));
}
if (remoteMessage.getNotification() != null) {
}
}
private void showNotification(String title, String author) {
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Article: " + title)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("By " + author)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
cloud function log
1:33:46.257 AM
sendNotification
Successfully sent message:2
1:33:46.263 AM
sendNotification
Author is Raja
1:33:47.022 AM
sendNotification
Successfully sent message: { messageId: 5711725841493019000 }
1:33:47.040 AM
sendNotification
Function execution took 1005 ms, finished with status: 'ok'

How to send other data than title and body in Firebase Messaging Service? (Node.js, Android)

I am working on an Android app and by using Node.js based function, I'm sending notification to Android and in Android onMessageReceived() function is used to receive data to show notifications. Now the problem, I'm facing is that I want to send some String type data in parallel to Title and Body. What changes should I make?
Here is my Node.js code
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.firestore.document("Users/{user_id}/Notifications/{notification_id}").onWrite((change,context)=> {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log("User ID:"+user_id+" | Notification ID:"+notification_id);
return admin.firestore().collection("Users").doc(user_id).collection("Notifications").doc(notification_id).get().then(queryResult =>{
const from_user_id = queryResult.data().from;
const from_message = queryResult.data().Message;
const from_data = admin.firestore().collection("Users").doc(from_user_id).get();
const to_data = admin.firestore().collection("Users").doc(user_id).get();
return Promise.all([from_data,to_data]).then(result =>{
const from_name = result[0].data().Name;
const to_name = result[1].data().Name;
const token_id = result[1].data().Token_ID;
const payload = {
notification: {
title: "Hey! "+from_name+" here",
body: "Dear "+to_name+", "+from_message+", Will you help me?",
icon: "default"
}
};
return admin.messaging().sendToDevice(token_id,payload).then(result =>{
return console.log("Notification Sent.");
});
});
});
});
And Here is my android code:
public class FirebaseMsgService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String messageTitle = remoteMessage.getNotification().getTitle();
String messageBody = remoteMessage.getNotification().getBody();
Uri sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.enough);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
.setSmallIcon(R.drawable.logo)
.setContentTitle(messageTitle)
.setSound(sound)
.setContentText(messageBody)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(messageBody))
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
int mNotificationID = (int) System.currentTimeMillis();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.notify(mNotificationID,mBuilder.build());
}
}
While I know squad about nodejs (or js in general) I got this working yesterday by passing a data object in the payload.
So, the json request that google makes (I'm using GCM still, but I'm sure FCM would be the same, or very similar payload) looks like this:
{
"to": "<GCM/FCM token>",
"priority": "normal",
"android_channel_id": -99,
"data": {
"title": "Some title",
"body": "Some body",
"more_data_one": "Some more data",
"more_data_two": "Some more data, again!"
}
}
Somehow, however, if I send both data and notification in the payload, the GCMServiceListener never gets called, and the app just displays whatever is in the notification portion of the payload.
By adding the data section (and therefore making the notification a "silent" notification), you are then on charge of intercepting the message, and displaying it with the Notification builder.

PushSharp Google Cloud Messaging Heads-up notification

I'm developing an application for Android and iOS and I'm using PushSharp (on server-side) to send push notifications to both platform. In particular I'm using (for Android) the Firebase platform (FCM).
Following this guide I was able to send push notification to an Android device setting icon and sound too but I think there is a problem.
When the notification arrives it doesn't being shown as Heads-up notification but only as status bar notification.
To be clear, I would:
but i see only the application icon that appears on the status bar.
How can I tell to FCM to show my notification as Head-Up notification similary to what I obtain with the following code?
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_media_play)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(Notification.PRIORITY_HIGH);
I have fixed it by installing following version of react-native-push-notification
npm install zo0r/react-native-push-notification.git
in your index.android.js
function init(){
PushNotification.configure({
onNotification:async (notification)=>{
if(!notification.userInteraction && !notification.foreground){
PushNotification.localNotification({
message: "you message"
});
}
,
requestPermissions:true,
senderID:"31************",
popInitialNotification:false
})
}
you must create a channel in your MainActivity.java.
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.os.Build;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ NotificationChannel notificationChannel = new
+ NotificationChannel("500", "MainChannel",
+ NotificationManager.IMPORTANCE_HIGH);
+ notificationChannel.setShowBadge(true);
+ notificationChannel.setDescription("Test Notifications");
+ notificationChannel.enableVibration(true);
+ notificationChannel.enableLights(true);
+ notificationChannel.setVibrationPattern(new long[]{400, 200, 400});
+ NotificationManager manager = getSystemService(NotificationManager.class);
+ manager.createNotificationChannel(notificationChannel);
+ }
Add the channelId to your server: an example with node.js
await admin
.messaging()
.send({
android: {
priority: 'high',
notification: {
sound: 'default',
title: 'your title',
body: 'your message',
imageUrl: 'img-uri',
priority: 'high', // this is importnat
channelId: '500', // the channelId we created in MainActivity.java
},
},
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
'apns-push-type': 'background',
'apns-priority': '5',
'apns-topic': '', // your app bundle identifier
},
},
topic: //topic or token,
data: {//send a custom data here to your client},
notification: {
title: 'your title',
body:'your message',
imageUrl: 'img-url',
},

Categories

Resources