notifications.scheduleNotification()

类型 函数
返回值 用户数据
修订 版本 2024.3703
关键词 notification, notifications, scheduleNotification
另请参阅 notifications.cancelNotification()
notifications.*

概述

计划将来传递本地通知事件。

此函数返回一个引用 ID,可用于取消通知。该 ID 是对象的内存地址(指针),因此无法保存,并且在程序下次运行时将不可用。

注意事项

iOS

在应用程序挂起时安排通知可能会导致应用程序崩溃。

Android

与 iOS 不同,Android 上的本地通知由应用程序而不是操作系统管理。这意味着当应用程序进程终止时,所有计划的通知和状态栏通知都将被清除。但是,按**返回**键退出应用程序窗口不会终止应用程序进程 — 这只会销毁运行项目 Lua 脚本的应用程序窗口,并且它会在销毁之前收到 "applicationExit" 系统事件。因此,应用程序进程将继续在后台运行 — 这是标准的 Android 应用程序行为,允许其通知保持可用状态。如果应用程序进程完全终止,Corona 将在应用程序重新启动时自动恢复所有待处理的通知。

也就是说,调用 os.exit() 将终止应用程序进程并**清除**所有通知。如果您只需要关闭应用程序窗口,请调用 native.requestExit(),它只会退出应用程序窗口并保持应用程序进程处于活动状态,从而保持您的通知处于活动状态。

另请注意,在重新启动 Android 设备后,所有计划的通知和状态栏通知都将被清除。为了恢复所有通知,您必须在 build.settings 文件中设置以下权限,以将您的应用程序设置为在 Android 设备启动后在后台启动

settings =
{
    android =
    {
        usesPermissions =
        {
            "android.permission.RECEIVE_BOOT_COMPLETED",
        },
    },
}

语法

notifications.scheduleNotification( time [, options] )
time (必填)

此参数可以采用以下两种格式之一

  • 一个 数字,表示从此计划调用到传递的秒数。
  • 一个 ,指示传递通知的**协调世界时**(UTC)。此表应包含与以下返回的属性相同的属性os.date( "!*t" )。请注意,一个常见的陷阱是传递 "*t" 而不是 "!*t",这会导致以当前时区而不是 UTC 时间给出时间。
options (可选)

指定要计划的通知的详细信息的表 — 有关详细信息,请参阅下一节。

选项参考

options 表包含要计划的通知的详细信息。

alert (可选)

字符串 如果是字符串,则为要显示给用户的通知消息。如果应用程序当前未运行,系统警报将显示此消息。对于表,您可以传入通知的 title 和/或 body

badge (可选)

数字 计划的通知触发时要在应用程序图标上显示的徽章编号。这将替换上次应用的徽章编号。设置为 0 可省略徽章编号。Android 不支持此选项。

sound (可选)

字符串 system.ResourceDirectory 中要在计划的通知触发时播放的声音文件的名称。仅当应用当前**不在**前台时才会播放此声音。在 iOS 上,可以播放的声音种类有限制(有关更多详细信息,请参阅 Apple 的文档)。

custom (可选)

将随 通知事件一起传递的表。这允许您传递带有通知的自定义信息。

示例

local notifications = require( "plugin.notifications.v2" )

-- Get the app's launch arguments in case it was started when the user tapped on a notification
local launchArgs = ...

-- Set up notification options
local options = {
    alert = "Wake up!",
    badge = 2,
    sound = "alarm.caf",
    custom = { foo = "bar" }
}

-- Schedule a notification to occur 60 seconds from now
local notification1 = notifications.scheduleNotification( 60, options )

-- Schedule a notification using Coordinated Universal Time (UTC)
local utcTime = os.date( "!*t", os.time() + 60 )
local notification2 = notifications.scheduleNotification( utcTime, options )

-- Listen for notifications
local function onNotification( event )
    print( event.name )
    if ( event.custom ) then
        print( event.custom.foo )
    end
end
Runtime:addEventListener( "notification", onNotification )

-- The launch arguments provide a notification event if this app was started when the user tapped on a notification
-- In this case, you must call the notification listener manually
if ( launchArgs and launchArgs.notification ) then
    onNotification( launchArgs.notification )
end