how to custom multi different sound of push notification in flutter - android

I want to set sound when push notification, but problem is app when update or install then sound is work ok and when i push local notification and change file of sound but sound notification not change follow. it still takes the old sound.
var platformChannelSpecificsAndroid = new AndroidNotificationDetails(
"fcm_default_channel",
"fcm_default_channel",
channelDescription: 'Channel to Received Push Notification',
playSound: true,
styleInformation: DefaultStyleInformation(true, true),
importance: Importance.max,
priority: Priority.high,
icon: 'launch_background',
sound: RawResourceAndroidNotificationSound(pushSound ?? ""),
);
var platformChannelSpecificsIos = new IOSNotificationDetails(
// presentSound: true
sound: pushSound ?? "");
var platformChannelSpecifics = new NotificationDetails(
android: platformChannelSpecificsAndroid,
iOS: platformChannelSpecificsIos);
new Future.delayed(Duration.zero, () {
flutterLocalNotificationsPlugin.show(
hashCode,
pushTitle,
pushText,
platformChannelSpecifics,
payload: payloadT,
);
});

I saw the same problem. I found this answer Play multiple different notification sounds from app . But it is only helpful for Kotlin

Related

Flutter PUSH Notification icon not showing

I tried to add flutter app icon by using a package flutter_launcher_icon app icon is correct but icons shows in push notification show as a white box
Notification Icon Shows as a white box
Resource File
I added icons by using a package [flutter_launcher_icons]
Expected Output
same error have happened to me so i have used icon as xml file in android
we have to add that file name here
void showNotification(int orderCount) async {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid = AndroidInitializationSettings('fav_icon');
var initializeSettings = InitializationSettings(android: initializationSettingsAndroid);
var res = await flutterLocalNotificationsPlugin.initialize(initializeSettings) ?? false;
Log.d("Notification manager initialized $res");
if (res) {
flutterLocalNotificationsPlugin.show(
1,
"Order",
"You have new notifications",
NotificationDetails(
android: AndroidNotificationDetails('NOTIFICATION', 'New order notifications',
channelDescription: 'Shows notifications when new orders are available',
importance: Importance.max,
priority: Priority.high,
playSound: true,
category: AndroidNotificationCategory.event,
color: MyColor.kSecondary)));
}
}

Any way to make flutter local notification persist a sound being played in android unless the notification is tapped?

I looked up in the net, it was suggested to set the additionalFlags option of AndroidNotificationDetails to have a value of 4.
This is what I did
AndroidNotificationDetails(
'notif',
'notif',
'Notification',
icon: '#mipmap/launcher',
priority: Priority.high,
sound: RawResourceAndroidNotificationSound('notif'),
largeIcon: DrawableResourceAndroidBitmap('#mipmap/launcher'),
additionalFlags: Int32List.fromList(<int>[4]),
importance: Importance.max,
playSound: true,
);
But the moment I swipe down to see the list of notifications, the sound stops playing.
I want the sound to keep playing, unless and until I tap on that particular notification (and not merely swipe down to see the list of notifications)?
You can persist the sound (or in this example an alarm) by using a insistentFlag and the androidAllowWhileIdle flag.
The below example uses Flutter local Notifications v.12
static Future<void> showFullScreenNotification(
Alarm alarm, tz.TZDateTime date) async {
const int insistentFlag = 4;
final Int64List vibrationPattern = Int64List(4);
vibrationPattern[0] = 0;
vibrationPattern[1] = 4000;
vibrationPattern[2] = 4000;
vibrationPattern[3] = 4000;
AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
alarm.id.toString(),
'scheduled_alarm_channel',
channelDescription: 'scheduled_alarm',
priority: Priority.high,
importance: Importance.high,
additionalFlags: Int32List.fromList(<int>[insistentFlag]),
playSound: true,
audioAttributesUsage: AudioAttributesUsage.alarm,
vibrationPattern: vibrationPattern,
);
NotificationDetails details =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.zonedSchedule(
...
date,
androidAllowWhileIdle: true,
...
);
}

Local notification flutter :Error "Unhandled Exception: NoSuchMethodError: The method 'show' was called on null."

