본문 바로가기
개발/Flutter

[번역] flutter_local_notifications

by dev_caleb 2022. 12. 8.
728x90

https://pub.dev/packages/flutter_local_notifications

 

 

 

flutter_local_notifications | Flutter Package

A cross platform plugin for displaying and scheduling local notifications for Flutter applications with the ability to customise for each platform.

pub.dev

 

 

너무 길어서 local notificiation 공부하는 것을 미뤄왔었는데

local notification을 통해서 보여주는 화면을 제어하고 싶은 마음(중요도가 낮은 곳에서는 창을 띄우지 않기)에, 공부해보게 되었다. 

 

 

그럼 시작해보자!

 

Caveats and limitations(주의사항 및 제한사항)

The cross-platform facing API exposed by the FlutterLocalNotificationsPlugin class doesn't expose platform-specific methods as its goal is to provide an abstraction for all platforms. As such, platform-specific configuration is passed in as data. There are platform-specific implementations of the plugin that can be obtained by calling the resolvePlatformSpecificImplementation. An example of using this is provided in the section on requesting permissions on iOS. In spite of this, there may still be gaps that don't cover your use case and don't make sense to add as they don't fit with the plugin's architecture or goals. Developers can fork or maintain their own code for showing notifications in these situations.

 

크로스플랫폼 facing하는 Api(FlutterLocalNotificationsPlugin에 의해 노출 되는) 모든 플랫폼에 추상화를 제공하는 것이 목표이기 때문에 플랫폼별 method를 노출하지 않습니다. 따라서 플랫폼별 구성이 데이터로 전송됩니다. resolvePlatformSpecificImplementation을 호출하여 얻을 수 있는 플러그인의 플랫폼별 구현이 있습니다. 이를 사용하는 예는 IOS requesting permissions 섹션에 나와있습니다. 그럼에도 불구하고 사용 사례를 다루지 않고 플러그인의 아키텍처나 목표와 맞지 않기 때문에 추가하는 것이 타당하지 않은 차이가 여전히 있을 수 있습니다. 개발자는 이러한 상황에서 notifications을 표시하기 위한 자체 코드를 포크하거나 유지할 수 있습니다.

 

 

🔧 Android Setup

계속하기 전에 플러그인의 최신 버전을 사용하고 있는지 확인하십시오. 그 이유는 버전 3.0.1+4 이후 필요한 설정 양이 줄어들었기 때문입니다. 이전에 application들은 안드로이드 매니페스트.xml 파일을 변경해야 했고 릴리스 빌드를 위해 약간 더 많은 설정이 필요했다. 몇 가지 이유로 인해 application이 여전히 이전 버전의 플러그인을 사용해야 하는 경우 릴리스 태그를 사용하여 이전 버전의 readme를 다시 참조하십시오.

 

 

Gradle setup 

Version 10+ on the plugin now relies on desugaring to support scheduled notifications with backwards compatibility on older versions of Android. Developers will need to update their application's Gradle file at android/app/build.gradle. Please see the link on desugaring for details but the main parts needed in this Gradle file would be

 

플러그인의 버전 10+는 이제 desugaring에 의존하여 이전 버전의 안드로이드에서 역호환성을 가진 예약된 notifications을 지원한다. 개발자들은 그들의 애플리케이션의 Gradle 파일을 android/app/build.gradle에서 업데이트해야 할 것이다.  자세한 내용은 desugaring 링크를 참조하십시오. 그러나 이 Gradle 파일에 필요한 main part는 다음과 같습니다.

 

 

