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
}
Related
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.
Following instructions on https://pub.dev/packages/firebase_messaging, I have implemented FCM. Although I have set click_action: FLUTTER_NOTIFICATION_CLICK, when I click on the notification tray item, it does not open the app. The data received by the flutter app from the cloud function is as follows. How do I at least open the app upon notification click?
onMessage: {notification: {title: pi, body: text message.},
data: {USER_NAME: pi, click_action: FLUTTER_NOTIFICATION_CLICK, }}
Cloud function payload
const payload = {
notification: {
title: sender,
body: content,
clickAction: 'ChatActivity',
},
data: {
"click_action": 'FLUTTER_NOTIFICATION_CLICK',
"USER_NAME": sender,
}
};
I have also created the notification channels and AndroidManifest has been correctly configured.
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.app_name);
String description = getString(R.string.notification_channel_description);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(getString(R.string.default_notification_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);
}
}
I have put the click action to the notification json and it works for me.
notification: {
title: sender,
body: content,
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
The click action is only required for onResume and onLaunch callbacks, so be sure to implement it as stated in the pub.dev doc:
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
_showItemDialog(message);
},
onBackgroundMessage: myBackgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
_navigateToItemDetail(message);
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
_navigateToItemDetail(message);
},
);
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.
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',
},