flutter app_links 配置 URLScheme 并进行模拟器测试

一、安装配置

  • 安装 app_links

    $ flutter pub add app_links
    
  • 安卓配置:android/app/src/main/AndroidManifest.xml

    application 标签中添加 URLScheme 配置

    <application
        android:label="base_project"
        ...>
        <activity
            android:name=".MainActivity"
            ...>
            
            ...
            
            <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"/>
                
            intent-filter>
        activity>
        ...
    application>
    
  • iOS 配置:ios/Runner/Info.plist

    CFBundleURLTypes
    
            
                    CFBundleURLSchemes
                    
                            myapp
                    
            
    
    
  • 使用:main.dart,也可以其他地方。

    import 'dart:async';
    import 'package:app_links/app_links.dart';
    
    ...
    ...
    ...
    
    class _MyAppState extends State<MyApp> {
    
      /// AppLinks
      late AppLinks _appLinks;
      StreamSubscription<Uri>? _linkSubscription;
    
      
    
      void initState() {
        super.initState();
        // 初始化 DeepLinks 监听
        initDeepLinks();
      }
    
      
      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"
    
    

你可能感兴趣的:(Flutter,flutter)