android {
  defaultConfig {
    multiDexEnabled true
  }

  compileOptions {
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled true
    // Sets Java compatibility to Java 8
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

dependencies {
  coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}

 

Note that the plugin uses Android Gradle plugin 4.2.2 to leverage this functionality so applications would also need to use that version at a minimum. For a Flutter project, this is specified in android/build.gradle and the main parts would look similar to the following  플러그인은 Android Gradle plugin 4.2.2를 사용하여 이 기능을 활용하므로 applications도 최소한 해당 버전을 사용해야 한다. Flutter 프로젝트의 경우, 이것은 Android/build.gradle로 지정되며 주요 부분은 다음과 유사합니다.

 

buildscript {
   ...

    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.2'
        ...
    }

There have been reports that enabling desugaring may result in a Flutter apps crashing on foldable devices. This would be an issue with Flutter itself, not the plugin. Please see this link for details to try out the solutions there. The plugin also requires that the compileSdkVersion in their application's Gradle file is set to 33

 

desugaring을 활성화하면 foldable devices에서 Flurter 앱이 crashing할 수 있다는 보고가 있었다. 이것은 플러그인이 아닌 Fluter 자체의 문제입니다. 자세한 내용은 이 링크를 참조하여 솔루션을 사용해 보십시오. 플러그인은 또한 응용 프로그램의 Gradle 파일의 compileSdkVersion을 33으로 설정해야 합니다.

 

android {
    compileSdkVersion 33
    ...
}

Requesting permissions on Android 13 or higher (Android 13 이상에 대한 사용 권한 요청)

From Android 13 (API level 33) onwards, apps now have the ability to display a prompt where users can decide if they want to grant an app permission to show notifications. For further reading on this matter read https://developer.android.com/guide/topics/ui/notifiers/notification-permission. To support this applications need target their application to Android 13 or higher and the compile SDK version needs to be at least 33 (Android 13). For example, to target Android 13, update your app's build.gradle file to have a targetSdkVersion of 33. Applications can then call the following code to request the permission where the requestPermission method is associated with the AndroidFlutterLocalNotificationsPlugin class (i.e. the Android implementation of the plugin)

안드로이드 13(API 레벨 33) 이후 앱은 사용자가 알림을 표시할 수 있는 권한을 앱에 부여할지 여부를 결정할 수 있는 prompt를 표시할 수 있는 기능을 갖게 되었다. 이 문제에 대한 자세한 내용은 https://developer.android.com/guide/topics/ui/notifiers/notification-permission를 참조하십시오. 이 applications을 지원하려면 안드로이드 13 이상의 applications을 대상으로 해야 하며 컴파일 SDK 버전이 최소 33(안드로이드 13)이어야 합니다. 예를 들어 Android 13을 대상으로 하려면 앱의 build.gradle 파일을 대상 SdkVersion 33으로 업데이트하십시오. 그런 applications은 다음 코드를 호출하여 requestPermission 메서드가 Android Flutter Local Notifications Plugin 클래스(즉, 플러그인의 Android 구현)와 연관된 권한을 요청할 수 있습니다.

 

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        FlutterLocalNotificationsPlugin();
flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
    AndroidFlutterLocalNotificationsPlugin>().requestPermission();

 

Custom notification icons and sounds (사용자 지정 알림 아이콘 및 소리 )

Notification icons should be added as a drawable resource. The example project/code shows how to set default icon for all notifications and how to specify one for each notification. It is possible to use launcher icon/mipmap and this by default is @mipmap/ic_launcher in the Android manifest and can be passed AndroidInitializationSettings constructor. However, the offical Android guidance is that you should use drawable resources. Custom notification sounds should be added as a raw resource and the sample illustrates how to play a notification with a custom sound. Refer to the following links around Android resources and notification icons.

 

알림 아이콘을 그릴 수 있는 리소스로 추가해야 합니다. 예제 프로젝트/코드는 모든 notification에 대한 기본 아이콘을 설정하는 방법과 각 알림에 대한 기본 아이콘을 지정하는 방법을 보여줍니다.  launcher icon/mipmap을 사용할 수 있으며 안드로이드 매니페스트에서 기본값은 @mipmap/ic_launcher이며 Android를 통과할 수 있습니다. 그러나 안드로이드의 공식적인 guidance은 drawable resources를 사용해야 한다는 것이다. 사용자 지정 알림 소리는 raw resource 로 추가해야 하며 샘플은 사용자 지정 소리로 how to play a notification을 보여줍니다. Android 리소스 및 알림 아이콘에 대한 다음 링크를 참조하십시오.

 

 

When specifying the large icon bitmap or big picture bitmap (associated with the big picture style), bitmaps can be either a drawable resource or file on the device. This is specified via a single property (e.g. the largeIcon property associated with the AndroidNotificationDetails class) where a value that is an instance of the DrawableResourceAndroidBitmap means the bitmap should be loaded from an drawable resource. If this is an instance of the FilePathAndroidBitmap, this indicates it should be loaded from a file referred to by a given file path.

 

큰 아이콘 비트맵 또는 큰 그림 비트맵(큰 그림 스타일과 연결됨)을 지정할 때 비트맵은 장치에서 그릴 수 있는 리소스 또는 파일이 될 수 있습니다. 이것은 단일 속성(예: Android Notification Details 클래스와 관련된 큰 아이콘 속성)을 통해 지정되며, 여기서 DrawableResource Android 비트맵의 인스턴스인 값은 비트맵이 DrawableResource에서 로드되어야 함을 의미합니다. 이것이 FilePath Android 비트맵의 인스턴스인 경우 지정된 파일 경로에서 참조하는 파일에서 로드해야 함을 나타냅니다.

 

For Android 8.0+, sounds and vibrations are associated with notification channels and can only be configured when they are first created. Showing/scheduling a notification will create a channel with the specified id if it doesn't exist already. If another notification specifies the same channel id but tries to specify another sound or vibration pattern then nothing occurs.

Android 8.0+의 경우 소리와 진동은 알림 채널과 연결되며 처음 created될 때만 구성할 수 있습니다. notification을 표시/스케줄링하는 것은 특정한 아이디로 채널을 만들 것이다. (그것이 존재하지 않을 경우). 다른  같은 채널id를 구성한 notification이 another sound 또는 vibration pattern을 구성하면 아무 일도 발생하지 않을 것이다.

 

Full-screen intent notifications 

If your application needs the ability to schedule full-screen intent notifications, add the following attributes to the activity you're opening. For a Flutter application, there is typically only one activity extends from FlutterActivity. These attributes ensure the screen turns on and shows when the device is locked.

application에서  full-screen intent notifications을 예약할 수 있는 기능이 필요한 경우 열려 있는 activity에 다음 속성을 추가합니다. Flutter application의 경우 일반적으로 FlutterActivity에서 확장된 활동이 하나만 있습니다. 이러한 속성을 사용하면 화면이 켜지고 장치가 잠겼을 때 표시됩니다.

 

<activity
    android:showWhenLocked="true"
    android:turnScreenOn="true">

For reference, the example app's AndroidManifest.xml file can be found here.

참고로 예제 앱의 AndroidManifest.xml 파일은 여기에서 확인할 수 있습니다.

Note that when a full-screen intent notification actually occurs (as opposed to a heads-up notification that the system may decide should occur), the plugin will act as though the user has tapped on a notification so handle those the same way (e.g. onDidReceiveNotificationResponse callback) to display the appropriate page for your application.

full-screen intent notification이 실제로 발생할 때(시스템이 발생해야 한다고 결정할 수 있는 미리 보기 알림이 아니라) 플러그인은 사용자가 알림을 두드린 것처럼 작동하므로 동일한 방법(예: DidReceiveNotificationResponse 콜백)으로 응용 프로그램에 적합한 페이지를 표시합니다.

Release build configuration (Release build  구성)

Before creating the release build of your app (which is the default setting when building an APK or app bundle) you will need to customise your ProGuard configuration file as per this link. Rules specific to the GSON dependency being used by the plugin will need to be added. These rules can be found here. Whilst the example app has a Proguard rules (proguard-rules.pro) here, it is recommended that developers refer to the rules on the GSON repository in case they get updated over time.

앱의 릴리스 빌드(APK 또는 앱 번들을 빌드할 때 기본 설정)를 만들기 전에 이 링크에 따라 ProGuard 구성 파일을 사용자 지정해야 합니다. 플러그인에서 사용 중인 GSON 종속성 관련 규칙을 추가해야 합니다. 이 규칙들은 여기에서 찾을 수 있다. 예제 앱은 여기에 Proguard 규칙(proguard-rules.pro)이 있지만, 개발자는 시간이 지남에 따라 업데이트될 경우 GSON 저장소의 규칙을 참조하는 것이 좋습니다.

 

⚠️ Ensure that you have configured the resources that should be kept so that resources like your notification icons aren't discarded by the R8 compiler by following the instructions here. If you fail to do this, notifications might be broken. In the worst case they will never show, instead silently failing when the system looks for a resource that has been removed. If they do still show, you might not see the icon you specified. The configuration used by the example app can be found here where it is specifying that all drawable resources should be kept, as well as the file used to play a custom notification sound (sound file is located here). R8 컴파일러가 알림 아이콘과 같은 리소스를 삭제하지 않도록 유지할 리소스를 구성했는지 확인하십시오. 이렇게 하지 않으면 알림이 손상될 수 있습니다. 최악의 경우 시스템이 제거된 리소스를 찾을 때 자동으로 실패하고 표시되지 않습니다. 그래도 표시되면 지정한 아이콘이 표시되지 않을 수 있습니다. 예제 앱에서 사용하는 구성은 사용자 지정 알림 사운드를 재생하는 데 사용되는 파일뿐만 아니라 모든 그릴 수 있는 리소스를 보관하도록 지정하는 여기에서 찾을 수 있습니다(사운드 파일은 여기에 있음).

 

General setup 

Add the following lines to the application method in the AppDelegate.m/AppDelegate.swift file of your iOS project. See an example of this here.

if #available(iOS 10.0, *) {
  UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}

 

Handling notifications whilst the app is in the foreground (App이 포그라운드일 때 notification handling 하기)

By design, iOS applications do not display notifications while the app is in the foreground unless configured to do so.

For iOS 10+, use the presentation options to control the behaviour for when a notification is triggered while the app is in the foreground. The default settings of the plugin will configure these such that a notification will be displayed when the app is in the foreground.

설계상 iOS 애플리케이션은 앱이 포그라운드에 있는 동안에는 알림을 표시하지 않습니다.
iOS 10+의 경우, 앱이 포그라운드에 있는 동안 notification이 트리거될 때의 동작을 제어하기 위해 presentation 옵션을 사용합니다. 플러그인의 기본 설정은 앱이 foreground에 있을 때 notification이 display되도록 이러한 설정을 구성합니다.

For older versions of iOS, you need to handle the callback as part of specifying the method that should be fired to the onDidReceiveLocalNotification argument when creating an instance DarwinInitializationSettings object that is passed to the function for initializing the plugin.

Here is an example:

 

// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('app_icon');
final DarwinInitializationSettings initializationSettingsDarwin =
    DarwinInitializationSettings(
        onDidReceiveLocalNotification: onDidReceiveLocalNotification);
final LinuxInitializationSettings initializationSettingsLinux =
    LinuxInitializationSettings(
        defaultActionName: 'Open notification');
final InitializationSettings initializationSettings = InitializationSettings(
    android: initializationSettingsAndroid,
    iOS: initializationSettingsDarwin,
    linux: initializationSettingsLinux);
flutterLocalNotificationsPlugin.initialize(initializationSettings,
    onDidReceiveNotificationResponse: onDidReceiveNotificationResponse);

...

void onDidReceiveLocalNotification(
    int id, String title, String body, String payload) async {
  // display a dialog with the notification details, tap ok to go to another page
  showDialog(
    context: context,
    builder: (BuildContext context) => CupertinoAlertDialog(
      title: Text(title),
      content: Text(body),
      actions: [
        CupertinoDialogAction(
          isDefaultAction: true,
          child: Text('Ok'),
          onPressed: () async {
            Navigator.of(context, rootNavigator: true).pop();
            await Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => SecondScreen(payload),
              ),
            );
          },
        )
      ],
    ),
  );
}

 

 

