Home > Software design >  How to know when app got killed and clear all the pending notifications in flutter?
How to know when app got killed and clear all the pending notifications in flutter?

Time:04-29

My app plays scheduled notifications (I'm using flutter local notification) in the background but when the phone shutdown and opens again later all the bunch of schedules notifications started to play overlapping each other (it annoys user because it plays with custom sound) so I don't want any notification get displayed if the user swipe & kills the app or shutdown & opens again. so I want to clear all my pending notification when the app got killed.

Please let me know if there's any solution available for this.

CodePudding user response:

Maybe you can clean all notifications where scheduled before runApp function in main function. With

await flutterLocalNotificationsPlugin.cancelAll();

CodePudding user response:

Replace your

android/app/src/main/kotlin/com/example/appname>/MainActivity.kt

with the following.

import android.app.NotificationManager
import android.content.Context
import io.flutter.embedding.android.FlutterActivity


class MainActivity: FlutterActivity() {

    override fun onResume() {
        super.onResume()
        closeAllNotifications();
    }

    private fun closeAllNotifications() {
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.cancelAll()
    }

}

And For IOS I use UNUserNotificationCenter:

import UIKit
import Flutter
import UserNotifications

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {

    GeneratedPluginRegistrant.register(with: self)
    if #available(iOS 10.0, *) {
        application.applicationIconBadgeNumber = 0 // For Clear Badge Counts
        let center = UNUserNotificationCenter.current()
        center.removeAllDeliveredNotifications() // To remove all delivered notifications
        center.removeAllPendingNotificationRequests()
    }
     
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
  • Related