Front-End/Flutter

[Flutter] 주기적인 알림 띄우기

Voyage_dev 2023. 10. 28. 17:47

앱에서 주기적으로 알림을 주면 앱의 월간 활성 사용자를 늘릴 수 있다.

  • notifications.show() 말고
  • notifications.zonedSchedule()로 주기를 적용해 보자
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

특정 시간에 알림 띄우는 법

// notification.dart

showNotification2() async {

  tz.initializeTimeZones();

  var androidDetails = const AndroidNotificationDetails(
    '유니크한 알림 ID',
    '알림종류 설명',
    priority: Priority.high,
    importance: Importance.max,
    color: Color.fromARGB(255, 255, 0, 0),
  );
  var iosDetails = const IOSNotificationDetails(
    presentAlert: true,
    presentBadge: true,
    presentSound: true,
  );

  notifications.zonedSchedule(
      2,
      '제목2',
      '내용2',
      tz.TZDateTime.now(tz.local).add(Duration(seconds: 5)),
      NotificationDetails(android: androidDetails, iOS: iosDetails),
      androidAllowWhileIdle: true,
      uiLocalNotificationDateInterpretation:
      UILocalNotificationDateInterpretation.absoluteTime
  );
}
  • 저번이랑 똑같지만 notifications.zonedSchedule() 쓰면 알림 띄워주는데 시간을 입력할 수 있다. 즉, 입력한 시간에 알림을 띄워주는 기능이다
  • 타임존에 따른 현재 시간은 tz.TZDateTime.now(tz.local) 이렇게 출력
  • uiLocalNotificationDateInterpretation: 은 iOS 10 미만 기기들 호환을 위한 기능
  • showNotification2() 함수를 원하는 곳에서 실행하면 5초 후에 알림이 뜬다
  • 앱이 꺼져 있어도 알림은 온다
  • seconds: 파라미터 대신 hours, minutes, days 이런거 넣을 수 있다.

주기적으로 알림 띄우는 법

notifications.periodicallyShow(
    3,
    '제목3',
    '내용3',
    RepeatInterval.daily,
    NotificationDetails(android: androidDetails, iOS: iosDetails),
    androidAllowWhileIdle: true
);
  • 매일 알림을 줄려면 notifications.zonedSchedule() 부분을
    • RepeatInterval.daily 부분을 맘대로 바꾸면 됩니다. weekly, hourly 도 있다
    • daily로 설정해놓으면 이 코드가 실행되는 시점 부터 정확히 24시간 후에 알림이 뜬다

예정된 알림 취소하는 법

await notifications.cancel(0);

// 0 자리엔 제목이랑 같이 있었던 알림 번호를 적으면 된다

await notifications.cancelAll();

// 모든 예정된 알림이 삭제

매일 7시 알림은 혹은 특정 시간

makeDate(hour, min, sec){
  var now = tz.TZDateTime.now(tz.local);
  var when = tz.TZDateTime(tz.local, now.year, now.month, now.day, hour, min, sec);
  if (when.isBefore(now)) {
    return when.add(Duration(days: 1));
  } else {
    return when;
  }
}
  • 이런 함수를 만들어서 시간을 입력하면 tz.TZDateTime()으로 만들어주는 함수이다
  • makeDate(8,30,0) 이러면 오늘 8시 30분이라는 날짜로 만들어 준다
notifications.zonedSchedule(
      2,
      '제목2',
      '내용2',
      makeDate(8,30,0),
      NotificationDetails(android: androidDetails, iOS: iosDetails),
      androidAllowWhileIdle: true,
      uiLocalNotificationDateInterpretation:
      UILocalNotificationDateInterpretation.absoluteTime,
      matchDateTimeComponents: DateTimeComponents.time
);
  • zonedSchedule 안에 시간자리에 그 함수를 집어넣으면 된다
  • makeDate(8,30,0) 이랬으니까 오늘 8시 30분으로 날짜가 그 자리에 남을 것인데
    • matchDateTimeComponents: DateTimeComponents.time 이런 파라미터가 있으면 같은 시간 매일 알림.
    • .time 대신 .dayOfWeekAndTime 이런 파라미터가 있으면 같은 요일, 시간 매주 알림.
    • .time 대신 .dayOfMonthAndTime 이런 파라미터가 있으면 같은 날짜, 시간 매달 알림
    • .time 대신 .dateAndTime 이런 파라미터가 있으면 같은 날짜, 시간 매년 알림

서버가 보내는 Push 알림은

  • 서버가 앱으로 직접 알림을 보내고 그러지 않는다
  • Firebase Cloud Messaging 서비스 도움을 받아서 푸시알림을 보낸다

코딩애플

  • 서버가 Firebase Cloud Message으로 메세지 → 알림좀
  • 그러면 그 친구가 님들 폰으로 알림메세지를 전송해준다.
  • 그럼 백그라운드에서 항상 실행되고 있던 폰의 Google Play라는 앱이 그걸 수신해서 알림을 띄우는 구조로 동작
  • 그래서 서버 -> FCM 통신하는 법을 알아야하고
  • FCM에서 플러터앱으로 알림수신하는 법도 알면 끝.