❓ Usage(사용)

Before going on to copy-paste the code snippets in this section, double-check you have configured your application correctly. If you encounter any issues please refer to the API docs and the sample code in the example directory before opening a request on Github.

이 섹션의 코드 스니펫을 복사하여 붙여넣기하기 전에 application 올바르게 구성했는지 다시 확인하십시오. 문제가 발생하면 Github에서 요청을 열기 전에 API 문서와 예제 디렉토리의 샘플 코드를 참조하십시오.

Notification Actions

Notifications can now contain actions but note that on Apple's platforms, these only on iOS 10 or newer and macOS 10.14 or newer. On macOS and Linux (see Linux limitations chapter), these will only run on the main isolate by calling the onDidReceiveNotificationResponse callback.

알림은 이제 동작을 포함할 수 있지만 Apple 플랫폼에서는 iOS 10 이상 및 MacOS 10.14 이상에서만 동작이 가능합니다. macOS 및 Linux(Linux 제한 장 참조)에서는 onDidReceiveNotificationResponse 콜백을 호출하여 기본 분리기에서만 실행됩니다.

On iOS and Android, these will run on the main isolate by calling the onDidReceiveNotificationResponse callback if the configuration has specified that the app/user interface should be shown i.e. by specifying the DarwinNotificationActionOption.foreground option on iOS and the showsUserInterface property on Android.

