首页 > 解决方案 > 如何用颤振的 URL_launcher 包发送短信?

问题描述

你好我搜索一个简单的例子(Android和iOS)用这个包发送短信

https://pub.dartlang.org/packages/url_launcher

在插件页面中,我只看到如何使用电话号码打开短信本机应用程序,但没有额外消息

sms:<phone number>, e.g. sms:5550101234 Send an SMS message to <phone 
number> using the default messaging app

标签: fluttersms

解决方案


在 Android 上,sms:支持完整的 URI,您可以发送带有类似正文 ( RFC5724 ) 的消息:

 _textMe() async {
    // Android
    const uri = 'sms:+39 348 060 888?body=hello%20there';
    if (await canLaunch(uri)) {
      await launch(uri);
    } else {
      // iOS
      const uri = 'sms:0039-222-060-888?body=hello%20there';
      if (await canLaunch(uri)) {
        await launch(uri);
      } else {
        throw 'Could not launch $uri';
      }
    }
  }

在此处输入图像描述

iOS上,官方文档说您只能使用 The 的数字字段URI

相反,正如Konstantine指出的那样,如果您使用非标准URI,而不是使用?您开始查询字符串,&它仍然可以正常工作。这似乎是一个未记录的功能。

短信方案用于启动消息应用程序。此类型 URL 的格式为“sms:”,其中是一个可选参数,用于指定 SMS 消息的目标电话号码。此参数可以包含数字 0 到 9 以及加号 (+)、连字符 (-) 和句点 (.) 字符。URL 字符串不得包含任何消息文本或其他信息

PS。要检查平台,您可以使用dart.io 库Platform

 _textMe() async {
    if (Platform.isAndroid) {
      const uri = 'sms:+39 348 060 888?body=hello%20there';
      await launch(uri);
    } else if (Platform.isIOS) {
      // iOS
      const uri = 'sms:0039-222-060-888&body=hello%20there';
      await launch(uri);
    }
  }

推荐阅读