การใช้งาน Flutter Local Notifications จัดการวิธ๊แจ้งเตือนใน Flutter

บทความใหม่ สัปดาห์ที่แล้ว โดย Ninenik Narkdee
flutter local notifications timezone

คำสั่ง การ กำหนด รูปแบบ ตัวอย่าง เทคนิค ลูกเล่น การประยุกต์ การใช้งาน เกี่ยวกับ flutter_local_notifications timezone

ดูแล้ว 181 ครั้ง


เนื้อหาในตอนต่อไปนี้ เราจะมาดูการใช้งานเกี่ยวกับการแจ้งเตือน
หรือ Notification ใน flutter โดยใช้ flutter_local_notification
ซึ่งโดยความสามารถแล้ว เราสามารถใช้งานได้ทั้งแบบ Local Notifications
(การแจ้งเตือนในเครื่อง) และ Push Notifications (การแจ้งเตือนแบบ push)
สำหรับการใช้งานแบบ Push นั้นจะต้องใช้งานร่วมกับ Firebase Cloud Messaging
(FCM) เพื่อรับการแจ้งเตือนจาก backend service แม้แอปจะไม่ได้เปิด ในที่นี้เราจะ
ไม่กล่าวถึง ซึ่งจริงๆ ถ้าเราเข้าใจการใช้งาน Local Notifications ก็สามารถประยุกต์
ใช้งานแบบ Push ได้ เพราะแบบ push เป็นการเรียกให้ตัว local notifications ทำ
งานอีกทีนั้นเอง
 

ติดตั้ง package ที่จำเป็นเพิ่มเติม ตามรายการด้านล่าง

    แพ็กเก็จที่จำเป็นต้องติดตั้งเพิ่มเติม สำหรับการทำงานมีดังนี้
 
  path_provider: ^2.1.4
  permission_handler: ^11.3.1
  http: ^1.2.2 
  flutter_local_notifications: ^17.2.3
  timezone: ^0.9.4
  flutter_timezone: ^3.0.1
 
    จริงๆ แพ็กเก็จพื้นฐานเราอาจจะใช้แค่ flutter_local_notifications ก็ได้ สำหรับการแจ้งเตือน
ธรรมดาพื้นฐานทั่วไป แต่ถ้าต้องมีการใช้งานที่หลากหลายเป็นแนวทาง ในที่นี้จะนำตัวที่เกี่ยวข้องมาร่วม
ด้วย ดังนี้
 
  path_provider: ใช้จัดการ path ไฟล์กรณีเราต้องการแสดงรูปในแจ้งเตือน
  permission_handler: การขอสิทธิ์เปิดการแจ้งเตือน และการอ่านเขียนไฟล์
  http: สำหรับดึงรูปบน server มาแสดงในแจ้งเตือน
  flutter_local_notifications: สำหรับการแจ้งเตือน
  timezone: จัดการโซนเวลา
  flutter_timezone: จัดการโซนเวลาของเครื่อง เช่นเวลาที่ไทย
 
การกำหนดการขอสิทธิ์เข้าถึงการใช้งานข้อมูล
ไฟล์ android > app > src > main > AndroidManifest.xml
 
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
    <!-- เกี่ยวกับเขียนอ่านไฟล์ เพิ่ม 2 ส่วนนี้ -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:maxSdkVersion="28"/>
    <!-- For Android 13+ -->
    <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
    <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
    <uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />

   <!-- เกี่ยวกับการแจ้งเตือน เพิ่ม 3 ส่วนนี้ -->
   <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.USE_EXACT_ALARM" />
    <!-- For apps with targetSDK 31 (Android 12) and newer -->
    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/> 

    <application ....
....
</manifest>
 
ส่วนของ <activity> เพิ่มส่วนนี้เข้าไป
 
android:showWhenLocked="true"
android:turnScreenOn="true"
 
ไฟล์ android > app > src > main > AndroidManifest.xml
 
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
   .......
    <application ....
<activity
            android:name=".MainActivity"
            android:exported="true"
        ..........
        ......
            android:hardwareAccelerated="true"
            android:showWhenLocked="true"
            android:turnScreenOn="true"
            android:windowSoftInputMode="adjustResize">

    </application>
....
</manifest>
 
และภายใน <application> เพิ่มส่วนนี้เข้าไป
 
        <receiver android:exported="false" android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
        <receiver android:exported="false" android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
            <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" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>
 
ไฟล์ android > app > src > main > AndroidManifest.xml
 
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
   .......
    <application ....
<activity
            android:name=".MainActivity"
            android:exported="true"
        ..........
        ......
            android:hardwareAccelerated="true"
            android:showWhenLocked="true"
            android:turnScreenOn="true"
            android:windowSoftInputMode="adjustResize">
      ..........
        ......
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />

        <receiver android:exported="false" android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
        <receiver android:exported="false" android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
            <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" />
                <action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
            </intent-filter>
        </receiver>
    </application>
....
</manifest>
 
แก้ไขส่วนของไฟล์ build.gradle
ไฟล์  android > app > build.gradle
 
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 {
  // Import the Firebase BoM
 // implementation platform('com.google.firebase:firebase-bom:33.1.2')

     // เพิ่มส่วนนี้เข้าไป ****************
    coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.2.2'
     // เพิ่มส่วนนี้เข้าไป ****************

  // TODO: Add the dependencies for Firebase products you want to use
  // When using the BoM, don't specify versions in Firebase dependencies
  // https://firebase.google.com/docs/android/setup#available-libraries
}
 
    สำหรับการตั้งค่าเพิ่มเติมให้ดูที่หน้า plugin flutter_local_notifications
 
 
 

การใช้งาน Flutter local notifications จัดการการแจ้งเตือน

    เราสามารถใช้งานแจ้งเตือนนี้ในรูปแบบต่างๆ ได้ เช่น แสดงสถานะการดาวน์โหลดไฟล์ การแจ้ง
เตือนหลังจากดำเนินการอย่างหนึ่งอย่างใด แล้วได้ผลลัพธ์ การตั้งกำหนดเวลาแจ้งเตือน การแจ้งเตือน
แบบกำหนดทำงานแบบซ้ำๆ ทุกนาที ชั่วโมง เหล่านี้เป็นต้น
    กรณีเราใช้การแจ้งเตือนแบบแสดงแถบสถานะความก้าวหน้าการดำเนินงาน เช่น การอัปโหลด 
การดาวน์โหลดไฟล์ การประมวลผล การแจ้งเตือนก็จะมีล้กษณะเป็น animation การเคลื่อนไหว
ของแถบสถานะด้วย
    กรณีเราใช้การแจ้งเตือนแบบแสดงรูปภาพ เช่น ภาพที่เกิดจากการ generate ที่เก็บไว้ในเครื่อง
