androidswiftflutterpush-notificationlocalnotification

Flutter scheduled local Notificaton


I have used flutterLocalNotificationsPlugin.zonedSchedule() to schedule the local Notification and its working great.

When this Scheduled Local notification is send before i want to check App Is in Foreground or app Is in Background.

If Flutter app is Running means app is Foreground so I want that scheduled Notification as In App Notification and if is closed means App is in Background than send Scheduled notification as actual Notification.

I Have Done this Functionality in IOS using Native swift code in Flutter But How can i do this for android side code??


Solution

  • This can be down without the help of native codes and will work for both ios and android (little modification to the code maybe needed).

    First, we create a life cycle handler class that will extend WidgetsBindingObserver class. In short, this class is used in flutter to notify objects of changes in the environment. To learn more visit: https://api.flutter.dev/flutter/widgets/WidgetsBindingObserver-class.html

    import 'package:flutter/material.dart';
    
    final lifecycleEventHandler = LifecycleEventHandler._();
    
    class LifecycleEventHandler extends WidgetsBindingObserver {
      bool inBackground = true;
    
      LifecycleEventHandler._();
    
      initialise() {
        WidgetsBinding.instance.addObserver(lifecycleEventHandler);
      }
    
      @override
      Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
        switch (state) {
          case AppLifecycleState.resumed:
            inBackground = false;
             print('App is in foreground');
            break;
          case AppLifecycleState.inactive:
          case AppLifecycleState.paused:
          case AppLifecycleState.detached:
            inBackground = true;
            print('App is in background');
            break;
        }
      }
    }
    

    Now, we will use this class from whenever we want our app to listen to changes. We can add this to our main.dart file inside void main(). If you want to listen to changes from the start of the app.

    lifecycleEventHandler.initialise();
    

    Calling the above function will add the observer to your app.

    Now, inside your notification function do the following:

    Future showNotification() async {
      if (!lifecycleEventHandler.inBackground){
        //Show in app notification
      }
      //otherwise notification in notification tray
      ...
    }