How do I use HTML code in Flutter notifications? - android

I started Flutter exactly today.
I want to use HTML code within Android notifications.
It seems that by setting the DefaultStyleInformation argument to true, HTML can be used, but I don't know how to write the actual code.
//This is the interface provided.
/// The default Android notification style.
class DefaultStyleInformation implements StyleInformation {
/// Constructs an instance of [DefaultStyleInformation].
const DefaultStyleInformation(
this.htmlFormatContent,
this.htmlFormatTitle,
);
/// Specifies if formatting should be applied to the content through HTML
/// markup.
final bool htmlFormatContent;
/// Specifies if formatting should be applied to the title through HTML
/// markup.
final bool htmlFormatTitle;
}
The following is the code I am writing.
I feel I need help with the "//here" part.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'dart:io';
Future<void> showBigTextNotification() async {
const styleInformation=DefaultStyleInformation(true,true);
const NotificationDetails notificationDetails =
NotificationDetails(
android: AndroidNotificationDetails(
'channel_id',
'Channel Name',
importance: Importance.max,
priority: Priority.high,
styleInformation: styleInformation
),
iOS: IOSNotificationDetails());
await flutterLocalNotificationsPlugin.show(
id,
Platform.isAndroid? '<b>'${title}'</b>': title, // here???
Platform.isAndroid? '<b>'${content}'</b>': content, // here???
payload: 'Destination Screen(Big Text Notification)');
}
thanks.

you problem is in the bigTextInformation style and some more thing are missing please use the below code which will now convert html text into regular text
Future<void> showBigTextNotification() async {
BigTextStyleInformation bigTextStyleInformation = BigTextStyleInformation(
body, htmlFormatBigText: true,
htmlFormatTitle:true ,
htmlFormatContent:true ,
contentTitle: 'overridden <b>big</b> content title',
htmlFormatContentTitle: true,
summaryText: 'summary <i>text</i>',
htmlFormatSummaryText: true
);
final androidChannelSpecifics = AndroidNotificationDetails(
'your channel id',
'your channel name',
importance: Importance.max,
styleInformation: bigTextStyleInformation,
priority: Priority.high,
ongoing: true,
autoCancel: true,
);
final iOSChannelSpecifics = IOSNotificationDetails();
NotificationDetails platformChannelSpecifics = NotificationDetails(android: androidChannelSpecifics, iOS: iOSChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
id,
Platform.isAndroid? '<b>'${title}'</b>': title, // here???
Platform.isAndroid? '<b>'${content}'</b>': content, // here???
type: platformChannelSpecifics,
payload: 'Destination Screen(Big Text Notification)');
}

Simply use BigTextStyleInformation to show html content in notifications
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
'',
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
importance: Importance.high,
styleInformation: BigTextStyleInformation(
'<b>Your</b> notification',
htmlFormatBigText: true,
),
),
),
payload: jsonEncode(message.data),
);

Related

Flutter : How to use color with html in FCM notification description text

This is test message. i want to show color in notification description body with html.
String message = "<html><body><font color=\"#000000\">Testing description message</font> </body></html>";
Flutter code for create local notification with html support.
BigTextStyleInformation bigTextStyleInformation =
BigTextStyleInformation(
message, htmlFormatBigText: true,
htmlFormatTitle:true ,
htmlFormatContent:true ,
//contentTitle: 'overridden <b>big</b> content title',
htmlFormatContentTitle: true,
//summaryText: 'summary <i>text</i>',
htmlFormatSummaryText: true,
);
androidDetails = AndroidNotificationDetails(
'pm_channel_id', 'pm_channel_name',
channelDescription: 'pm_channel_description',
importance: Importance.max,
priority: Priority.high,
ticker: 'ticker',
styleInformation: bigTextStyleInformation,
ongoing: true,
autoCancel: true,
color: MyColors.yellow
);
var iOSDetails = IOSNotificationDetails();
var platform =
NotificationDetails(android: androidDetails, iOS: iOSDetails);
await PushNotification.notificationsPlugin
.show(0, title, message, platform,
payload: 'Welcome to the app',);

How to show app custom icon in flutter_local_notification in flutter?

