เนื้อหาในตอนต่อไปนี้ เราจะมาดูการใช้งานเกี่ยวกับการแจ้งเตือน
หรือ 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | < 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> เพิ่มส่วนนี้เข้าไป
1 2 | android:showWhenLocked="true" android:turnScreenOn="true" |
ไฟล์ android > app > src > main > AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | < 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> เพิ่มส่วนนี้เข้าไป
1 2 3 4 5 6 7 8 9 | < 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | < 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 | ไฟล์ 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 = final String bigPicturePath = await _downloadAndSaveFile( // ส่วนของการกำหนดการแสดงรุป ถ้าต้องการ 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 = final String bigPicturePath = await _downloadAndSaveFile( 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( 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 = 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 ได้อีกด้วย
หวังว่าเนื้อหานี้จะเป็นแนวทางนำไปปรับใช้งานได้ง่ายและสะดวกมากขึ้น