AndroidAlarmManager calls flutterLocalNotificationsPlugin.show(), but no notification is displayed - android

I have a terrible problem with AlarmManager and FlutterLocalNotification.
When I call show() from AlarmManager callback, in order to write a scheduled notification, no notification is displayed.
I initialise the flutter_local_notification plugin in the main() function of the App in this way:
NotificationManager n = new NotificationManager();
void main() async
{
WidgetsFlutterBinding.ensureInitialized();
await AndroidAlarmManager.initialize();
n.initNotificationManager();
runApp(MainClass());
}
NotificationManager class is:
class NotificationManager
{
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
AndroidInitializationSettings initializationSettingsAndroid;
IOSInitializationSettings initializationSettingsIOS;
InitializationSettings initializationSettings;
void initNotificationManager()
{
initializationSettingsAndroid = new AndroidInitializationSettings('#mipmap/ic_launcher');
initializationSettingsIOS = new IOSInitializationSettings();
initializationSettings = new InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
void showNotificationWithDefaultSound(String title, String body, String payload)
{
var androidPlatformChannelSpecifics =
new AndroidNotificationDetails('your channel id',
'your channel name',
'your channel description',
importance: Importance.Max,
priority: Priority.High);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
var platformChannelSpecifics = new NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
flutterLocalNotificationsPlugin.show(0, title, body, platformChannelSpecifics, payload: payload);
}
}
In the initState() of a page inside the App I make AlarmManager calls the callback in this way:
void initState()
{
super.initState();
AndroidAlarmManager.oneShotAt(DateTime.now().add(Duration(seconds: 5)), 0, alarmCallback);
//......
}
The callback is:
alarmCallback()
{
n.showNotificationWithDefaultSound("Title", "MySuperBody", "Hey, this is the Payload!");
return;
}
How can I fix this?

The solution is to migrate your project to AndroidX using Refractor in android studio.

Related

Flutte local notification at a specific time daily for android

android only
I tried NotificationServices Scheduled method with _flutterLocalNotificationsPlugin.periodicallyShow and it doesn't seems to work.
also how to test it in a android emulator (changing the date and time on the device works or not)
notification_service.dart
class NotificationServices {
FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
final AndroidInitializationSettings _androidInitializationSettings =
AndroidInitializationSettings('logo1');
void initialiseNotifications() async {
InitializationSettings initializationSettings = InitializationSettings(
android: _androidInitializationSettings,
);
await _flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
void scheduleNotifications(String title, String body) async {
int hour = 19;
var ogValue = hour;
int minute = 05;
var time = Time(hour,minute,20);
AndroidNotificationDetails androidNotificationDetails =
const AndroidNotificationDetails(
'channelId',
'channelName',
importance: Importance.max,
priority: Priority.high,
);
NotificationDetails notificationDetails = NotificationDetails(
android: androidNotificationDetails,
);
await _flutterLocalNotificationsPlugin.periodicallyShow(
0, 'title', 'body', RepeatInterval.daily, notificationDetails);
}
void stopNotifications() async{
_flutterLocalNotificationsPlugin.cancel(0);
}
}
main.dart
NotificationServices notificationServices = NotificationServices();
notificationServices.initialiseNotifications();
notificationServices.scheduleNotifications('Daily Reminder', 'You have a ToDo list to complete');

Why Flutter Android Alarm Manager is not working in device once the App is closed?

I am new to flutter.
Alarm functionality is working unless the app is closed.
After closing the app android alarm manager is not working.
I have put all the tags in AndroidManifest.xml.
On call back this _ringAlarm() method has been called.
Future<void> _ringAlarm() async {
NotificationManager n = new NotificationManager();
n.initNotificationManager();
n.showNotificationWithDefaultSound("Keep it,it's YOURS", widget.text.split("_")[1]);
//n.showNotificationWithAlarmSound();
//Working in Simulator but not in Device
//n._showNotificationCustomSound();
//FlutterRingtonePlayer.playAlarm();
FlutterRingtonePlayer.play(
android: AndroidSounds.alarm,
ios: IosSounds.glass,
looping: false, // Android only - API >= 28
volume: 1, // Android only - API >= 28
asAlarm: false, // Android only - all APIs
);
Future.delayed(const Duration(milliseconds: 4000), () {
FlutterRingtonePlayer.stop();
});
print(Const.todoTextList);
}
Here is implementation of notification manager class
class NotificationManager
{
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
AndroidInitializationSettings initializationSettingsAndroid;
IOSInitializationSettings initializationSettingsIOS;
InitializationSettings initializationSettings;
void initNotificationManager()
{
initializationSettingsAndroid = new AndroidInitializationSettings('#mipmap/ic_launcher');
initializationSettingsIOS = new IOSInitializationSettings();
initializationSettings = new InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
void showNotificationWithDefaultSound(String title, String body)
{
var androidPlatformChannelSpecifics = new AndroidNotificationDetails('your channel id', 'your channel name', 'your channel description', importance: Importance.Max, priority: Priority.High);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
var platformChannelSpecifics = new NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
flutterLocalNotificationsPlugin.show(0, title, body, platformChannelSpecifics);
}
static const MethodChannel platform = MethodChannel('your channel name');
/* Future<void> showNotificationWithAlarmSound() async {
/// this calls a method over a platform channel implemented within the
/// example app to return the Uri for the default alarm sound and uses
/// as the notification sound
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
final String alarmUri = await platform.invokeMethod('getAlarmUri');
final UriAndroidNotificationSound uriSound =
//UriAndroidNotificationSound(AndroidSounds.alarm.toString());
UriAndroidNotificationSound(alarmUri);
final AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'uri channel id', 'your channel name', 'your channel description',
sound: uriSound,
styleInformation: const DefaultStyleInformation(true, true));
final NotificationDetails platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics,iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0, 'uri sound title', 'uri sound body', platformChannelSpecifics);
}*/
//For custom notification
Future<void> _showNotificationCustomSound() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails(
'your other channel id',
'your other channel name',
'your other channel description',
sound: RawResourceAndroidNotificationSound('easy_going'),
);
const IOSNotificationDetails iOSPlatformChannelSpecifics =
IOSNotificationDetails(sound: 'easy_going');
//const MacOSNotificationDetails macOSPlatformChannelSpecifics =
//MacOSNotificationDetails(sound: 'slow_spring_board.aiff');
const NotificationDetails platformChannelSpecifics = NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'custom sound notification title',
'custom sound notification body',
platformChannelSpecifics);
}
}
It is working good if I don't close actual app.Once I close the app notification will not work.I am unable to reproduce this issue in simulator.If I get any suggestion how to reproduce this in simulator that also will be helpful to me.

Dismiss notification on click

I am using Flutter Local Notification to trigger periodic notifications in my app.
It provides a callback, which is executed when user taps on the notification,
I want to use the callback to run a async function, but i don't want to launch the app when the user clicks on it. I simply want to dismiss the notification.
Is there any way to achieve it?
Here is my code.
var initializationSettingsAndroid =
AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOS = IOSInitializationSettings();
var initializationSettings = InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
_notificationPlugin = FlutterLocalNotificationsPlugin();
_notificationPlugin.initialize(
initializationSettings,
onSelectNotification: onSelectNotification,
);
My callback function,
Future onSelectNotification(String payload) async {
showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text("Hello"),
content: Text("content"),
),
);
AnAsyncFunction();
}
Notification triggering function,
Future getPeriodicNoification() async {
print("hello");
// // Show a notification every minute with the first appearance happening a minute after invoking the method
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your channel id',
'your channel name',
'your channel description',
importance: Importance.Max,
priority: Priority.High,
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await _notificationPlugin.periodicallyShow(0, 'repeating title',
'repeating body', RepeatInterval.EveryMinute, );
}