iOS 및 Android에서는 구성에서 앱/사용자 인터페이스를 표시하도록 지정한 경우(즉, Darwin Notification Action 옵션을 지정한 경우) onDidReceive Notification Response 콜백을 호출하여 기본 분리기에서 실행됩니다.iOS의 forground 옵션과 Android의 UserInterface 속성을 보여줍니다.

If they haven't, then these actions may be selected by the user when an app is sleeping or terminated and will wake up your app. However, it may not wake up the user-visible part of your App; but only the part of it which runs in the background. This is done by spawning a background isolate. 

그렇지 않은 경우, 앱이 절전 모드이거나 종료될 때 사용자가 이러한 작업을 선택하여 앱을 절전 모드로 전환할 수 있습니다. 그러나 앱에서 사용자가 볼 수 있는 부분은 깨우지 않고 백그라운드에서 실행되는 부분만 깨울 수 있습니다. 이 작업은 백그라운드 격리자를 생성하여 수행됩니다.

This plugin contains handlers for iOS & Android to handle these background isolate cases and will allow you to specify a Dart entry point (a function). When the user selects a action, the plugin will start a separate Flutter Engine which will then invoke the onDidReceiveBackgroundNotificationResponse callback

이 플러그인에는 iOS 및 Android에서 이러한 background 격리 cases를 처리하는 핸들러가 포함되어 있으며 Dart 진입점(function)을 지정할 수 있습니다. 사용자가 작업을 선택하면 플러그인이 별도의  Flutter Engine을 시작하여 onDidReceiveBackgroundNotificationResponse 콜백을 호출합니다.

 