หรือภาพจาก server ที่ต้องการใช้งาน(เราต้องดาวน์โหลดมาที่เครื่องก่อนแสดง ไม่สามารถแสดงรูป
จาก server โดยตรงได้)
    เมื่อเรากดไปที่การแจ้งเตือน เราสามารถกำหนด คำสั่งการทำงานได้ โดยทั่วไปเมื่อกดที่แถบแจ้งเตือน
ก็จะเปิดแอปของเราขึ้นมา ในกรณีที่ปิดแอปนั้นไว้อยู่ (ถ้าแอปถูกปิดไปแล้ว)
    นอกจากนั้นเรายังสามารถกำหนดปุ่ม หรือ action เฉพาะให้กับการแจ้งเตือนนั้นๆ ได้ เช่น ปุ่มยกเลิก
หรือปุ่มทำงานอื่นๆ ที่ต้องการ เมื่อกดปุ่มที่กำหนด เราก็กำหนดการทำงานของปุ่มนั้นได้
    การกำหนดการทำงานแบบทำซ้ำทุกนาที ชั่วโมง วัน หรีอสัปดาห์ โดยค่าน้อยสุดกำหนดที่หน่วยนาที
อย่างไรก็ตาม เวลาที่แจ้งเตือนอาจจะไม่ตรงกับเวลาที่กำหนด เช่น อาจจะช้าหรือเร็วบ้างขึ้นกับการทำงาน
โดยรวมของอุปกรณ์ ซึ่งมีเรื่องของการจัดการกับพลังงานเข้ามาเกี่ยวข้อง  อย่างไรก็ดี หากต้องการ
กำหนดการทำงานที่ตรงกับเวลาที่กำหนด ก็สามารถใช้รูปแบบ zonedSchedule มาใช้งานได้ ซึ่งเป็น
ลักษณะการกำหนดเวลาเป้าหมายให้กับการแจ้งเตือน และต้องใช้ timezone มาช่วย
    ทุกๆ การแจ้งเตือนจะมีไอดีที่เป็นตัวเลขเฉพาะ และไม่ซ้ำกัน เราสามารถยกเลิกการแจ้งเตือนด้วยการ
อ้างอิงจากค้า id นี้ หรือจะยกเลิกการแจ้งเตือนทั้งหมดทีเดียวก็ได้โดยไม่ต้องระบบ id
    ทุกๆ การแจ้งเตือนจะมี channel id ดังนั้นหากมีรูปแบบการแสดงที่ต่างกัน ต้องกำหนดค่า id ของ
แต่ละ channel ให้ต่างกันด้วย
    ตัวอย่างด้านล่างเป็นโค้ดการตั้งค่าทั้งหมดที่ใช้สำหรับการแจ้งเตือน จะมีปุ่มสำหรับเรียกทดสอบการ
ทำงานของแต่ละฟังก์ชั่น โดยถ้าต้องการทดสอบฟังก์ชั่นไหน ก็เปิดใช้งานแล้วรันทดสอบ หรือจะนำไป
ประยุกต์สร้างหลายๆ ปุ่มก็ได้ แต่ในที่นี้จะปิดเป็นคอมเม้นท์ไว้ ต้องการค่อยเปิดใช้งาน
 

ไฟล์  notification.dart

ไฟล์  notification.dart

import 'dart:io';
import 'dart:typed_data';
import 'dart:async'; // สำหรับ Timer

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

// กำหนดต่าไอดี ในที่นี้ใช้สำหรับทดสอบ 
int id = 0;

class Notifications extends StatefulWidget {
  static const routeName = '/notification';

  const Notifications({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _NotificationsState();
  }
}

class _NotificationsState extends State<Notifications> {

  // กำหนดตัวแปรสำหรับใช้งานการแจ้งเตือนทั้งหมด
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

  Timer? _timer; // ใช้เพื่อควบคุมการทำงานซ้ำ

  @override
  void initState() {
    super.initState();
    // ส่วนของการกำหนด timezone เริ่มต้น
    _configureLocalTimeZone();
    // เริ่มต้นการตั้งค่าการแจ้งเตือน
    _initializeNotifications();
      // กำหนดการร้องขอสิทธิืเข้าถึงการเขียนและอ่านไฟล์ storage
    requestPermissions();
  }

  // ขอ permission สำหรับจัดการ storage
  void requestPermissions() async {
    await Permission.storage.request();
  }  

  // ส่วนกำหนด timezone ทำให้เวลาที่ใช้งานตรงกับเวลาเครื่อง
  Future<void> _configureLocalTimeZone() async {
    tz.initializeTimeZones();
    final String? timeZoneName = await FlutterTimezone.getLocalTimezone();
    print("${timeZoneName}"); // Asia/Bangkok
    tz.setLocalLocation(tz.getLocation(timeZoneName!));
  }

  // ส่วนของการกำหนดค่าเริ่มต้นการแจ้งเตือน ต้องมีสเมอ
  Future<void> _initializeNotifications() async {
    // รูปไอคอนที่แสดงในแอป
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');


    // กำหนดค่าเริ่มต้นต่างๆ ของการตั้งค่าไว้ใช้งาน
    const InitializationSettings initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid, // ใช้รูปไอคอนแอป
    );

    // เรียกใช้งานการตั้งค่าเริ่มต้นต่างๆ 
     await flutterLocalNotificationsPlugin.initialize(
      initializationSettings, // นำค่าตั้งค่าเริ่มต้นมาใช้งาน
      // บบรทัดนี้ใช้สำหรับ รอคำสั่งเมื่อกดที่แถบแจ้งเตือน
      onDidReceiveNotificationResponse: (NotificationResponse response) async {
        // ตรวจสอบว่ากดที่แถบแจ้งเตือน หรือกดที่เมนู action เพิ่มเติม
        switch (response.notificationResponseType) {
          case NotificationResponseType.selectedNotification: // ถ้ากดที่แถบแจ้งเตือน
            // กำหนดคำสังส่วนนี้ตามต้องการ
            // ทดสอบแจ้งข้อมูลที่ส่งมาด้วยใน payload ถ้ามี เพื่อเอามาใช้งาน หรือทำคำสั่ง
            print('Notification clicked with payload: ${response.payload}');
            // ในที่นี้ทดลอง เมื่อกดแล้วให้ปิดการแจ้งเตือนทั้งหมด ถ้ามีตั้งค่าไว้ ไม่ใช้ให้เอาออก
           await flutterLocalNotificationsPlugin.cancelAll();
            print('All Notification stopped');     

            // กรณีมีการใช้งานเกี่ยวกับ เวลา สมมติต้องการยกเลิกการทำซ้ำแบบ ตารางเวลา 
            if (_timer != null && _timer!.isActive) {
              _timer!.cancel(); // ยกเลิก Timer
              _timer = null;
              print('Timer cancelled');
            }

            break;
          case NotificationResponseType.selectedNotificationAction: // กรณีกดที่ปุ่มเมนู action
            print("selectedNotificationAction");
            if (response.actionId == 'cancel') { // ถ้าปุ่มที่กด เรากำหนดค่าไอดีไว้เป็น cancel
                print("selectedNotificationAction clicked");
              // หรือหยุดการแจ้งเตือนทั้งหมด
          //  await flutterLocalNotificationsPlugin.cancelAll();

              // หยุดการแจ้งเตือนด้วย ID ที่กำหนด
              await flutterLocalNotificationsPlugin.cancel(0); // 0 คือ ID ของการแจ้งเตือน
              print('Notification stopped');                
            }
            break;
        }        
      },
    ); 