Not launching the app on notification click? Flutter Local Notifications

I am working on a project, I have used Flutter Local Notifications to show periodic notifications,
I'm trying to figure out if there is a way to not to launch the app on notification click, for example, when a user clicks on a notification, it should just disappear from the notification panel.
This is the code I tried so far,
Initialising,
var initializationSettingsAndroid =
AndroidInitializationSettings('#mipmap/ic_launcher');
var initializationSettingsIOS = IOSInitializationSettings();
var initializationSettings = InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
_notificationPlugin = FlutterLocalNotificationsPlugin();
_notificationPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
Calling,
Future getPeriodicNoification() async {
print("hello");
// Show a notification every minute with the first appearance happening a minute after invoking the method
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your channel id',
'your channel name',
'your channel description',
importance: Importance.Max,
priority: Priority.High,
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await _notificationPlugin.periodicallyShow(0, 'repeating title',
'repeating body', RepeatInterval.EveryMinute, platformChannelSpecifics);
}
Callback function(On notification click)
Future onSelectNotification(String payload) async {
ThisisAnAsyncFunction();
}
Please help.
You can use the close function under BehaviourSubject that you use when adding the payload.
static final onNotifications = BehaviorSubject<String?>();
then call this when selecting the notification.
onSelectNotification() => onNotifications.close();

