Search code examples
androidflutterdartmobilenotifications

Local notificaitons for flutter only works on emulator but not a real Android device?


I am implementing three buttons (5, 10, and 15 minutes) that are supposed to schedule a future notification for the user. E.g. when they click 5 minutes, a notification will pop up after 5 minutes with a message no matter what. I am using the local notifications package for flutter. I found that I am able to get it to work well with numerous emulators, however, when I try it on a real Android device, it does not function at all. The notification will not pop up.

Here is the code I used, let me know if anything is wrong or how I need to fix it to work on a real Android device:

 import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:rxdart/rxdart.dart';
import 'package:timezone/data/latest_all.dart';
import 'package:timezone/timezone.dart';

class NotificationApi {
static final _notifications = FlutterLocalNotificationsPlugin();
static final onNotifications = BehaviorSubject<String?>();

static bool notificationPermission = true;

static Future _notificationDetails() async {
    return const NotificationDetails(
        android: AndroidNotificationDetails(
            'channelID',
            'channelName',
            channelDescription: 'channelDescription',
            importance: Importance.high, // Set the importance to high
            priority: Priority.high, // Set the priority to high
            playSound: true,
        ),
    );
}

static Future init({bool initScheduled = false}) async {
    const AndroidInitializationSettings android =
        AndroidInitializationSettings('@mipmap/ic_launcher');
    const InitializationSettings settings =
        InitializationSettings(android: android);

    final details = await _notifications.getNotificationAppLaunchDetails();
    if (details != null && details.didNotificationLaunchApp) {
        onNotifications.add(details.notificationResponse?.payload);
    }

    await _notifications.initialize(settings,
        onDidReceiveNotificationResponse: ((payload) async {
            onNotifications.add(payload.payload);
        }));

    if (initScheduled) {
        initializeTimeZones();
        final timeZoneName = await FlutterTimezone.getLocalTimezone();
        setLocalLocation(getLocation(timeZoneName));
    }
}

static Future<bool?> checkNotificationPermissions() async {
    if (Platform.isAndroid) {
        await _notifications
            .resolvePlatformSpecificImplementation<
                AndroidFlutterLocalNotificationsPlugin>()
            ?.requestPermission();
        return await _notifications
            .resolvePlatformSpecificImplementation<
                AndroidFlutterLocalNotificationsPlugin>()
            ?.areNotificationsEnabled();
    }
    return null;
}

static void showScheduledNotification({
    required int id,
    String? title,
    String? body,
    String? payload,
    required DateTime scheduledDate,
}) async =>
    _notifications.zonedSchedule(id, title, body,
        TZDateTime.from(scheduledDate, local), await _notificationDetails(),
        androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime,
        payload: payload);

static void cancel(int id) => _notifications.cancel(id);
static void cancelAll() => _notifications.cancelAll();
}

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
    return MaterialApp(
        home: HomePage(),
    );
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
bool _notificationPermission = true;

@override
void initState() {
    super.initState();

    WidgetsBinding.instance!.addPostFrameCallback((_) async {
        await NotificationApi.init(initScheduled: true);
        _listenNotifications();
        NotificationApi.checkNotificationPermissions().then((value) {
            setState(() {
                _notificationPermission = value ?? true;
            });
        });
    });
    }

@override
void dispose() {
    NotificationApi.onNotifications.close();
    super.dispose();
}  

Future<void> _requestNotificationPermission() async {
    final bool? result = await NotificationApi.checkNotificationPermissions();
    if (result != null && !result) {
        setState(() {
            _notificationPermission = false;
        });
        // Handle the case where the user has not granted notification permissions
    }
    }

void _scheduleNotification(int minutes) {
    final scheduledDate = DateTime.now().add(Duration(minutes: minutes));
    NotificationApi.showScheduledNotification(
        id: minutes,
        scheduledDate: scheduledDate,
        title: 'Time is up',
        body: 'This is the notificaiton message that needs to be displayed.',
    );

    ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text('Notification scheduled for $minutes minutes.'),
        ),
    );
    }

void _listenNotifications() =>
    NotificationApi.onNotifications.stream.listen((payload) {
        // Handle notification payload, if needed
        print('Notification payload: $payload');
    });

@override
Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            title: const Text('Local Notification Page'),
        ),
        body: Center(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                    ElevatedButton(
                        onPressed: () async {
                            await _requestNotificationPermission();
                            _scheduleNotification(5);
                        },
                        child: const Text('Schedule notification message in 5 Minutes'),
                    ),
                    SizedBox(height: 16),
                    ElevatedButton(
                        onPressed: () async {
                            await _requestNotificationPermission();
                            _scheduleNotification(10);
                        },
                        child: const Text('Schedule notification message in 10 Minutes'),
                    ),
                    SizedBox(height: 16),
                    ElevatedButton(
                        onPressed: () async {
                            await _requestNotificationPermission();
                            _scheduleNotification(15);
                        },
                        child: const Text('Schedule notification message in 15 Minutes'),
                    ),
                ],
            ),
        ),
    );
}
}

I tried this code above, tried updating my local notifications package (was 14.0.0, then the newest version, but I went back to 14.0.0 because I had issues with the newest version), and tried new emulators. But on a real Android device it doesn't display a notification at all.


Solution

  • Try these

    1- check your permission requests in AndroidManifest.xml

    2- when u install the app grant all permission in app settings

    3- try to send notifications and check the terminal

    I hope that helped

    all the best