    // เช็คและขอสิทธิ์การแจ้งเตือน
    await _requestNotificationPermission();
  }



  // ฟังก์ชันสำหรับขอสิทธิ์การแจ้งเตือน
  Future<void> _requestNotificationPermission() async {
    var status = await Permission.notification.status;

    if (status.isDenied || status.isRestricted) {
      // ขอสิทธิ์ใหม่ ถ้าไม่ได้รับอนุญาต
      status = await Permission.notification.request();
      if (status.isGranted) {
        print('Notification permission granted');
      } else {
        print('Notification permission denied');
        _showPermissionDeniedDialog(); // แสดง Dialog เมื่อสิทธิ์ถูกปฏิเสธ
      }
    } else if (status.isPermanentlyDenied) {
      // ถ้าโดนปิดถาวร ให้เปิดการตั้งค่า
      _showPermissionDeniedDialog(); // แสดง Dialog เมื่อสิทธิ์ถูกปฏิเสธแบบถาวร
    }
  }

  // ฟังก์ชันแสดง Dialog เพื่อแจ้งเตือนผู้ใช้
  void _showPermissionDeniedDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Notification Permission'),
          content: const Text(
              'การแจ้งเตือนถูกปิดใช้งาน กรุณาไปที่การตั้งค่าเพื่อเปิดสิทธิ์การแจ้งเตือน'),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: const Text('Cancel'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                openAppSettings(); // เปิดหน้าตั้งค่าของแอป
              },
              child: const Text('ไปที่การตั้งค่า'),
            ),
          ],
        );
      },
    );
  }

  // ฟังก์ชั่นสำหรับการโหลดรูปจาก server มาบันทึกที่เครื่องชั่วคราว เพื่อนำรูปไปแสดง
  // โดยตัวฟังก์ชั่นจะไปดึงรูปแล้วเขียนเป็นไฟล์ไว้จากนั้นก็ส่งออกเป็น path ของไฟล์ไปใช้งาน
  Future<String> _downloadAndSaveFile(String url, String fileName) async {
    // สามารถเก็บไว้ที่ cache ได้
    final Directory directory = await getTemporaryDirectory();
    // final Directory directory = await getApplicationDocumentsDirectory();
    final String filePath = '${directory.path}/$fileName';
    final http.Response response = await http.get(Uri.parse(url));
    final File file = File(filePath);
    await file.writeAsBytes(response.bodyBytes);
    return filePath;
  }

  // ส่วนของฟังก์ชั่นแจ้งเตือนทั้งหมด

  // การแจ้งเตือนทั่วไป
  Future<void> _showNotification() async {
    // ส่วนการกำหนดรูปไอคอน และรูปภาพที่แสดงในแจ้งเตือน
    // เรียกใช้ฟังก์ชั่นสร้างรูปโดยโหลดจาก server มาบันทึกในเครื่อง แล้วเรียรกใช้
    // path ไฟล์ที่ได้
    final String largeIconPath =
        await _downloadAndSaveFile('https://dummyimage.com/48x48', 'largeIcon');
    final String bigPicturePath = await _downloadAndSaveFile(
        'https://dummyimage.com/400x800', 'bigPicture');

    // ส่วนของการกำหนดการแสดงรุป ถ้าต้องการ
    final BigPictureStyleInformation bigPictureStyleInformation =
        BigPictureStyleInformation(
            FilePathAndroidBitmap(bigPicturePath), // รูปใหญ่
            largeIcon: FilePathAndroidBitmap(largeIconPath), // รูปไอคอน จากไฟล์
            // largeIcon: DrawableResourceAndroidBitmap('splash'), // ใช้รูปจาก res/drawable
            contentTitle: 'overridden <b>big</b> content title', // ข้อความ (แถบขยาย)
            htmlFormatContentTitle: true, // รองรับ html
            summaryText: 'summary <i>text</i>', // ข้อความสรุป  (แถบขยาย)
            htmlFormatSummaryText: true // รองรับ html
        );


    // ส่วนของการกำหนดรูปแบบเฉพาะของ channel แต่ละ platform
    AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(
        /* ตัวอย่าง
        'order_updates',  // channelId: ควรเป็น string ที่ระบุถึงประเภทการแจ้งเตือน
        'Order Updates',  // channelName: คำอธิบายเกี่ยวกับการแจ้งเตือน        
        */  
        'your_channel_id_1', // ชื่อไอดีของ channel 
        'your_channel_name', // คำอธิบายเพื่อสื่อถึง 
        importance: Importance.max, // กำหนดความสำคัญ
        priority: Priority.high, // ความพิเศษ การมาก่อน
        showWhen: true, // บอกเวลากานแจ้งเตือน เช่น ขณะนี้ หรือ 1 นาทีผ่านมา เป็นต้น
        ongoing: false, // ทำให้แจ้งเตือนยังคงแสดงอยู่จนกว่าจะกดปุ่มหยุด ปัดทิ้งได้
        largeIcon: FilePathAndroidBitmap(largeIconPath), // รูปไอคอน
        actions: const <AndroidNotificationAction>[ // กำหนดเมนูเพิ่มเติมให้กับปุ่ม
          AndroidNotificationAction(
            'cancel', // ID ของ action เอาไว้ใช้เวลาเมื่อกดแล้วเทียบค่า เพื่อทำงาน
            'ยกเลิกแจ้งเตือน', // ข้อความที่จะแสดงบนปุ่ม
            showsUserInterface: true, // ต้องกำหนดเพือ่ให้ปุ่มทำงาน
            cancelNotification: true, // ให้ปุ่มนี้สามารถหยุดการแจ้งเตือนได้ หรือยกเลิกการแจ้งเตือนนี้ได้
          ),
        ],     
        styleInformation: bigPictureStyleInformation, // ใช้ BigPictureStyle
        // กรณีใ้ช้รูปแบบข้อความที่ขนาดใหญ่ขึ้น
  /*      styleInformation: BigTextStyleInformation(
          'ยกเลิกแจ้งเตือน',
          contentTitle: 'ยกเลิกแจ้งเตือน 2',
        ),      */           
    );

    // นำค่าที่กำหนดมาใช้งาน ในที่นี้กำหนดเฉพาะใน android 
    NotificationDetails platformChannelSpecifics =
        NotificationDetails(
          android: androidPlatformChannelSpecifics // ค่าจากด้านบน
        );

    // เรียกคำสั่งการแจ้งเตือนพื้นฐานด้วยคำสั่ง show()   
    await flutterLocalNotificationsPlugin.show(
      0, // ID ของการแจ้งเตือน
      'Hello', // หัวข้อของการแจ้งเตือน (แถบเล็ก)
      'This is a notification', // เนื้อหาของการแจ้งเตือน (แถบเล็ก)
      platformChannelSpecifics, // รูปแบบที่ตั้งค่านำมาใช้งาน
    );
  }

  // แจ้งเตือนที่เกิดซ้ำตามช่วงเวลาที่กำหนด
  Future<void> scheduleRepeatingNotifications() async {
    final String largeIconPath =
        await _downloadAndSaveFile('https://dummyimage.com/48x48', 'largeIcon');
    final String bigPicturePath = await _downloadAndSaveFile(
        'https://dummyimage.com/400x800', 'bigPicture');
    final BigPictureStyleInformation bigPictureStyleInformation =
        BigPictureStyleInformation(FilePathAndroidBitmap(bigPicturePath),
            largeIcon: FilePathAndroidBitmap(largeIconPath),
            contentTitle: 'overridden <b>big</b> content title',
            htmlFormatContentTitle: true,
            summaryText: 'summary <i>text</i>',
            htmlFormatSummaryText: true);

    AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(
      'repeating_channel_id_2',
      'repeating_channel_name',
      importance: Importance.max,
      priority: Priority.high,
      ongoing: true, // ทำให้แจ้งเตือนยังคงแสดงอยู่จนกว่าจะกดปุ่มหยุด
      actions: <AndroidNotificationAction>[
        // สร้างปุ่ม ข้อความ สามารถกำหนดได้หลายปุ่ม
        AndroidNotificationAction(
          'cancel', // ID ของ action
          'ยกเลิกแจ้งเตือน', // ข้อความที่จะแสดงบนปุ่ม
          showsUserInterface: true, // ต้องกำหนดเพื่อให้ปุ่มนี้ทำงาน
          cancelNotification: true, // ปุ่มนี้สามารถหยุดการแจ้งเตือนได้
        ),
      ],   
      styleInformation: bigPictureStyleInformation,
  /*     styleInformation: BigTextStyleInformation(
        'ยกเลิกแจ้งเตือน',
        contentTitle: 'ยกเลิกแจ้งเตือน 2', 
      ),         */
    );

    NotificationDetails platformChannelSpecifics =
        NotificationDetails(android: androidPlatformChannelSpecifics);

    await flutterLocalNotificationsPlugin.periodicallyShow(
      0, // ID ของการแจ้งเตือน
      'Repeating Notification', // หัวข้อ
      'This is a repeating notification', // เนื้อหา
      RepeatInterval.everyMinute, // ระยะเวลา (เช่น ทุกๆ นาที)
      platformChannelSpecifics, // รูปแบบที่ตั้งค่านำมาใช้งาน
    );
  }

  // การแจ้งเตือนจำลองแถบสถานะความก้าวหน้า ในตัวอย่าง ใช้วิธีวนลูป แล้วหน่วงเวลา
  // หากนำไปใช้งานจริง จะนำไปใช้ในลูปของ progress ในตัวอย่างใช้ for loop เพื่อจำลอง
  // การทำงานเมื่อสถานะ progress ค่อยๆ เพิ่ม
  Future<void> _showProgressNotification() async {
    id++;
    final int progressId = id;
    const int maxProgress = 5; // จำลองค่าสูงสุด
    for (int i = 0; i <= maxProgress; i++) {
      await Future<void>.delayed(const Duration(seconds: 1), () async {
        final AndroidNotificationDetails androidNotificationDetails =
            AndroidNotificationDetails(
              'progress_channel_3', 
              'progress channel',
                channelDescription: 'progress channel description',
                channelShowBadge: false,
                importance: Importance.max,
                priority: Priority.high,
                onlyAlertOnce: true, // แสดงแค่ครั้งเดียว
                showProgress: true, // แสดงแถบก้าวหน้า
                maxProgress: maxProgress, // ค่าสูงสุด หรือค่าเต็ม เช่น 100
                progress: i // สถานะค่ายๆ เพิ่มตามค่า progress
            );
        final NotificationDetails notificationDetails =
            NotificationDetails(android: androidNotificationDetails);
        await flutterLocalNotificationsPlugin.show(
            progressId,
            'progress notification title',
            'progress notification body',
            notificationDetails,
            payload: 'item x');
      });
    }
  }

  // แสดงแบบรูปแบบ media เช่นกำลังเล่นเพลง
  Future<void> _showNotificationMediaStyle() async {
    final String largeIconPath = await _downloadAndSaveFile(
        'https://dummyimage.com/128x128/00FF00/000000', 'largeIcon');
    final AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
      'media_channel_id_4',
      'media channel name',
      channelDescription: 'media channel description',
      largeIcon: FilePathAndroidBitmap(largeIconPath),
      // styleInformation: const MediaStyleInformation(),      
      importance: Importance.max,
      priority: Priority.high,      
      actions: <AndroidNotificationAction>[
        // สร้างปุ่ม ข้อความ สามารถกำหนดได้หลายปุ่ม
        const AndroidNotificationAction(
          'play', // ID ของ action
          'Play', // ข้อความที่จะแสดงบนปุ่ม
          showsUserInterface: true, // ต้องกำหนดเพื่อให้ปุ่มนี้ทำงาน
          cancelNotification: true, // ปุ่มนี้สามารถหยุดการแจ้งเตือนได้
        ),   
        const AndroidNotificationAction(
          'pause', // ID ของ action
          'Pause', // ข้อความที่จะแสดงบนปุ่ม
          showsUserInterface: true, // ต้องกำหนดเพื่อให้ปุ่มนี้ทำงาน
          cancelNotification: true, // ปุ่มนี้สามารถหยุดการแจ้งเตือนได้
        ), 
        const AndroidNotificationAction(
          'next', // ID ของ action
          'Next', // ข้อความที่จะแสดงบนปุ่ม
          showsUserInterface: true, // ต้องกำหนดเพื่อให้ปุ่มนี้ทำงาน
          cancelNotification: true, // ปุ่มนี้สามารถหยุดการแจ้งเตือนได้
        ),      
      ],      
    );

    // Notification details for the platform
    final NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);

    // Show the notification
    await flutterLocalNotificationsPlugin.show(
      id++, // Notification ID
      'Now Playing', // Title
      'Song Title - Artist Name', // Body
      notificationDetails, // Notification details
    );

  }

  // แสดงการแจ้งเตือนพร้อมเสียงและการสั่น
  Future<void> _showNotificationWithAudioAttributeAlarm() async {
    const AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(
      'your_alarm_channel_id_5',
      'your alarm channel name',
      channelDescription: 'your alarm channel description',
      importance: Importance.max,
      priority: Priority.high,
      // เสียงสำหรับการเตือน (alarm)
      audioAttributesUsage: AudioAttributesUsage.alarm,
    );
    const NotificationDetails platformChannelSpecifics =
        NotificationDetails(android: androidPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.show(
      0,
      'notification sound controlled by alarm volume',
      'alarm notification sound body',
      platformChannelSpecifics,
    );
  }  

  // แจ้งเตือนแบบรองรับแสดงตัวเลขที่ไอคอน ว่ามีแจ้งเตือนจำนวนเท่าไหร่
  // ตัวเลขไม่ได้แสดงตรงแถบแจ้งเตือน แต่แสดงที่ไอคอนแอป 
  Future<void> _showNotificationWithNumber() async {
    const AndroidNotificationDetails androidPlatformChannelSpecifics =
        AndroidNotificationDetails(
          'your_channel_id_6',
          'your channel name',
          channelDescription: 'your channel description',
          channelShowBadge: true, // แสดง ฺ Badge ในไอคอนแอป
          importance: Importance.max,
          priority: Priority.high,
          number: 1 // กำหนดจำนวนการแจ้งเตือน แสดงที่ไอคอนแอป
        );
    const NotificationDetails platformChannelSpecifics =
        NotificationDetails(android: androidPlatformChannelSpecifics);
        // ถ้าต้องการหน่วงเวลา 5 วินาที เช่น ไปหน้าแอป เพื่อดูผลลัพธ์ ให้เอาคอมมเ้นนี้ออก
  //     await Future<void>.delayed(const Duration(seconds: 5), () async {

    await flutterLocalNotificationsPlugin.show(
        0, 'icon badge title', 
        'icon badge body', 
        platformChannelSpecifics,
        payload: 'item x' // ค่าที่ส่งไปใน payload เมื่อกดที่แถบแจ้งเตือน
    );

  //     });

  }  

  // แสดงแจ้งเตือนพร้อมแสดงการจับเวลา
  Future<void> _showNotificationWithChronometer() async {
    print("${tz.TZDateTime.now(tz.local)}");
    print("${DateTime.now()}");
    final AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
      'your_channel_id_7',
      'your channel name',
      channelDescription: 'your channel description',
      importance: Importance.max,
      priority: Priority.high,
      usesChronometer: true, // แสดงตัวจับเวลา
      // กำหนดนับถอยหลังนับจากตอนนี้ถึงอีก 2 นาทีข้างหน้า (+120 วินาที)
      when: DateTime.now().millisecondsSinceEpoch + 120 * 1000,
      chronometerCountDown: true, // กำหนดนับถอยหลัง
      // ถ้าต้องการนับเวลา จากปัจจจุบันไปเริ่มที่ 00 ใช้เป็น
     /* when: DateTime.now().millisecondsSinceEpoch,
      chronometerCountDown: false,*/
    );
    final NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
        id++, 'plain title', 'plain body', 
        notificationDetails,
        payload: 'item x');
  }  

  // แสดงแจ้งเตือนพร้อมข้อความย่อยกำหนดเอง แทนตรงเวลา
  Future<void> _showNotificationWithCustomSubText() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
      'your_channel_id_8',
      'your channel name',
      channelDescription: 'your channel description',
      importance: Importance.max,
      priority: Priority.high,
      showWhen: false, // ไม่แสดงเวลา
      subText: 'custom subtext', // แสดงข้อความส่วนนี้แทนตรงเวลา
    );
    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
        id++, 'plain title', 'plain body', notificationDetails,
        payload: 'item x');
  }  

  // แสดงแจ้งเตือนแบบกำหนดเวลาเอง ในตัวอย่่างใช้เป็น 2 นาทีที่แล้ว
  Future<void> _showNotificationWithCustomTimestamp() async {
    final AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
      'your_channel_id_9',
      'your channel name',
      channelDescription: 'your channel description',
      importance: Importance.max,
      priority: Priority.high,
      // กำหนดเวลาที่มีการแจ้งย้อนหลังเป็น 2 นาทีที่แล้ว (120 วินาที) 
      when: DateTime.now().millisecondsSinceEpoch - 120 * 1000,
    );
    final NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
        id++, 'plain title', 'plain body', 
        notificationDetails,
        payload: 'item x');
  }  

  // แสดงแจ้งเตือนโดยไม่โชว์เวลา
  Future<void> _showNotificationWithoutTimestamp() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
          'your_channel_id_10', 
          'your channel name',
            channelDescription: 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
            showWhen: false // ไม่แสดงเวลาแจ้งเตือน
        );
    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
        id++, 'plain title', 'plain body', 
        notificationDetails,
        payload: 'item x');
  }

  // แสดงแจ้งเตือนทั้งหมดทั้งแบบหน้าจอเปิดหรือปิดอยู่
  // กำหนดความเป็นส่วนตัวและการแสดงผลของการแจ้งเตือน
  Future<void> _showPublicNotification() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
          'your_channel_id_11', 
          'your channel name',
            channelDescription: 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
            ticker: 'ticker', // ข้อความแสดงเตือน ที่ทดสอบดูส่วนนี้ไม่แสดง
            visibility: NotificationVisibility.public,