How i can create notification without click button?
how to initialize when opening the application a notification appears ?
String groupKey = 'com.android.example.WORK_EMAIL';
String groupChannelId = 'grouped channel id';
String groupChannelName = 'grouped channel name';
String groupChannelDescription = 'grouped channel description';
AndroidNotificationDetails firstNotificationAndroidSpecifics =
AndroidNotificationDetails(
groupChannelId, groupChannelName,
groupChannelDescription,
importance: Importance.Max,
priority: Priority.High,
groupKey: groupKey,
style: AndroidNotificationStyle.BigText,
styleInformation: BigTextStyleInformation(''),
);
final AndroidNotificationDetails android = AndroidNotificationDetails(
'ch_ID',
'Ch_Name',
'ch_Description',
priority: Priority.High,
importance: Importance.Max,
// add this line in your code
styleInformation: BigTextStyleInformation(''),
);
NotificationDetails firstNotificationPlatformSpecifics =
NotificationDetails(
firstNotificationAndroidSpecifics, null,);
flutterLocalNotificationsPlugin.show(
1, 'Confirmation ',
'Hello' , firstNotificationPlatformSpecifics);
how to launch a notification in flutter?

flutterLocalNotificationsPlugin.show

My flutter app, show this notification when FCM is triggered.
await flutterLocalNotificationsPlugin.show(
0, "my app. Alert", "Alert text from App", platform
);
Is there any way to show a image in the notification bar and not only the text?
Something like:
await flutterLocalNotificationsPlugin.show(
0, "my app. Alert", "Alert text from App","url: myimage.com/sample.jpg", platform
);
Thanks
If you are using the flutter_local_notifications plugin, then you can do something like this for android:
Future<void> _showBigPictureNotification() async {
var largeIconPath = await _downloadAndSaveImage(
'http://via.placeholder.com/48x48', 'largeIcon');
var bigPicturePath = await _downloadAndSaveImage(
'http://via.placeholder.com/400x800', 'bigPicture');
var bigPictureStyleInformation = BigPictureStyleInformation(
bigPicturePath, BitmapSource.FilePath,
largeIcon: largeIconPath,
largeIconBitmapSource: BitmapSource.FilePath,
contentTitle: 'overridden <b>big</b> content title',
htmlFormatContentTitle: true,
summaryText: 'summary <i>text</i>',
htmlFormatSummaryText: true);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'big text channel id',
'big text channel name',
'big text channel description',
style: AndroidNotificationStyle.BigPicture,
styleInformation: bigPictureStyleInformation);
var platformChannelSpecifics =
NotificationDetails(androidPlatformChannelSpecifics, null);
await flutterLocalNotificationsPlugin.show(
0, 'big text title', 'silent body', platformChannelSpecifics);
}
For more such examples, please refer the official example provided by the plugin developer, here.

Custom sound for Android Push Notification not working (FCM)