Configuration:(구성)

Android and Linux do not require any configuration.Android 및 Linux에는 구성이 필요하지 않습니다.

iOS will require a few steps: iOS에는 몇 가지 단계가 필요합니다.

Adjust AppDelegate.m and set the plugin registrant callback:

AppDelegate.m을 조정하고 플러그인 등록자 콜백을 설정합니다.

 

For Swift, open the AppDelegate.swift and update the didFinishLaunchingWithOptions as follows where the commented code indicates the code to add in and why

Swift의 경우 AppDelegate.swift를 열고 다음과 같이 didFinishLaunchingWithOptions를 업데이트합니다. 여기서 주석 코드는 추가할 코드와 이유를 나타낸다. 

 

import UIKit
import Flutter
// This is required for calling FlutterLocalNotificationsPlugin.setPluginRegistrantCallback method.
import flutter_local_notifications

@UIApplicationMain
override func application(
  _ application: UIApplication,
  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
  // This is required to make any communication available in the action isolate.
  FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
    GeneratedPluginRegistrant.register(with: registry)
  }

  ...
  return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}

 

On iOS/macOS, notification actions need to be configured before the app is started using the initializemethod

 

iOS/macOS에서는 초기화 방법을 사용하여 앱을 시작하기 전에 알림 작업을 구성해야 합니다.

 

