本指南主要基于有关在 iOS 和 Android 应用程序中创建 URL 方案的旧 博客文章 和论坛文章整合。请注意,Android URL 方案是通过意图筛选器设置的,但为简洁起见,本指南将它们称为 URL 方案。此外,本指南不会介绍应用链接或通过网站 URL 启动应用。
简单来说,URL 方案允许您的应用程序从另一个应用程序中打开。它们通常采用类似于 mycoolappname://MyCustomString
的形式。现代 iOS 版本使您能够在 Safari 中打开 URL 方案。对于 Android,您可能需要使用第三方工具,如 深度链接测试器。请注意,URL 方案应使用小写字母。
对于 iOS,您需要在 CFBundleURLScheme
中定义您的 URL 方案,而对于 Android,需要在应用程序 build.settings
中定义类似于以下示例代码的意图筛选器
。
settings = { orientation = { default = { "portrait" } }, iphone = { plist = { UIApplicationExitsOnSuspend = false, CFBundleURLTypes = { { CFBundleURLSchemes = { "fb1234567890", -- example scheme for facebook "mycoolappscheme", -- example second scheme } } } } }, android = { intentFilters = { { label = "Optional Title Goes Here", actions = { "android.intent.action.VIEW" }, categories = { "android.intent.category.DEFAULT", "android.intent.category.BROWSABLE", }, data = { scheme = "mycoolappscheme" }, }, -- You can add more intent filters here. }, }, }
当您的应用既不在前台运行也不处于暂停状态(即处于完全关闭状态)时,会发生“冷启动”。如果您的应用是使用 URL 方案启动的,则以下是获取用于启动您的应用的 main.lua 的 URL 字符串的方法
local launchArgs = ... local launchURL if launchArgs and launchArgs.url then launchURL = launchArgs.url end print( launchURL ) -- output: mycoolappscheme://MyCustomString
上述示例假定您的应用已将 mycoolappscheme 注册为 URL 方案,并且用户使用以下 URL 字符串启动了该应用:mycoolappscheme://MyCustomString 在上述示例中,如果用户以正常方式(未使用 URL 方案)启动该应用,则 launchURL 的值为 nil。
如果您的应用已打开,但不在前台运行,则它会被视为“暂停”。当您的应用在暂停时使用 URL 方案启动时,您可以使用系统事件监听器来获取用于启动应用的 URL。以下是一个示例
local launchURL local function onSystemEvent( event ) if event.type == "applicationOpen" and event.url then launchURL = event.url print( launchURL ) -- output: mycoolappscheme://MyCustomString end end Runtime:addEventListener( "system", onSystemEvent )
您可以简单地将以上两个示例合并,一切都将很好,但我建议您将代码放入函数中,并且只从两个不同的地方调用该函数。以下是如何实现这一目标的示例
local launchArgs = ... local function printURL( url ) print( url ) -- output: mycoolappscheme://MyCustomString end if launchArgs and launchArgs.url then printURL( launchArgs.url ) end local function onSystemEvent( event ) if event.type == "applicationOpen" and event.url then printURL( event.url ) end end Runtime:addEventListener( "system", onSystemEvent )
要检查是否可以通过 system.openURL() 打开应用 URL 方案,请参见 system.canOpenURL()。