一、原理
操作系统都提供了一种**"协议分发机制"**:
-
系统维护一个协议 → 应用的映射表。
-
当用户输入或点击某个 URI(如
myapp://doSomething
),系统会查询该表:- 如果找到对应的 APP → 唤醒并传递参数。
- 如果未找到 → 报错或交给浏览器/其他兜底程序。
📌 本质:协议注册 = 告诉系统"这个协议归我处理" 。
这样 APP 就能通过特定链接被调用,并且拿到参数做相应操作。
二、典型示例
1. Windows 自定义协议
注册方式:写入注册表。
python
[HKEY_CLASSES_ROOT\myapp]
@="URL:MyApp Protocol"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\myapp\shell\open\command]
@=""C:\Program Files\MyApp\myapp.exe" "%1""
原理:
myapp://open?id=123
→ Windows 调用myapp.exe "myapp://open?id=123"
。
2. macOS URL Scheme
配置 Info.plist:
xml
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>myapp</string>
</array>
</dict>
</array>
原理:
- Safari 输入
myapp://page
→ 系统分发给对应的 APP,传入 URL。
3. Linux x-scheme-handler
创建 .desktop
文件:
ini
[Desktop Entry]
Name=MyApp
Exec=/usr/bin/myapp %u
Type=Application
MimeType=x-scheme-handler/myapp;
注册命令:
arduino
xdg-mime default myapp.desktop x-scheme-handler/myapp
原理:
- 用户点击
myapp://foo
→ 系统执行/usr/bin/myapp myapp://foo
。
4. iOS 自定义协议
配置 Info.plist:
xml
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>myapp</string>
</array>
</dict>
</array>
应用接收回调:
swift
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
print("调用: (url.absoluteString)")
return true
}
原理:
- 输入
myapp://scan
→ 系统拉起 APP,并传递 URL 给AppDelegate
。
5. Android Intent Filter
在 Manifest 中声明:
ini
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="myapp" android:host="open"/>
</intent-filter>
代码接收:
kotlin
val data: Uri? = intent?.data
println("调用: ${data.toString()}")
原理:
- 点击
myapp://open/page
→ 系统启动对应 Activity,并把 URL 传入。
三、总结
-
共同点:所有平台都允许 APP 注册协议 → 当触发该协议时,系统唤醒 APP 并传入参数。
-
不同点:
- Windows/Linux → 修改系统配置(注册表 / .desktop)。
- macOS/iOS/Android → 在 APP 的配置文件里声明 URL Scheme。
📌 一句话总结 :
协议注册就是系统级的"路由表",APP 只要登记,就能通过专属链接被调用。
本文部分内容借助 AI 辅助生成,并由作者整理审核。