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.
Related
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())
I am sending following payload for notification:
var message = {
data: {
user: sendData.from,
body: sendData.message,
sentto: sendData.to,
gcm_username: sendData.from
},
android: {
priority: 'high',
notification: {
title: 'Yeni mesaj aldınız',
body: sendData.from + ' size bir mesaj gönderdi',
tag: sendData.from,
sound: 'default',
channelId: 'messages'
}
},
token: deviceToken
};
But sometimes i have to cancel certain notification when user opens the app from the app icon.
I tried following code:
#RequiresApi(api = Build.VERSION_CODES.M)
public Notification deleteNotificationByTag(String senderCode) {
NotificationManager notificationManager = (NotificationManager) mApplication.getSystemService(Context.NOTIFICATION_SERVICE);
StatusBarNotification[] barNotifications = notificationManager.getActiveNotifications();
for(StatusBarNotification notification: barNotifications) {
Log.d(TAG, "getActiveNotification: " + notification.getTag());
if (notification.getTag() != null && notification.getTag().equals(senderCode)) {
notificationManager.cancel(notification.getId());
}
}
return null;
}
But notification.getId() method is always returning 0 value. So cancel is not working. How can i fix it?
You can use the tag to cancel the notification as follows:
public void cancel (String tag, int id);
So even if the id is 0, it should work if the tag is unique.
One option is to send data messages and create notifications with id manually and You can cancel messages as per your requirements.
My notification channel:
CharSequence name = mApplication.getString(R.string.notification_messages_channel);
String description = mApplication.getString(R.string.notification_messages_channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_MESSAGES, name, importance);
channel.setDescription(description);
channel.enableVibration(true);
channel.enableLights(true);
channel.setVibrationPattern(new long[]{500,100,500});
NotificationManager notificationManager = mApplication.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
And this is my payload:
var message = {
data: {
user: "asdasd",
body: "adsadasd",
sentto: "asdasd",
gcm_username: "asdda"
},
android: {
priority: 'high',
notification: {
title: 'Yeni mesaj aldınız',
body: 'size bir mesaj gönderdi',
tag: "asd223",
sound: 'default'
}
},
token: deviceToken
};
When a notification arrives to the phone, it plays the notification sound but not vibrating. Where is the problem?
Channel looks set up correctly.
Try adding this directly to NotificationCompat.Builder()
val mBuilder = NotificationCompat.Builder(ctx, "ID")
.setVibrate(arrayOf(100L, 200L).toLongArray())
And make sure, you have your phone set to:
Ok, I found the answer. I added channel information to payload and problem resolved.
New payload:
var message = {
data: {
user: "asdasd",
body: "adsadasd",
sentto: "asdasd",
gcm_username: "asdda"
},
android: {
priority: 'high',
notification: {
title: 'Yeni mesaj aldınız',
body: 'size bir mesaj gönderdi',
tag: "asd223",
sound: 'default',
channel: 'messages'
}
},
token: deviceToken
}
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.
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',
},