/*             private: การแจ้งเตือนจะถูกแสดงให้เห็นเฉพาะเมื่อหน้าจอถูกปลดล็อก.
            public: การแจ้งเตือนจะแสดงข้อมูลทั้งหมดเมื่อหน้าจอเปิดอยู่หรือปิดอยู่ (ในกรณีของการแจ้งเตือน).
            secret: จะไม่แสดงเนื้อหาในการแจ้งเตือนเลย จนกว่าจะปลดล็อก.    */         
        );
    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);

        // ถ้าต้องการหน่วงเวลา 5 วินาที เช่น ปิดหน้าจอ เพื่อดูผลลัพธ์ ให้เอาคอมมเ้นนี้ออก
      //  await Future<void>.delayed(const Duration(seconds: 5), () async {

    await flutterLocalNotificationsPlugin.show(
        id++,
        'public notification title',
        'public notification body',
        notificationDetails,
        payload: 'item x');

    //    });
  }  

  // แสดงแจ้งเตือนแบบใช้เพื่ออัปเดท ค่าต่างๆ ของ channel เดิม
  // สมมติเช่น channel id นี้ต้องการกำหนด priority เป็น low หรือ high เป็นต้น
  Future<void> _showNotificationUpdateChannelDescription() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
          'your_channel_id_12', 
          'your channel name',
            channelDescription: 'your updated channel description',
            importance: Importance.max,
            priority: Priority.high,
            channelAction: AndroidNotificationChannelAction.update
        );
    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
        id++,
        'updated notification channel',
        'check settings to see updated channel description',
        notificationDetails,
        payload: 'item x');
  }  

  // แสดงแจ้งเตือนแบบมีแถบสถานะ กำลังดำเนินการอย่างใดอย่างหนึ่งอยู่
  // เราสามารถใช้แสดงการทำงานที่ยังไมแล้วเสร็จ และถ้าเสร็จสิ้นก็ปิดการแจ้งเตือนนี้ไปได้
  Future<void> _showIndeterminateProgressNotification() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
            'indeterminate_progress_channel_13', 
            'indeterminate progress channel',
            channelDescription: 'indeterminate progress channel description',
            channelShowBadge: false, // ไม่แสดงตัวเลขจำนวนแจ้งเตือน
            importance: Importance.max,
            priority: Priority.high,
            onlyAlertOnce: true, // แสดงเสียง การสั่น หรือการแจ้งเตือนแค่ครั้งเดียวคร้้งแรก
            showProgress: true, // แสดงตัวแถบสถานะวิ่ง
            indeterminate: true // แสดงสถานะดำเนินการอยู่ แถบสถานะวิ่งไมหยุด
          );
    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
        id++,
        'indeterminate progress notification title',
        'indeterminate progress notification body',
        notificationDetails,
        payload: 'item x');
  }  

  // แสดงแจ้งเตือนโดยไม่แสดงตัวเลขจำนวนการแจ้งเตือนที่ยังไม่เปิดในไอคอนแอป
  Future<void> _showNotificationWithNoBadge() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
          'no_badge_channel_id_14',
           'no badge name',
            channelDescription: 'no badge description',
            channelShowBadge: false, // ไม่แสดงตัวเลขจำนวนแจ้งเตือน
            importance: Importance.max,
            priority: Priority.high,
            onlyAlertOnce: true // แสดงเสียง การสั่น หรือการแจ้งเตือนแค่ครั้งเดียวคร้้งแรก
          );
    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
        id++, 'no badge title', 'no badge body', 
        notificationDetails,
        payload: 'item x');
  }

  // แสดงแจ้งเตือนแบบทำซ้ำทุกๆ นาที ชั่วโมง หรือเวลาที่กำหนด
  // โดยใช้คำสั่ง periodicallyShowWithDuration และกำหนดช่วงเวลาทำซ้ำ
  Future<void> _repeatPeriodicallyWithDurationNotification() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
            'repeating_channel_id_15', 
            'repeating channel name',
            channelDescription: 'repeating description');
    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.periodicallyShowWithDuration(
      id++,
      'repeating period title',
      'repeating period body',
      const Duration(minutes: 1), // กำหนดแจ้งเตือนทุกๆ 1 นาที
      notificationDetails,
      androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
    );
  }

  // แสดงแจ้งเตือนแบบทำซ้ำทุกๆ นาที ชั่วโมง หรือเวลาที่กำหนด
  // โดยใช้คำสั่ง periodicallyShow และกำหนดเเวลาทำซ้ำด้วย 
  Future<void> _repeatNotification() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
            'repeating_channel_id_16',
             'repeating channel name',
            channelDescription: 'repeating description');
    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.periodicallyShow(
      id++,
      'repeating title',
      'repeating body',
      RepeatInterval.everyMinute, // กำหนดเวลาทำซ้ำ
      notificationDetails,
      androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
    );
  }  

  // แสดงการแจ้งเตอนแบบค้างไว้ตลอดปิดไม่ได้
  Future<void> _showOngoingNotification() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
          'your_channel_id_17', 
          'your channel name',
            channelDescription: 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
            ongoing: true, // ให้แสดงค้างตลอดปัดออกไม่ได้
            autoCancel: false, // แม้กดก็จะถูกลบออก เพราะไม่ให้ยกเลิกอัตโนมัติ เว้นแต่เราไปตั้งค่าเมื่อกดแถบแจ้งเตือน
          );
    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
        id++,
        'ongoing notification title',
        'ongoing notification body',
        notificationDetails);
  }

  // ฟังก์ชั่นสำหรับยกเลิกการแจ้งเตือนทั้งหมด
  Future<void> _cancelAllNotifications() async {
    await flutterLocalNotificationsPlugin.cancelAll();
  }  

  // ฟังก์ชั่สำหรับตรวจสอบการรองรับการแสดงแจ้งเตือนแบบเต็มหน้าจอหรือไม่
  Future<void> _requestFullScreenIntentPermission() async {
    final bool permissionGranted = await flutterLocalNotificationsPlugin
            .resolvePlatformSpecificImplementation<
                AndroidFlutterLocalNotificationsPlugin>()
            ?.requestFullScreenIntentPermission() ??
        false;
    await showDialog<void>(
        context: context,
        builder: (BuildContext context) => AlertDialog(
              content: Text(
                  'Full screen intent permission granted: $permissionGranted'),
              actions: <Widget>[
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: const Text('OK'),
                ),
              ],
            ));
  } 

  // แดดงแจ้งเตือนแบบไม่แสดงส่วนของเนื้อหา
  Future<void> _showNotificationWithNoBody() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
          'your_channel_id_18', 
          'your channel name',
            channelDescription: 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
            ticker: 'ticker');
    const NotificationDetails notificationDetails = NotificationDetails(
      android: androidNotificationDetails,
    );
    await flutterLocalNotificationsPlugin.show(
        id++, 'plain title', null, notificationDetails,
        payload: 'item x');
  }

  // แดดงแจ้งเตือนแบบไม่แสดงส่วนของหัวข้อการแจ้งเตือน
  Future<void> _showNotificationWithNoTitle() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
          'your_channel_id_19', 
          'your channel name',
            channelDescription: 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
            ticker: 'ticker');
    const NotificationDetails notificationDetails = NotificationDetails(
      android: androidNotificationDetails,
    );
    await flutterLocalNotificationsPlugin
        .show(id++, null, 'plain body', notificationDetails, payload: 'item x');
  }  

  // แสดงแจ้งเตือนแบบใช้เสียงที่กำหนดเอง ต้องมีไฟล์เสียงในตำแหน่ง res > raw
  // android > app > src > main > res > raw > sound_notification.wav
  Future<void> _showNotificationCustomSound() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
      'your_other_channel_id_20',
      'your other channel name',
      channelDescription: 'your other channel description',
      // กำหนดเสียงเตือนเอง
      sound: RawResourceAndroidNotificationSound('sound_notification'),
      playSound: true,
      // sound:  const UriAndroidNotificationSound("assets/tunes/pop.mp3"),
    );
    final NotificationDetails notificationDetails = NotificationDetails(
      android: androidNotificationDetails,
    );
    await flutterLocalNotificationsPlugin.show(
      id++,
      'custom sound notification title',
      'custom sound notification body',
      notificationDetails,
    );
  }  

  // แสดงแจ้งเตือนแบบกำหนดจังหวะการสั่นเอง เท่าที่ทดสอบ การสั่งไม่แสดง
  Future<void> _showNotificationCustomVibrationIconLed() async {
    final String largeIconPath =
        await _downloadAndSaveFile('https://dummyimage.com/48x48', 'largeIcon');

    final Int64List vibrationPattern = Int64List(4);
    vibrationPattern[0] = 0;     // เริ่มสั่นทันที (0 มิลลิวินาที)
    vibrationPattern[1] = 1000;  // สั่นเป็นเวลา 1000 มิลลิวินาที (1 วินาที)
    vibrationPattern[2] = 5000;  // รอ 5000 มิลลิวินาที (5 วินาที) ก่อนสั่นอีกครั้ง
    vibrationPattern[3] = 2000;  // สั่นอีกครั้งเป็นเวลา 2000 มิลลิวินาที (2 วินาที)

    final AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
            'other_custom_channel_id_21', 
            'other custom channel name',
            channelDescription: 'other custom channel description',
            // icon: 'secondary_icon',
            // largeIcon: const DrawableResourceAndroidBitmap('sample_large_icon'),
            largeIcon: FilePathAndroidBitmap(largeIconPath),
            vibrationPattern: vibrationPattern,
            enableVibration: true,
            enableLights: true,
            color: const Color.fromARGB(255, 255, 0, 0),
            ledColor: const Color.fromARGB(255, 255, 0, 0),
            ledOnMs: 1000,
            ledOffMs: 500);

    final NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
        id++,
        'title of notification with custom vibration pattern, LED and icon',
        'body of notification with custom vibration pattern, LED and icon',
        notificationDetails);
  }  

  // แสดงแจ้งเตือนแบบไม่มีเสียง
  Future<void> _showNotificationWithNoSound() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
          'silent_channel_id_22', 
          'silent channel name',
            channelDescription: 'silent channel description',
            playSound: false, // ปิดการแสดงเสียง
            styleInformation: DefaultStyleInformation(true, true));
    const NotificationDetails notificationDetails = NotificationDetails(
        android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
        id++, '<b>silent</b> title', '<b>silent</b> body', 
        notificationDetails);
  }  

  // แสดงการแจ้งเตือนแบบเงียบ ไม่มีเสียง แสง หรือการสั่น
  Future<void> _showNotificationSilently() async {
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
          'your_channel_id_23', 
          'your channel name',
            channelDescription: 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
            ticker: 'ticker',
            silent: true // แสดงแบบเงียบ
          );
    const NotificationDetails notificationDetails = NotificationDetails(
        android: androidNotificationDetails);
    await flutterLocalNotificationsPlugin.show(
        id++, 'silent title', 'silent body', 
        notificationDetails);
  }  

  // แสดงแจ้งเตือนแบบตั้งเวลามีความมั่นยำ กำหนดได้ในหน่วย วินาที
  // ตัวอย่างกำหนดให้แสดงในอีก 30 วินาทีข้างหน้า
  Future<void> _zonedScheduleNotification() async { 
   const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
            'your_channel_id_24',
            'your channel name',
            channelDescription: 'your channel description',
            importance: Importance.max,
            priority: Priority.high,
          );

    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);    
    print("${tz.TZDateTime.now(tz.local)}");
    await flutterLocalNotificationsPlugin.zonedSchedule(
        0,
        'scheduled title',
        'scheduled body',
        // กำหนดให้แสดงในอีก 30 วินาทีข้างหน้า นับจากเวลาี่เริ่มแจ้งเตือน
        tz.TZDateTime.now(tz.local).add(const Duration(seconds: 30)),
        notificationDetails,
        androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime);
  }  



  // แสดงการแจ้งเตือนพร้อมเสียงและการสั่นใช้รูปแบบจากนาฬิกาปลุก
  Future<void> _zonedScheduleAlarmClockNotification() async {
   const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
            'alarm_clock_channel_scheduled_25',
            'Alarm Clock Channel scheduled',
            channelDescription: 'Alarm Clock Notification scheduled',
            importance: Importance.max,
            priority: Priority.high,
            // เสียงสำหรับการเตือน (alarm)
            audioAttributesUsage: AudioAttributesUsage.alarm,
          );

    const NotificationDetails notificationDetails =
        NotificationDetails(android: androidNotificationDetails);

    await flutterLocalNotificationsPlugin.zonedSchedule(
        123,
        'scheduled alarm clock title',
        'scheduled alarm clock body',
        // กำหนดให้แจ้งเตือนในอีก 5 วินาที หลังจากเรียกใช้งาน
        tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
        notificationDetails,
        androidScheduleMode: AndroidScheduleMode.alarmClock,
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime);
  }  

  // แสดงการแจ้งเตือนแบบประยุกต์ โดยใช้การตั้งเวลา รวมกับการวนลูปทำซ้ำในทุก เวลาที่กำหนด
  Future<void> _scheduleFiveMinuteNotification() async {
    final location = tz.local; // ใช้โซนเวลาปัจจุบันของเครื่อง

    print("${tz.TZDateTime.now(tz.local)}");
    for (int i = 0; i < 4; i++) { // ตั้งค่าทุกๆ 20 วินาที (3 ครั้ง = 1 นาที)
      final scheduledTime = tz.TZDateTime.now(location).add(Duration(seconds: 20 * i));
      await flutterLocalNotificationsPlugin.zonedSchedule(
        i, // ID ของการแจ้งเตือน (ต้องไม่ซ้ำ)
        'Reminder',
        'This is a notification that occurs every 20 seconds',
        scheduledTime,
        const NotificationDetails(
          android: AndroidNotificationDetails(
            'your_channel_name_26',
            'your_channel_description',
          ),
        ),
        androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
        uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
        matchDateTimeComponents: DateTimeComponents.time, // ใช้เพื่อจับเวลาเฉพาะทุกๆ เวลาที่กำหนด
      );
    }

    // ตั้งค่าให้เรียกฟังก์ชันนี้อีกครั้งหลังจาก 60 นาที
    _timer = Timer(const Duration(minutes: 1), _scheduleFiveMinuteNotification);    
    // เรียกฟังก์ชันตัวเองหลังจากครบ 1 ชั่วโมง
    // Future.delayed(Duration(minutes: 1), _scheduleFiveMinuteNotification);    
  }  

  @override
  void dispose() {
    // ยกเลิก Timer ก่อนทำลาย widget
    if (_timer != null && _timer!.isActive) {
      _timer!.cancel();
      print('Timer cancelled');
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Notification'),
      ),
      body: Center(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('Notification Screen'),
          ElevatedButton(
            // แจ้งเตือนประยุกต์แบบตั้งเวลาให้ทำซ้ำ
            // onPressed: _scheduleFiveMinuteNotification,
            // แจ้งเตือนแบบตั้งเวลามีความแม่นยำ กำหนดได้ในหน่วย วินาที
            // พร้อมเสียงและการสั่นใช้รูปแบบจากนาฬิกาปลุก
            // onPressed: _zonedScheduleAlarmClockNotification,
            // แจ้งเตือนแบบตั้งเวลามีความแม่นยำ กำหนดได้ในหน่วย วินาที
            // onPressed: _zonedScheduleNotification,
            // แจ้งเตือนแบบเงียบ ไม่มีเสียง แสง หรือการสั่น
            // onPressed: _showNotificationSilently,
            // แจ้งเตือนแบบไม่มีเสียง
            // onPressed: _showNotificationWithNoSound,
            // แจ้งเตือนแบบกำหนดจังหวะการสั่นเอง เท่าที่ทดสอบ การสั่งไม่แสดง
            // onPressed: _showNotificationCustomVibrationIconLed,
            // แจ้งเตือนแบบใช้เสียงที่กำหนดเอง ต้องมีไฟล์เสียงในตำแหน่ง res > raw
            // onPressed: _showNotificationCustomSound,
            // แจ้งเตือนแบบไม่แสดงส่วนของหัวข้อการแจ้งเตือน
            // onPressed: _showNotificationWithNoTitle,
            // แจ้งเตือนแบบไม่แสดงส่วนของรายละเอียดการแจ้งเตือน
            // onPressed: _showNotificationWithNoBody,
            // เรียกฟังก์ชั่สำหรับตรวจสอบการรองรับการแสดงแจ้งเตือนแบบเต็มหน้าจอหรือไม่
            // onPressed: _requestFullScreenIntentPermission,
            // แจ้งเตือนแบบค้างตลอดเว้นแต่ มีคำส่ังให้ยกเลิกการแจ้งเตือน
            // onPressed: _showOngoingNotification,
            // แจ้งเตือนแบบทำซ้ำทุกๆ นาที ชั่วโมง หรือเวลาที่กำหนด
            // onPressed: _repeatNotification,
            // แจ้งเตือนแบบทำซ้ำทุกๆ นาที ชั่วโมง หรือเวลาที่กำหนด
            // onPressed: _repeatPeriodicallyWithDurationNotification,
            // แจ้งเตือนโดยไม่แสดงตัวเลขจำนวนการแจ้งเตือนที่ยังไม่เปิดในไอคอนแอป
            // onPressed: _showNotificationWithNoBadge,
            // แจ้งเตือนแบบมีแถบสถานะ กำลังดำเนินการอย่างใดอย่างหนึ่งอยู่
            // onPressed: _showIndeterminateProgressNotification,
            // แจ้งเตือนแบบใช้เพื่ออัปเดท ค่าต่างๆ ของ channel เดิม
            // onPressed: _showNotificationUpdateChannelDescription,
            // แจ้งเตือนทั้งหมดทั้งแบบหน้าจอเปิดหรือปิดอยู่
            // onPressed: _showPublicNotification,
            // แจ้งเตือนโดยไม่โชว์เวลา
            // onPressed: _showNotificationWithoutTimestamp,
            // แจ้งเตือนแบบกำหนดเวลาเอง ในตัวอย่่างใช้เป็น 2 นาทีที่แล้ว
            // onPressed: _showNotificationWithCustomTimestamp,
            // แจ้งเตือนพร้อมข้อความย่อยกำหนดเอง แทนตรงเวลา
            // onPressed: _showNotificationWithCustomSubText,
            // แจ้งเตือนพร้อมแสดงการจับเวลา
            // onPressed: _showNotificationWithChronometer,
            // แจ้งเตือนแบบแสดงเลขที่ไอคอนแอป ไม่ใช่ในแถบแจ้งเตือน
            onPressed: _showNotificationWithNumber,
            // แจ้งเตือนพร้อมเสียง และการสั่น จากระบบ alarm หรือเตือนการปลุก
            // onPressed: _showNotificationWithAudioAttributeAlarm,
            // แจ้งเตือนแบบเล่นไฟล์เสียงหรือวิดีโอ
            // onPressed: _showNotificationMediaStyle,
            // แจ้งเตือนแบบมีแถบสถานะ ตัวอย่างจำลองการโหลดข้อมูล
            // onPressed: _showProgressNotification, 
            // แจ้งเตือนที่เกิดซ้ำตามช่วงเวลาที่กำหนด
            // onPressed: scheduleRepeatingNotifications,
            // แจ้งเตือนทั่วไป
            // onPressed: _showNotification,             
            child: const Text('Other Notification'),
          ),
          ElevatedButton(
            onPressed: scheduleRepeatingNotifications, 
            // onPressed: scheduleRepeatingNotifications,
            child: const Text('Show Repeat Notification'),
          ),          
          ElevatedButton(
            onPressed: _showNotification, 
            child: const Text('Show Notification'),
          ),          
        ],
      )),
    );
  }
}
 