final DarwinInitializationSettings initializationSettingsDarwin = DarwinInitializationSettings(
    // ...
    notificationCategories: [
    const DarwinNotificationCategory(
        'demoCategory',
        <DarwinNotificationAction>[
            IOSNotificationAction('id_1', 'Action 1'),
            IOSNotificationAction(
            'id_2',
            'Action 2',
            options: <DarwinNotificationActionOption>{
                DarwinNotificationActionOption.destructive,
            },
            ),
            DarwinNotificationAction(
            'id_3',
            'Action 3',
            options: <DarwinNotificationActionOption>{
                DarwinNotificationActionOption.foreground,
            },
            ),
        ],
        options: <DarwinNotificationCategoryOption>{
            DarwinNotificationCategoryOption.hiddenPreviewShowTitle,
        },
    )
],

 

On iOS/macOS, the notification category will define which actions are availble. On Android and Linux, you can put the actions directly in the AndroidNotificationDetails and LinuxNotificationDetails classes.

 

iOS/macOS에서 알림 카테고리는 사용 가능한 작업을 정의합니다. Android 및 Linux에서 작업을 Android Notification Details 및 Linux Notification Details 클래스에 직접 넣을 수 있습니다.

 

 

Usage:

You need to configure a top level or static method which will handle the action:

@pragma('vm:entry-point')
void notificationTapBackground(NotificationResponse notificationResponse) {
  // handle action
}

Specify this function as a parameter in the initialize method of this plugin:

await flutterLocalNotificationsPlugin.initialize(
    initializationSettings,
    onDidReceiveNotificationResponse: (NotificationResponse notificationResponse) async {
        // ...
    },
    onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
);

 

Remember this function runs (except Linux) in a separate isolate! This function also requires the @pragma('vm:entry-point') annotation to ensure that tree-shaking doesn't remove the code since it would be invoked on the native side. See here for official documentation on the annotation.

이 기능은 별도의 격리된 상태에서 실행됩니다(Linux 제외)! 이 함수는 또한 트리 쉐이킹이 네이티브 측에서 호출되기 때문에 코드를 제거하지 않도록 @pragma('vm:entry-point') 주석을 필요로 한다. 주석에 대한 공식 문서는 여기를 참조하십시오.

Developers should also note that whilst accessing plugins will work, on Android there is no access to the Activity context. This means some plugins (like url_launcher) will require additional flags to start the main Activity again.

또한 개발자는 플러그인에 액세스하는 동안 Android에서는 Activity context에 액세스할 수 없다는 점에 유의해야 합니다. 즉, 일부 플러그인(url_launcher 등)은 기본 활동을 다시 시작하기 위해 추가 플래그를 필요로 합니다.

Specifying actions on notifications: notifications에 대한 작업 지정:

The notification actions are platform specific and you have to specify them differently for each platform.

On iOS/macOS, the actions are defined on a category, please see the configuration section for details.

On Android and Linux, the actions are configured directly on the notification.

notification 작업은 플랫폼별로 다르므로 플랫폼별로 다르게 지정해야 합니다.
iOS/macOS에서는 작업이 범주에 정의되어 있습니다. 자세한 내용은 구성 섹션을 참조하십시오.
Android 및 Linux의 경우 작업은 notification에서 직접 구성됩니다.

 

Future<void> _showNotificationWithActions() async {
  const AndroidNotificationDetails androidNotificationDetails =
      AndroidNotificationDetails(
    '...',
    '...',
    '...',
    actions: <AndroidNotificationAction>[
      AndroidNotificationAction('id_1', 'Action 1'),
      AndroidNotificationAction('id_2', 'Action 2'),
      AndroidNotificationAction('id_3', 'Action 3'),
    ],
  );
  const NotificationDetails notificationDetails =
      NotificationDetails(android: androidNotificationDetails);
  await flutterLocalNotificationsPlugin.show(
      0, '...', '...', notificationDetails);
}

Each notification will have a internal ID & an public action title. 각 통지에는 internal ID와 public action title이 있습니다.

 

Example app 

The example directory has a sample application that demonstrates the features of this plugin.

예제 디렉터리에는 이 플러그인의 기능을 보여주는 샘플 응용 프로그램이 있습니다.

 

 

Initialisation초기화

The first step is to create a new instance of the plugin class and then initialise it with the settings to use for each platform

첫 번째 단계는 플러그인 클래스의 새 인스턴스를 만든 다음 각 플랫폼에 사용할 설정으로 초기화하는 것입니다.

 

FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();
// initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('app_icon');
final DarwinInitializationSettings initializationSettingsDarwin =
    DarwinInitializationSettings(
        onDidReceiveLocalNotification: onDidReceiveLocalNotification);
final LinuxInitializationSettings initializationSettingsLinux =
    LinuxInitializationSettings(
        defaultActionName: 'Open notification');
final InitializationSettings initializationSettings = InitializationSettings(
    android: initializationSettingsAndroid,
    iOS: initializationSettingsDarwin,
    macOS: initializationSettingsDarwin,
    linux: initializationSettingsLinux);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
    onDidReceiveNotificationResponse: onDidReceiveNotificationResponse);

Initialisation can be done in the main function of your application or can be done within the first page shown in your app.

초기화는 application의 main function에서 수행하거나 application에 표시된 첫 페이지 내에서 수행할 수 있습니다.

Developers can refer to the example app that has code for the initialising within the mainfunction. The code above has been simplified for explaining the concepts.

개발자는 메인 기능 내 초기화 코드가 있는 example app을 참조할 수 있다. 위의 코드는 개념을 설명하기 위해 단순화되었다.

Here we have specified the default icon to use for notifications on Android (refer to the Android setup section) and designated the function (onDidReceiveNotificationResponse) that should fire when a notification has been tapped on via the onDidReceiveNotificationResponse callback.

