一、安装配置
-
安装
app_links$ flutter pub add app_links -
安卓配置:
android/app/src/main/AndroidManifest.xml在
application标签中添加URLScheme配置<application android:label="base_project" ...> <activity android:name=".MainActivity" ...> <!-- 其他配置 --> ... <!-- 配置 URL Scheme --> <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"/> <!-- <data android:scheme="myapp" android:host="pay"/> --> </intent-filter> </activity> ... </application> -
iOS配置:ios/Runner/Info.plist<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>myapp</string> </array> </dict> </array> -
使用:
main.dart,也可以其他地方。import 'dart:async'; import 'package:app_links/app_links.dart'; ... ... ... class _MyAppState extends State<MyApp> { /// AppLinks late AppLinks _appLinks; StreamSubscription<Uri>? _linkSubscription; @override void initState() { super.initState(); // 初始化 DeepLinks 监听 initDeepLinks(); } @override void dispose() { // 取消 DeepLinks 监听 _linkSubscription?.cancel(); super.dispose(); } /// 初始化 DeepLinks,例如现有 URL Scheme 配置路径:myapp://pay?id=123 void initDeepLinks() async { try { _appLinks = AppLinks(); // 获取启动时的链接 _appLinks.getInitialLink().then((link) { // 如果有值,处理启动时接收到的链接 if (link != null) { print("Initial link: $link"); } }); // 监听链接变化,应用在运行时接收到的链接,或每当应用通过深度链接被唤醒时,都会触发该方法 _linkSubscription = _appLinks.uriLinkStream.listen((uri) { print("Received deep link: $uri"); }); } catch (e) { print('Error: $e'); } } }
二、测试
-
iOS哪个设备或者模拟器安装了这个
app,打开设置设备或模拟器的Safari浏览器,输入myapp://则可以打开对应的应用,并获得该链接,还可以myapp://pay?id=123等等。 -
安卓
手机已连接电脑或模拟器已启动,可以通过
$ adb devices看到设备。执行下面命令:$ adb shell am start -a android.intent.action.VIEW -d "myapp://" # 或 $ adb shell am start -a android.intent.action.VIEW -d "myapp://pay?id=123" # 连接路径或参数都可以自己指定也可以指定设备运行:
List of devices attached emulator-5554 device 1234567890abcdef device # 上面是 $ adb devices 输出的设备列表 # 对设备 emulator-5554 运行指令 $ adb -s emulator-5554 shell am start -a android.intent.action.VIEW -d "myapp://your/custom/path"