คำอธิบายแสดงในโค้ด ดูตัวอย่างผลลัพ์ธต่างๆ
 



 
แนวทางสำหรับการใช้งาน flutter_local_notification ทั้งหมดก็จะประมาณนี้ อาจจะยุ่งยากบ้าง
ในเรื่องของการตั้งค่าต่างๆ ในที่นี้เรานำเสนอเฉพาะ android การตั้งค่าอื่นๆ สามารถดูได้ที่หน้า
หลักของแพ็กเก็จ 
    เราสามารถนำการแจ้งเตือนนี้มาประยุกต์ใช้งานต่างๆ เช่นการกำหนดให้แจ้งเตือนโดยที่เราตั้งเวลา
ไว้ได้ เพราะรองรับทั้งแบบขณะใช้งานอยู่และแบบ background service หรือปิดแอปไปแล้วก็สามารถ
แจ้งเตือนขึ้นมาได้ หรือแม้แต่หน้าจอล็อกและดับไปแล้ว ก็สามารถปลุกให้แจ้งเตือนขึ้นมาแสดงได้ นอก
จากนั้น เราสามารถนำไปประยุกต์ใช้งานกับ push notification ได้อีกด้วย 
    หวังว่าเนื้อหานี้จะเป็นแนวทางนำไปปรับใช้งานได้ง่ายและสะดวกมากขึ้น