I am trying to send local notification in android using flutter_local_notifications and it's working nicely. But the problem is I can not show the app custom icon in notification bar. So, could anyone please help me sharing a solution. Thanks in advance!
Here you go with code and image-
const notificationChannelId = 'fit_jerk';
const notificationId = 1;
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
const AndroidNotificationChannel channel = AndroidNotificationChannel(
notificationChannelId, // id
'MY FOREGROUND SERVICE', // title
description:
'This channel is used for sending daily quotation.', // description
importance: Importance.low, // importance must be at low or higher level
);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await service.configure(
androidConfiguration: AndroidConfiguration(
onStart: onStart,
autoStart: true,
isForegroundMode: true,
notificationChannelId: notificationChannelId, // this must match with notification channel you created above.
initialNotificationTitle: 'FitJerk',
initialNotificationContent: 'Welcome to FitJerk',
foregroundServiceNotificationId: notificationId,
), iosConfiguration: IosConfiguration(),);}
await flutterLocalNotificationsPlugin.show(
notificationId,
'FitJerk',
todayQuote,
const NotificationDetails(
android: AndroidNotificationDetails(
notificationChannelId,
'MY FOREGROUND SERVICE',
icon: 'mipmap/ic_launcher',
ongoing: false,
),
),
);

Flutter Firebase Messaging: Messages not displayed on Android

