การตั้งเวลาการแจ้งเตือนภายในเครื่อง
ติดตั้ง expo-notifications ขอสิทธิ์ ตั้งเวลาการแจ้งเตือนภายในเครื่องให้แสดงหลังเวลาหน่วง และจัดการการแตะการแจ้งเตือนเพื่อนำทางไปยังหน้าจอที่กำหนด
การตั้งเวลาการแจ้งเตือนภายในเครื่อง เป็นบทเรียน React Native Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน React Native Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What Are Local Notifications?
Local notifications are alerts that your app schedules and delivers entirely on-device, without a server. Unlike push notifications, they do not require an internet connection or a backend service. They are ideal for reminders, daily habit prompts, timer alerts, and in-app alerts that trigger after a specific time or based on a recurring schedule.
Installing expo-notifications
Install expo-notifications using the Expo install command so the SDK-compatible version is selected. In managed Expo projects native linking is automatic. Also add the notification configuration block to app.json to set the Android notification icon and color used by the OS.
npx expo install expo-notifications
// app.json:
{
"expo": {
"notification": {
"icon": "./assets/notification-icon.png",
"color": "#6200ee",
"androidMode": "default"
}
}
}Requesting Notification Permission
On both iOS and Android you must request notification permission before scheduling any notification. iOS requires explicit user approval — the system shows a dialog. Android 13+ also requires runtime permission. Call Notifications.requestPermissionsAsync() and check whether status is 'granted' before proceeding.
import * as Notifications from 'expo-notifications';
async function requestNotificationPermission() {
const { status } = await Notifications.requestPermissionsAsync();
if (status !== 'granted') {
Alert.alert(
'Permission Denied',
'Enable notifications in Settings to receive reminders.'
);
return false;
}
return true;
}Setting a Default Notification Handler
Set a global notification handler with Notifications.setNotificationHandler to control how notifications behave when the app is in the foreground. Without this, notifications delivered while your app is open are silently ignored on iOS. Call it once at the module level (outside any component) so it is always active.
import * as Notifications from 'expo-notifications';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true, // show banner while app is open
shouldPlaySound: true,
shouldSetBadge: false,
}),
});Scheduling a One-Time Notification
Notifications.scheduleNotificationAsync schedules a notification to be delivered at a specific time. The trigger can be a number of seconds from now, a specific Date object, or a repeating calendar trigger. The function returns a unique notification identifier that you can use later to cancel the notification if needed.
async function scheduleReminder() {
const hasPermission = await requestNotificationPermission();
if (!hasPermission) return;
const id = await Notifications.scheduleNotificationAsync({
content: {
title: 'Daily Reminder',
body: 'Time to check your goals for today!',
sound: true,
data: { screen: 'Goals' }, // custom data for handling the tap
},
trigger: {
seconds: 60, // deliver in 60 seconds
},
});
console.log('Notification scheduled with ID:', id);
}Scheduling a Recurring Notification
To schedule a repeating notification — for example a daily 8 AM reminder — use a calendar trigger with a repeats: true flag. Specify the hour, minute, and optionally day-of-week to create any recurring pattern. The OS delivers the notification at the specified time and automatically reschedules it for the next occurrence.
await Notifications.scheduleNotificationAsync({
content: {
title: 'Good morning!',
body: 'Your daily coding practice is waiting.',
},
trigger: {
type: Notifications.SchedulableTriggerInputTypes.CALENDAR,
hour: 8,
minute: 0,
repeats: true, // fires every day at 8:00 AM
},
});Cancelling a Scheduled Notification
Save the notification identifier returned by scheduleNotificationAsync (e.g., in state or AsyncStorage) so you can cancel it later. Call Notifications.cancelScheduledNotificationAsync(id) with the saved ID to cancel a specific notification. Use cancelAllScheduledNotificationsAsync() to cancel all pending notifications at once.
const [notifId, setNotifId] = React.useState<string | null>(null);
async function cancelReminder() {
if (notifId) {
await Notifications.cancelScheduledNotificationAsync(notifId);
setNotifId(null);
console.log('Notification cancelled');
}
}
// Or cancel all at once:
await Notifications.cancelAllScheduledNotificationsAsync();Handling Foreground Notifications
Use Notifications.addNotificationReceivedListener to react when a notification arrives while the app is open. This is useful for updating in-app badges, playing a custom sound, or refreshing a data feed. Always remove the listener in the useEffect cleanup to prevent memory leaks.
useEffect(() => {
const subscription = Notifications.addNotificationReceivedListener(
(notification) => {
console.log('Received:', notification.request.content.title);
const screen = notification.request.content.data?.screen;
if (screen) setBadge(screen);
}
);
return () => subscription.remove();
}, []);Handling Notification Taps
Use Notifications.addNotificationResponseReceivedListener to handle when the user taps a notification banner. This callback fires whether the app was in the foreground, background, or closed. Use the custom data field you attached when scheduling to navigate to the correct screen in your app.
useEffect(() => {
const subscription = Notifications.addNotificationResponseReceivedListener(
(response) => {
const screen = response.notification.request.content.data?.screen;
if (screen && navigationRef.current) {
navigationRef.current.navigate(screen);
}
}
);
return () => subscription.remove();
}, []);Getting All Scheduled Notifications
Call Notifications.getAllScheduledNotificationsAsync() to retrieve a list of all pending scheduled notifications. This is useful for debugging, for showing a 'Reminders' management screen where users can review and delete scheduled notifications, or for preventing duplicate scheduling if the user reopens the settings screen.
async function listScheduledNotifications() {
const scheduled = await Notifications.getAllScheduledNotificationsAsync();
console.log('Pending notifications:', scheduled.length);
scheduled.forEach((notif) => {
console.log(
notif.identifier,
notif.content.title,
JSON.stringify(notif.trigger)
);
});
}Badges and Android Channels
On iOS, set the app badge number with Notifications.setBadgeCountAsync(count). On Android 8+, notifications must be assigned to a notification channel which controls sound, vibration, and importance. Create a channel once on app startup using Notifications.setNotificationChannelAsync and reference its ID in your notification's channelId field.
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('reminders', {
name: 'Reminders',
importance: Notifications.AndroidImportance.HIGH,
vibrationPattern: [0, 250, 250, 250],
sound: 'default',
});
}
// Reference in notification:
await Notifications.scheduleNotificationAsync({
content: { title: 'Reminder', channelId: 'reminders' },
trigger: { seconds: 30 },
});Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: requestPermissionsAsync must be granted before any notification can appear, scheduleNotificationAsync with a trigger delivers one-time or repeating notifications at specified times, and addNotificationResponseReceivedListener handles user taps to navigate to the right screen. Next up we explore handling permissions gracefully.
คำถามที่พบบ่อย
บทเรียน “การตั้งเวลาการแจ้งเตือนภายในเครื่อง” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การตั้งเวลาการแจ้งเตือนภายในเครื่อง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส React Native Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส React Native Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การตั้งเวลาการแจ้งเตือนภายในเครื่อง”
ติดตั้ง expo-notifications ขอสิทธิ์ ตั้งเวลาการแจ้งเตือนภายในเครื่องให้แสดงหลังเวลาหน่วง และจัดการการแตะการแจ้งเตือนเพื่อนำทางไปยังหน้าจอที่กำหนด คุณปฏิบัติ React Native Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน React Native Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน React Native Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การตั้งเวลาการแจ้งเตือนภายในเครื่อง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน React Native Academy นี้ได้ไหม
ได้ บทเรียน React Native Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การเข้าถึงกล้องด้วย expo-camera
- การอ่านตำแหน่ง GPS ด้วย expo-location
- การตั้งเวลาการแจ้งเตือนภายในเครื่อง
- การจัดการสิทธิ์อย่างเหมาะสม