여기서는 Android에서 알림에 사용할 기본 아이콘(Android 설정 섹션 참조)을 지정하고 DidReceiveNotificationResponse 콜백을 통해 알림을 누르면 실행되는 기능(DidReceiveNotificationResponse)을 지정했습니다.

Specifying this callback is entirely optional but here it will trigger navigation to another page and display the payload associated with the notification.

이 콜백을 지정하는 것은 전적으로 선택 사항이지만 여기서 다른 페이지로 탐색을 트리거하고 notification와 관련된 페이로드를 표시합니다.

 

This callback cannot be used to handle when a notification launched an app. Use the getNotificationAppLaunchDetailsmethod when the app starts if you need to handle when a notification triggering the launch for an app e.g. change the home route of the app for deep-linking.

이 콜백은 알림이 앱을 시작할 때 처리하는 데 사용할 수 없습니다. 앱의 시작을 트리거하는 알림을 처리해야 하는 경우 앱이 시작될 때 getNotificationAppLaunchDetails 메서드를 사용합니다. 예를 들어 딥 링크를 위해 앱의 홈 경로를 변경합니다.

Note that all settings are nullable, because we don't want to force developers so specify settings for platforms they don't target. You will get a runtime ArgumentError Exception if you forgot to pass the settings for the platform you target. 모든 설정은 nullable입니다. 개발자에게 타겟하지 않는 플랫폼에 대한 설정을 강제로 지정하도록 하고 싶지 않기 때문입니다. 대상 플랫폼에 대한 설정을 전달하는 것을 잊은 경우runtime ArgumentError가 발생합니다.

void onDidReceiveNotificationResponse(NotificationResponse notificationResponse) async {
    final String? payload = notificationResponse.payload;
    if (notificationResponse.payload != null) {
      debugPrint('notification payload: $payload');
    }
    await Navigator.push(
      context,
      MaterialPageRoute<void>(builder: (context) => SecondScreen(payload)),
    );
}

In the real world, this payload could represent the id of the item you want to display the details of. Once the initialisation is complete, then you can manage the displaying of notifications. Note that this callback is only intended to work when the app is running. For scenarios where your application needs to handle when a notification launched the app refer to here

실제 세계에서 이 페이로드는 세부 정보를 표시할 항목의 ID를 나타낼 수 있습니다. 초기화가 완료되면 알림 표시를 관리할 수 있습니다. 이 콜백은 앱이 실행 중일 때만 작동합니다.(foreground에서만 동작한다는 얘기 ) 알림이 앱을 시작할 때 application이 처리해야 하는 시나리오는 여기를 참조하십시오.

 

이건 밑에 있으니 조금 이따가 읽기

The DarwinInitializationSettings class provides default settings on how the notification be presented when it is triggered and the application is in the foreground on iOS/macOS. There are optional named parameters that can be modified to suit your application's purposes. Here, it is omitted and the default values for these named properties is set such that all presentation options (alert, sound, badge) are enabled.

다윈InitializationSettings 클래스는 notification이 트리거되고application이 iOS/macOS의 foreground에 있을 때 notification을 표시하는 방법에 대한 기본 설정을 제공합니다. application's purposes에 맞게 수정할 수 있는 선택적 명명된 매개변수가 있습니다. 여기서 생략하고 이러한 명명된 속성에 대한 기본값을 설정하여 모든 프레젠테이션 옵션(경고, 사운드, 배지)을 사용할 수 있도록 합니다.

 

On iOS and macOS, initialisation may show a prompt to requires users to give the application permission to display notifications (note: permissions don't need to be requested on Android). Depending on when this happens, this may not be the ideal user experience for your application. If so, please refer to the next section on how to work around this.

iOS와 macOS에서 초기화는 사용자에게 the application permission to display notifications을 요구하는 프롬프트를 표시할 수 있다(참고: 안드로이드에서는 권한을 요청할 필요가 없다. 이러한 상황이 발생하는 시기에 따라 응용프로그램에 이상적인 사용자 환경이 아닐 수 있습니다. 그렇다면 다음 섹션에서 이 문제를 해결하는 방법을 참조하십시오.

For an explanation of the onDidReceiveLocalNotification callback associated with the DarwinInitializationSettings class, please read this. 다윈과 관련된 onDidReceiveLocalNotification 콜백에 대한 설명을 보려면InitializationSettings 클래스입니다. 이것을 참조하십시오.

  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
  const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('app_icon');
  final DarwinInitializationSettings initializationSettingsDarwin =
      DarwinInitializationSettings(
    requestSoundPermission: false,
    requestBadgePermission: false,
    requestAlertPermission: false,
    onDidReceiveLocalNotification: onDidReceiveLocalNotification,
  );
  final MacOSInitializationSettings initializationSettingsMacOS =
      MacOSInitializationSettings(
          requestAlertPermission: false,
          requestBadgePermission: false,
          requestSoundPermission: false);
  final LinuxInitializationSettings initializationSettingsLinux =
    LinuxInitializationSettings(
        defaultActionName: 'Open notification');
  final InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsDarwin,
      macOS: initializationSettingsDarwin,
      linux: initializationSettingsLinux);
  await flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onDidReceiveNotificationResponse: onDidReceiveNotificationResponse);