I'm working on a Flutter App with Firebase Messaging. The notifications work perfectly fine on iOS. On Android, they work when the app is in the foreground, but are not displayed when the app is in background or terminated. I could already rule out doze mode, as the app has been put to background just seconds before triggering the message. The logfile also says, the message is received by the devices, but somehow not displayed.
The problem also only exists when the app is installed via .apk and not when I build directly with Android Studio, so I thought maybe the fingerprinting could cause the problem. But the messages are received by the device and just not displayed -> so that's not it either, right?
I use firebase_messaging: ^12.0.0 as the plugin.
Here is the implementation of my background handler:
static Future<void> setUp() async {
await Firebase.initializeApp(
name: 'Firebase-App',
options: DefaultFirebaseOptions.currentPlatform,
);
//... iOS stuff
//Enable Foreground-Messages for Android
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description:
'This channel is used for important notifications.', // description
importance: Importance.max,
);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
await configLocalNotification(flutterLocalNotificationsPlugin);
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
//Display Foreground-Message on Android
flutterLocalNotificationsPlugin.show(
message.hashCode,
Uri.decodeComponent(message.data['title']).replaceAll('+', ' '),
Uri.decodeComponent(message.data['message']).replaceAll('+', ' '),
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
icon: '#mipmap/ic_launcher',
importance: Importance.max,
),
),
payload: json.encode(message.data),
);
});
await FirebaseMessaging.instance
.setForegroundNotificationPresentationOptions(
alert: true, badge: true, sound: true);
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
}
static Future<void> _firebaseMessagingBackgroundHandler(
RemoteMessage message) async {
await Firebase.initializeApp();
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel', // id
'High Importance Notifications', // title
description:
'This channel is used for important notifications.', // description
importance: Importance.max,
);
await flutterLocalNotificationsPlugin.show(
message.hashCode,
Uri.decodeComponent(message.data['title']).replaceAll('+', ' '),
Uri.decodeComponent(message.data['message']).replaceAll('+', ' '),
NotificationDetails(
android: AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
icon: '#mipmap/ic_launcher',
importance: Importance.max,
// other properties...
),
),
payload: json.encode(message.data),
);
}
static Future<void> configLocalNotification(
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async {
const initializationSettingsAndroid =
AndroidInitializationSettings('#mipmap/ic_launcher');
const initializationSettingsIOS = IOSInitializationSettings();
const initializationSettings = InitializationSettings(
iOS: initializationSettingsIOS, android: initializationSettingsAndroid);
//Handle on click event when App is in foreground or background
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
//handle on click event when app is terminated
final NotificationAppLaunchDetails? notificationAppLaunchDetails =
await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
if (notificationAppLaunchDetails?.didNotificationLaunchApp ?? false) {
final String? selectedNotificationPayload =
notificationAppLaunchDetails!.payload;
debugPrint(
'notification payload on launch: $selectedNotificationPayload');
await onSelectNotification(selectedNotificationPayload);
}
}
Thanks in advance for your help, I'm really at the end of the line here!

How to schedule multiple time specific local notifications in flutter

I am developing water drinking reminder app with flutter.
I want to schedule a list of time specified local notifications that user can add to this list and delete from this list. like this
Any help would appreciate, Thanks.
After hours of research I have solved this problem.
The full code is below.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_native_timezone/flutter_native_timezone.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
class NotificationHelper {
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
/// Initialize notification
initializeNotification() async {
_configureLocalTimeZone();
const IOSInitializationSettings initializationSettingsIOS = IOSInitializationSettings();
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings("ic_launcher");
const InitializationSettings initializationSettings = InitializationSettings(
iOS: initializationSettingsIOS,
android: initializationSettingsAndroid,
);
await flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
/// Set right date and time for notifications
tz.TZDateTime _convertTime(int hour, int minutes) {
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
tz.TZDateTime scheduleDate = tz.TZDateTime(
tz.local,
now.year,
now.month,
now.day,
hour,
minutes,
);
if (scheduleDate.isBefore(now)) {
scheduleDate = scheduleDate.add(const Duration(days: 1));
}
return scheduleDate;
}
Future<void> _configureLocalTimeZone() async {
tz.initializeTimeZones();
final String timeZone = await FlutterNativeTimezone.getLocalTimezone();
tz.setLocalLocation(tz.getLocation(timeZone));
}
/// Scheduled Notification
scheduledNotification({
required int hour,
required int minutes,
required int id,
required String sound,
}) async {
await flutterLocalNotificationsPlugin.zonedSchedule(
id,
'It\'s time to drink water!',
'After drinking, touch the cup to confirm',
_convertTime(hour, minutes),
NotificationDetails(
android: AndroidNotificationDetails(
'your channel id $sound',
'your channel name',
channelDescription: 'your channel description',
importance: Importance.max,
priority: Priority.high,
sound: RawResourceAndroidNotificationSound(sound),
),
iOS: IOSNotificationDetails(sound: '$sound.mp3'),
),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
matchDateTimeComponents: DateTimeComponents.time,
payload: 'It could be anything you pass',
);
}
/// Request IOS permissions
void requestIOSPermissions() {
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}
cancelAll() async => await flutterLocalNotificationsPlugin.cancelAll();
cancel(id) async => await flutterLocalNotificationsPlugin.cancel(id);
}
add your custom times like this
for (int i = 0; i < _provider.getScheduleRecords.length; i++) {
_notificationHelper.scheduledNotification(
hour: int.parse(_provider.getScheduleRecords[i].time.split(":")[0]),
minutes: int.parse(_provider.getScheduleRecords[i].time.split(":")[1]),
id: _provider.getScheduleRecords[i].id,
sound: 'sound0',
);
}
You can use flutter_local_notifications plugin, it can send scheduled, instant and also repeating notifications
await flutterLocalNotificationsPlugin.zonedSchedule(
0,
'scheduled title',
'scheduled body',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
const NotificationDetails(
android: AndroidNotificationDetails(
'your channel id', 'your channel name',
channelDescription: 'your channel description')),
androidAllowWhileIdle: true,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime);
This example will schedule a notification that appears after 5 seconds.
Try Awesome Notifications.
It has many features including seconds precision scheduled notifications.

Notification sound does not work in flutter flutter_local_notifications

Future scheduleAlarmWithSound(Task task) async {
final exists = await _checkIfAlreadyScheduled(task.id);
if (exists) return;
var scheduleNotificationDateTime =
DateTime.fromMillisecondsSinceEpoch(task.endTime);
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('v1', 'Todo', 'Reminder',
icon: 'icon',
importance: Importance.max,
priority: Priority.high,
largeIcon: DrawableResourceAndroidBitmap('icon'),
sound: RawResourceAndroidNotificationSound('annoyingalarm'),
playSound: true,
showWhen: true);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.schedule(
task.id,
task.task,
'Time\'s up!\n Did you completed the task?\nIf not better luck next time.',
scheduleNotificationDateTime,
platformChannelSpecifics);
print("Alarm scheduled with sound");
}
Future scheduleAlarmWithoutSound(Task task) async {
final exists = await _checkIfAlreadyScheduled(task.id);
if (exists) return;
var scheduleNotificationDateTime =
DateTime.fromMillisecondsSinceEpoch(task.endTime);
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('v1', 'Todo', 'Reminder',
icon: 'icon',
importance: Importance.max,
priority: Priority.high,
largeIcon: DrawableResourceAndroidBitmap('icon'),
playSound: false,
showWhen: true);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.schedule(
task.id,
task.task,
'Time\'s up! Did you completed the task?',
scheduleNotificationDateTime,
platformChannelSpecifics);
print("Alarm scheduled without sound");
}
First of all, let me explain my program. It's a reminder app. If we click remind me button then a notification with an alarm sound will be set else a notification without an alarm sound will be set. There is also an option for altering this decision in future. The problem is that when I set a reminder with an alarm sound notification, the sound is not played. But the sound is played if there is no function for setting an alarm without sound.

Categories

Resources