กด Like หรือ Share เป็นกำลังใจ ให้มีบทความใหม่ๆ เรื่อยๆ น่ะครับ



อ่านต่อที่บทความ



ทบทวนบทความที่แล้ว









เนื้อหาที่เกี่ยวข้อง






เนื้อหาพิเศษ เฉพาะสำหรับสมาชิก

กรุณาล็อกอิน เพื่ออ่านเนื้อหาบทความ

ยังไม่เป็นสมาชิก

สมาชิกล็อกอิน



( หรือ เข้าใช้งานผ่าน Social Login )




URL สำหรับอ้างอิง





คำแนะนำ และการใช้งาน

สมาชิก กรุณา ล็อกอินเข้าระบบ เพื่อตั้งคำถามใหม่ หรือ ตอบคำถาม สมาชิกใหม่ สมัครสมาชิกได้ที่ สมัครสมาชิก


  • ถาม-ตอบ กรุณา ล็อกอินเข้าระบบ
  • เปลี่ยน


    ( หรือ เข้าใช้งานผ่าน Social Login )







เว็บไซต์ของเราให้บริการเนื้อหาบทความสำหรับนักพัฒนา โดยพึ่งพารายได้เล็กน้อยจากการแสดงโฆษณา โปรดสนับสนุนเว็บไซต์ของเราด้วยการปิดการใช้งานตัวปิดกั้นโฆษณา (Disable Ads Blocker) ขอบคุณครับ