I have push notifications working using FCM from a cloud function. This works for both iOS and Android and displays the appropriate icon and plays a custom sound on iOS.
All is working except the custom sound for Android, it simply plays the default sound.
I have created a folder and added my sound file to it as follows: android\app\src\main\res\raw\mp3_example.mp3
This mp3 is 27s long. I have also tried a .wav and .aiff.
I read that I may have to create a push notification channel for later versions of Android so it could be related to this. I tried creating a channel and using the channelID from the cloud function and it works but there is no sound just a vibration.
The test device is a Moto G6 running Android 8.
I am using:
FCM
Firebase Cloud Functions
Ionic 4
Capacitor
https://github.com/stewwan/capacitor-fcm
Cloud Function:
const notification: admin.messaging.Notification = {
title: title,
body: body
}
const message: admin.messaging.Message = {
notification,
topic: 'QMTBC',
android:{
notification:{
sound: 'mp3_example.mp3',
icon: 'push_logo',
color: '#000000'
}
},
apns:{
payload:{
aps: {
sound: 'gears-short.wav'
}
}
}
}
return admin.messaging().send(message)
app.component.ts
import { FCM } from 'capacitor-fcm';
const fcm = new FCM();
const { PushNotifications } = Plugins;
initializeApp() {
this.platform.ready().then(() => {
PushNotifications.register();
PushNotifications.addListener('registration', (token: PushNotificationToken) => {
console.log('token ' + token.value);
fcm
.subscribeTo({ topic: 'QMTBC' })
.then(r => console.log(`subscribed to topic`))
.catch(err => console.log(err));
});
PushNotifications.addListener('registrationError', (error: any) => {
console.log('error on register ' + JSON.stringify(error));
});
PushNotifications.addListener('pushNotificationReceived', (notification: PushNotification) => {
console.log('notification ' + JSON.stringify(notification));
this.pushNotificationService.notifications.push(notification);
});
PushNotifications.addListener('pushNotificationActionPerformed', (notification: PushNotificationActionPerformed) => {
console.log('notification ' + JSON.stringify(notification));
this.pushNotificationService.notifications.push(notification);
});
fcm.getToken()
.then(r => console.log(`Token ${r.token}`))
.catch(err => console.log(err));
});
}
UPDATE:
I tried creating a channel as follows.
If I use the channel I just get the default sound. If I specific no channel or one that does not exist I also get the default sound (default channel).
cloud function:
const message: admin.messaging.Message = {
notification,
topic: 'QMTBC',
android:{
notification:{
sound: 'punch.mp3',
icon: 'push_logo',
color: '#000000',
channelId: 'QMTBC'
}
}
app.component.ts
const channel: PushNotificationChannel = {
description: 'QMTBC',
id : 'QMTBC',
importance: 5,
name : 'QMTBC'
};
PushNotifications.createChannel(channel).then(channelResult => {
console.log(channelResult);
console.log('Channel created');
// PushNotifications.listChannels().then(channels => {
// console.log('Channels');
// console.log(channels);
// });
}, err => {
console.log('Error Creating channel');
console.log(err);
});
});
UPDATE 2:
I can see the channel I have created for the app on my device and it says the sound is default. I can manually change it to another inbuilt android sound and this works. But I still can't use my custom sound.
UPDATE 3:
The custom sound works on if the Android version is < 8. Only tested this on an emulator.
#MadMac I was facing the same problem these days, after read FCM documentations and the Capacitor Java code, I got it.
It's necessary to set the visibility to 1, place your file in res/raw folder.
PushNotifications.createChannel({
description: 'General Notifications',
id: 'fcm_default_channel',
importance: 5,
lights: true,
name: 'My notification channel',
sound: 'notifications.wav',
vibration: true,
visibility: 1
}).then(()=>{
console.log('push channel created: ');
}).catch(error =>{
console.error('push channel error: ', error);
});
I'm using this payload in my firestore function to send notifications
{
android: {
notification: {
defaultSound: true,
notificationCount: 1,
sound: 'notifications.wav',
channelId: 'fcm_default_channel'
},
ttl: 20000,
collapseKey
},
apns: {
payload: {
aps: {
badge: 1,
sound: 'default'
}
}
},
notification: {
title,
body: message,
},
token: token
};
This was such a good question that helped me find the answer. So I post my answer here. Try setting the sound of the notifications to notification channels themselves at the time when you create the channels. I suppose, based on your info, the old Android versions will play sound according to the sound field in the notification payload, but in the new versions you would have to set it directly to the notification channels themselves since that is where the control is now currently intended to be by Google. I had to uninstall and reinstall the app for this code change to work, because my channels were previously initialized and the channels won't update after the first initialization.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !notificationChannelsInitialized) {
val newMessagesChannel = NotificationChannel(NEW_MESSAGES_NOTIFICATION_CHANNEL_ID, "New Messages", NotificationManager.IMPORTANCE_HIGH)
val notificationSoundUri =
Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE.toString() + "://" + context.packageName + "/" + R.raw.ns) // ns.wav is my notification sound file in the res/raw folder in Android Studio
val notificationSoundUriAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
newMessagesChannel.setSound(notificationSoundUri, notificationSoundUriAttributes)
val notificationManager: NotificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannels(listOf( newMessagesChannel)) // and other channels
}
I was able to get it working for React Native using the react-native-push-notification library (here). The key to resolving is that you must create a channel within your app. (I had thought channels were created on the backend, but that's not right). After placing the mp3 file in the res/raw directory in the android folder of my app, I added the following code in React Native (copied from documentation in the above library), and it worked:
import PushNotification, {Importance} from 'react-native-push-notification';
...
PushNotification.createChannel(
{
channelId: "channel-id", // (required)
channelName: "My channel", // (required)
channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
playSound: true, // (optional) default: true
soundName: "mp3_example", // (optional) See `soundName` parameter of `localNotification` function
importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
vibrate: true, // (optional) default: true. Creates the default vibration pattern if true.
},
(created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
);

Categories

Resources