There's some error on my Flutter Local Notification

I need help, there's an error when calling Local Notification.
For the initState :
initState() {
super.initState();
flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
var initializationSettingsAndroid =
new AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = new IOSInitializationSettings();
var initializationSettings = new InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
FlutterLocalNotificationsPlugin().initialize(initializationSettings, onSelectNotification: onSelectNotification);
}
For the function :
showNotification() async {
var android = new AndroidNotificationDetails('Channel ID', 'Channel Name', 'channelDescription');
var iOS = new IOSNotificationDetails();
var platform = new NotificationDetails(android, iOS);
await flutterLocalNotificationsPlugin.show(
0, 'New Notification', 'Flutter Local Notif', platform,payload: 'test notification');
}
The error is "PlatformException (PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null))"
I've already tried on the documentation and also youtube, but I always get this error message
I have faced this, and in my case it was an icon problem app_icon
in your initState function replace this
var initializationSettingsAndroid = new AndroidInitializationSettings('app_icon');
with this
var initializationSettingsAndroid = new AndroidInitializationSettings('#mipmap/ic_launcher');
Hope this helps you.
Add your app_icon.png to MY_PROJECT\android\app\src\main\res\drawable\app_icon.png
However, for me the error was in androidInitialization. I was initializing it this way:
var androidInit = AndroidInitializationSettings('app_icon.png');
Here, the .png shouldn't be added. I know this might be silly but if it helps anyone out there facing the same problem then there you go! This is the correct method:
var androidInit = AndroidInitializationSettings('app_icon');
this one works for me you can give a chance
#override
initState() {
super.initState();
to the Android head project
var initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = IOSInitializationSettings(
onDidReceiveLocalNotification: onDidReceiveLocalNotification);
var initializationSettings = InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: onSelectNotification);
}
Future<void> _showNotification() async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'your channel id', 'your channel name', 'your channel description',
importance: Importance.Max, priority: Priority.High, ticker: 'ticker');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0, 'plain title', 'plain body', platformChannelSpecifics,
payload: 'item x');
}
Future<void> onSelectNotification(String payload) async {
if (payload != null) {
debugPrint('notification payload: ' + payload);
}
}
There is problem in your plugin initialization. I see in your code, you created the instance flutterLocalNotificationsPlugin but used FlutterLocalNotificationsPlugin().initialize() instead. And then you tried to show notification with the created instance which has not been initialized.
I got this error for the same reason - my FlutterLocalNotificationsPlugin was not initialized properly. To check if it is, I tried the below code:
void main() {
runApp(MyApp());
initializeNotification(); //Its Important to place this line after runApp() otherwise FlutterLocalNotificationsPlugin will not be initialize and you will get the error as mentioned in the question.
}
void initializeNotification() async {
try {
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
var initializationSettingsAndroid = AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = IOSInitializationSettings();
var initializationSettings = InitializationSettings(initializationSettingsAndroid, initializationSettingsIOS);
await flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: didSelectNotification);
} catch(e) {
print(e.toString());
}
}
If it catch any exception, your flutterLocalNotificationsPlugin has not been initialized, and you will get an error.
Also try to wrap initialization code in separate async-await function.
In my case, I added app_icon.png to the android drawables, in this path : MY_PROJECT\android\app\src\main\res\drawable
Take a look at the source code here
https://github.com/MaikuB/flutter_local_notifications/tree/master/flutter_local_notifications/example/android/app/src/main/res/drawable
Copy Paste all drawables to your project, it will work.
And Don't Forget to add these receivers to Manifest
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
</intent-filter>
</receiver>
for me adding WidgetsFlutterBinding.ensureInitialized(); to main.dart before creating AndroidInitializationSettings helps.
uture _requestPermissions() async {
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('app_icon');
/// Note: permissions aren't requested here just to demonstrate that can be
/// done later
final DarwinInitializationSettings initializationSettingsIOS =
DarwinInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: false,
requestSoundPermission: false,
onDidReceiveLocalNotification: (
int id,
String? title,
String? body,
String? payload,
) async {
didReceiveLocalNotificationSubject.add(
ReceivedNotification(
id: id,
title: title,
body: body,
payload: payload,
),
);
});

Categories

Resources