본문 바로가기

개발/Flutter

Flutter 알림 설정

728x90

Flutter 에서 알림 기능을 지원하는 좋은 플러그인이 있다.

 

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

 

 

우선 플러그인을 pubspec.yaml 파일에 추가한다.

현재는 5.0.0+1 버전이 최신 버전이다.

flutter_local_notifications: ^5.0.0+1

 

현지 시간에 맞추기 위해서 flutter_native_timezone 이란 플러그인도 필요하므로 추가해 준다.

flutter_native_timezone: ^1.0.10

 

 

안드로이드 설정

android/app/src/main/AndroidManifest.xml 파일에 아래와 같이 추가한다.

 

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

 

728x90

iOS 설정

ios/Runner/AppDelegate.swift 파일에 아래와 같이 적용한다.

 

Object-C 파일인 경우

if (@available(iOS 10.0, *)) {
  [UNUserNotificationCenter currentNotificationCenter].delegate = (id<UNUserNotificationCenterDelegate>) self;
}

 

Swift 파일인 경우

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

 

파일 적용

우선 플러그인을 import 해 준다.

import 'package:timezone/timezone.dart' as tz;
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

 

init 메소드에서 초기화 한다.

var initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');
var initializationSettingsIOS = IOSInitializationSettings(
        requestAlertPermission: true,
        requestBadgePermission: true,
        requestSoundPermission: true);

var initializationSettings = InitializationSettings(
        android: initializationSettingsAndroid, iOS: initializationSettingsIOS);

flutterLocalNotificationsPlugin.initialize(initializationSettings);

 

 

iOS의 경우 사용자 권한이 필요하므로 init에서 권한을 묻는다. 

flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
              IOSFlutterLocalNotificationsPlugin>()
          ?.requestPermissions(
            alert: true,
            badge: true,
            sound: true,
          );

 

 

로컬 시간 초기화 함수를 추가해 준다.

Future<void> configureLocalTimeZone() async {
  String timezone;
  tz.initializeTimeZones();
  try {
    timezone = await FlutterNativeTimezone.getLocalTimezone();
  } on PlatformException {
    print('Failed to get the timezone.');
  }
  final String timeZoneName = timezone;
  tz.setLocalLocation(tz.getLocation(timeZoneName));
}

 

 

아래의 코드는 특정일자, 특정 시간에 알림이 울리도록 하는 코드이다.

참고로 flutterLocalNotificationsPlugin.zonedSchedule 함수의 id는 유니크한 숫자 id를 입력해야 여러가지 알림을 설정할 수 있다.

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

Future<void> _ddayScheduleNotification(int id, int afterDays) async {
    await flutterLocalNotificationsPlugin.zonedSchedule(
        id,
        'scheduled title',
        'scheduled body',
        _nextInstance(afterDays), // 알림일자 세팅
        const NotificationDetails(
            android: AndroidNotificationDetails(
                'channel id',
                'channel name',
                'channel description',)),
        androidAllowWhileIdle: true,
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime);
  }

  // 알림일자
  tz.TZDateTime _nextInstance(int afterDays) {
    final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
    // Add days
    final tz.TZDateTime bestBefore = now.add(Duration(days: afterDays));
    // set Hours and minutes
    tz.TZDateTime scheduledDate = tz.TZDateTime(tz.local, bestBefore.year,
        bestBefore.month, bestBefore.day, _alramHours, _alramMinutes);
        
    // 알람시간이 현재보다 이전인 경우 5초 뒤에 알람이 울린다.
    if (scheduledDate.isBefore(now)) {
      scheduledDate =
          tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5));
    }
    return scheduledDate;
  }

 

 

매일 특정 시간에 알림 설정


Time alramTime = new Time(9, 30, 00);
dailyNotification(context, alramTime);


Future<void> dailyNotification(
    BuildContext context, Time alarmTime) async {
  await flutterLocalNotificationsPlugin.zonedSchedule(
      alarmId,
      'scheduled title',
      'scheduled body',
      scheduledDaily(alarmTime),
      const NotificationDetails(
        android: AndroidNotificationDetails(
          'channel id',
          'channel name',
          'channel description',
          priority: Priority.high,
          importance: Importance.high,
        ),
      ),
      androidAllowWhileIdle: true,
      uiLocalNotificationDateInterpretation:
          UILocalNotificationDateInterpretation.absoluteTime,
      matchDateTimeComponents: DateTimeComponents.time);
}

tz.TZDateTime scheduledDaily(Time alarmTime) {
  final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
  tz.TZDateTime scheduledDate = tz.TZDateTime(
      tz.local, now.year, now.month, now.day, alarmTime.hour, alarmTime.minute);
  scheduledDate = scheduledDate.add(const Duration(days: 1));
  return scheduledDate;
}

 

 

모든 알림 취소 함수

  Future<void> cancelAllNotifications() async {
    await flutterLocalNotificationsPlugin.cancelAll();
  }

 

 

알림이 정상적으로 오는 것을 확인 할 수 있다.

'개발 > Flutter' 카테고리의 다른 글

냉장고 관리 앱 - 인더프리지  (0) 2021.05.07
Flutter Android/iOS 앱 이름 현지화  (1) 2021.04.20
Flutter AdMob 광고 달기  (0) 2021.04.13
Flutter Webview  (0) 2021.02.10
[Flutter 어플] 크리스천의 평범한 삶 (크평삶)  (0) 2021.02.10