Then call the requestPermissions method with desired permissions at the appropriate point in your application

final bool result = await flutterLocalNotificationsPlugin
    .resolvePlatformSpecificImplementation<
        IOSFlutterLocalNotificationsPlugin>()
    ?.requestPermissions(
    alert: true,
    badge: true,
    sound: true,
    );

Here the call to flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>() returns the iOS implementation of the plugin that contains APIs specific to iOS if the application is running on iOS.

 

여기서 FlowerLocalNotificationsPlugin.resolvePlatform 특정 구현에 대한 호출<IOSFlutterLocalNotificationsPlugin>()은 응용 프로그램이 iOS에서 실행 중인 경우 iOS 관련 API가 포함된 플러그인의 iOS 구현을 반환합니다.

Similarly, the macOS implementation is returned by calling flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<MacOSFlutterLocalNotificationsPlugin>(). 마찬가지로 macOS 구현은 flotterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<MacOSFlutterLocalNotificationsPlugin>()을 호출하여 반환됩니다. 

 The ?. operator is used as the result will be null when run on other platforms. Developers may alternatively choose to guard this call by checking the platform their application is running on. 다른 플랫폼에서 실행할 경우 결과가 null이 되므로 ? 연산자가 사용됩니다. 개발자는 응용 프로그램이 실행 중인 플랫폼을 확인하여 이 호출을 보호하도록 선택할 수도 있습니다.

 

Displaying a notification(notification 보여주기)

const AndroidNotificationDetails androidNotificationDetails =
    AndroidNotificationDetails('your channel id', 'your channel name',
        channelDescription: 'your channel description',
        importance: Importance.max,
        priority: Priority.high,
        ticker: 'ticker');
const NotificationDetails notificationDetails =
    NotificationDetails(android: androidNotificationDetails);
await flutterLocalNotificationsPlugin.show(
    0, 'plain title', 'plain body', notificationDetails,
    payload: 'item x');

Here, the first argument is the id of notification and is common to all methods that would result in a notification being shown. This is typically set a unique value per notification as using the same id multiple times would result in a notification being updated/overwritten. 여기서 첫 번째 인수는 알림의 ID이며 알림이 표시되는 모든 방법에 공통적입니다. 동일한 ID를 여러 번 사용하면 알림이 업데이트/덮어쓰기되기 때문에 일반적으로 알림당 고유한 값이 설정됩니다.

 

The details specific to the Android platform are also specified. 안드로이드 플랫폼 특유의 세부 사항도 명시되어 있다. This includes the channel details that is required for Android 8.0+. 여기에는 Android 8.0+에 필요한 채널 세부 정보가 포함됩니다. Whilst not shown, it's possible to specify details for iOS and macOS as well using the optional iOS and macOS named parameters if needed. 표시되지는 않지만 필요한 경우 iOS 및 MacOS 이름 지정 매개 변수를 사용하여 iOS 및 MacOS에 대한 세부 정보를 지정할 수 있습니다.The payload has been specified ('item x'), that will passed back through your application when the user has tapped on a notification. Note that for Android devices that notifications will only in appear in the tray and won't appear as a toast aka heads-up notification unless things like the priority/importance has been set appropriately. Refer to the Android docs (https://developer.android.com/guide/topics/ui/notifiers/notifications.html#Heads-up) for additional information. The "ticker" text is passed here is optional and specific to Android. This allows for text to be shown in the status bar on older versions of Android when the notification is shown.

 

 

 

 

 

 

 

 

728x90