본문 바로가기
[개발] 이야기

[flutter] Setting and implementing Local Notification Available for both Android and iOS, clearing registered notifications remove

by 헤이나우
반응형

목차

     

    Flutter Local Notification package description


    - This is a package used by Flutter to send notifications to the device currently in use. If you look at the flutter_local_notification on the pub.dev site, you can see that it has over 5,000 likes. More than 5,000 is a very high number, but it is proof that the stability of this plugin is confirmed and that many people are using it. So, instead of going through the trouble of implementing it, let’s create a function that sends notifications to the device using this plugin!

    1. flutter_local_notifications install

    - Access https://pub.dev/packages/flutter_local_notifications and copy the installation link.
    - Enter pubspec.yaml in dependencies and then enter pub.get

    2. Android Settings

    - In order to receive notifications, various permissions are required. The permission to receive notifications must be declared on Android.
    - Android permission settings -> /android/app/src/main/AndroidManifest.xml

    <manifest xmlns:android="http://schemas.android.com/apk/res/android">
    
        <!--local notification -->
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
        <uses-permission android:name="android.permission.VIBRATE" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
        <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
        <!--local notification -->
        
        <application
            android:label="@string/app_name"
            android:name="${applicationName}"
            android:icon="@mipmap/ic_launcher">
            <activity
                android:name=".MainActivity"
                android:showWhenLocked="true"
                android:turnScreenOn="true"
                android:exported="true"
                android:launchMode="singleTop"
                android:theme="@style/LaunchTheme"
                android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
                android:hardwareAccelerated="true"
                android:windowSoftInputMode="adjustResize">
                <meta-data
                  android:name="io.flutter.embedding.android.NormalTheme"
                  android:resource="@style/NormalTheme"
                  />
    
                <intent-filter>
                    <action android:name="android.intent.action.MAIN"/>
                    <category android:name="android.intent.category.LAUNCHER"/>
                </intent-filter>
            </activity>
            
            <!--local notification -->
            <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" android:exported="false" />
            <receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver" android:exported="false">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED"/>
                    <action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
                    <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                </intent-filter>
            </receiver>
            <!--local notification -->
            
        </application>
    </manifest>

    - <!--Local notification permission settings --> Just check the code between comments.

     

    2-1. uses-permission

    - These are the permissions you set to receive notifications.
    - Permissions such as vibrating or waking up the phone are included. Be sure to enter those four items.

    2-2. receiver

    - Create a receive so that the currently registered notifications are maintained even when the phone is rebooted, so that the receive is executed when the phone is rebooted.
    - Do not change the android:name of the receiver to the path provided in the plugin, but copy and paste it as is.

    2-3 Show notifications in locked state

    android:showWhenLocked="true"
    android:turnScreenOn="true"

    3. iOS settings

     

     - /ios/Runner/AppDelegate.swift

    import UIKit
    import Flutter
    
    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
      override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
      ) -> Bool {
      
    	//Let's enter this part
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
        }
    
    
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
    }

    4. Using & writing code in flutter

    4-1. init

    - Before it is built at the top of the main function, it must be initialized to use the Notification service.
    - Unlike Android, only pay attention to the logic that receives iOS push-related permissions from the user.

    void main() async {
      WidgetsFlutterBinding.ensureInitialized();
      
      await _initNotiSetting(); //local Notifcation init
      
      .
      .
      .
      build..
    }
    
    Future<void> _initNotiSetting() async {
      //Notification object create
      final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    
      //Android init
      final AndroidInitializationSettings initSettingsAndroid =
          AndroidInitializationSettings('@mipmap/ic_launcher');
    
      // IOS init
      // When the request... value is set to true, permission is requested as soon as the app is turned on.
      final DarwinInitializationSettings initSettingsIOS =
          DarwinInitializationSettings(
              requestSoundPermission: true,
              requestBadgePermission: true,
              requestAlertPermission: true);
    
      //Notification init
      final InitializationSettings initSettings = InitializationSettings(
        android: initSettingsAndroid,
        iOS: initSettingsIOS,
      );
      await flutterLocalNotificationsPlugin.initialize(
        initSettings,
      );
      //Notification initial settings
       //You can create a callback function that operates when a message is pressed by adding the onSelectNotification option. (You do not need to use it)
       //If not used, the app will just run when the notification is clicked.
      //await flutterLocalNotificationsPlugin.initialize(initSettings,onSelectNotification:[콜백] );
    }

    4-2. Create a notification class

    - This is a code that actually uses the Noti function. For more details, check the code with comments.

    static Future sendLocalNotificationDateTime({
        required int idx,
        required DateTime date,
        required String title,
        required String content,
      }) async {
        bool? result = null;
        final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
        
        if (Platform.isAndroid) {
          
          result = true;
        } else {
          //When using IOS, check the current permissions (notifications) and request permission from the user.
          result = await flutterLocalNotificationsPlugin
              .resolvePlatformSpecificImplementation<
                  IOSFlutterLocalNotificationsPlugin>()
              ?.requestPermissions(
                alert: true,
                badge: true,
                sound: true,
              );
        }
        //Set notification settings for each model.
        var android = AndroidNotificationDetails(
          'id',
          title,
          channelDescription: content,
          importance: Importance.max,
          priority: Priority.max,
          color: const Color.fromARGB(255, 255, 0, 0),
        );
    
        var ios = DarwinNotificationDetails();
        //기종별 설정값
        var detail = NotificationDetails(android: android, iOS: ios);
        //result: 권한여부
        if (result == true) {
          await flutterLocalNotificationsPlugin
              .resolvePlatformSpecificImplementation<
                  AndroidFlutterLocalNotificationsPlugin>()
              ?.deleteNotificationChannelGroup('id');
          //Register the notification to the actual device scheduler.
           // You can set the time to send notifications in _setNotiTime.
          await flutterLocalNotificationsPlugin.zonedSchedule(
            idx,
            title,
            content,
            _setNotiTime(date: date),
            detail,
            //androidAllowWhileIdle: true,
            uiLocalNotificationDateInterpretation:
                UILocalNotificationDateInterpretation.absoluteTime,
            //This option is important (depending on the option value, set the option to operate according to the time only or to operate according to the month, day, and time)
             //If it is set to time as shown below, a notification will occur if the time is the same no matter how much you specify the date in setNotTime.
            matchDateTimeComponents:
                DateTimeComponents.dateAndTime, //또는dayOfMonthAndTime
          );
        }
      }
    
      static tz.TZDateTime _setNotiTime({
        required DateTime date,
      }) {
        tz.initializeTimeZones(); 
        tz.setLocalLocation(tz.getLocation('Asia/Seoul')); //TimeZone 설정(외국은 다르게!)
        final now = tz.TZDateTime.now(tz.local);
        var scheduledDate = tz.TZDateTime(tz.local, now.year, now.month, now.day,
            date.hour, date.minute, date.second); //alarm date time
        //var test = tz.TZDateTime.now(tz.local).add(const Duration (seconds: 5));
        
        return scheduledDate;
      }

    4-3 Use

    // idx: Notification unique number
    // date: notification time
    // title: Notification title
    //content: Notification content
    LocalNotification.sendLocalNotificationDateTime(idx: idx, date: endDT, title: "{title}", content: "content");

     

    4-4 How to unregister registered notifications

    static clear({required int idx}) {
        final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
        flutterLocalNotificationsPlugin.cancel(idx);
      }

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    Hola

    반응형

    댓글