在Flutter中如何通过特定接口打开手机上的外部应用?

在Flutter中如何通过特定接口打开手机上的外部应用?需要配置哪些权限才能实现这个功能?能否详细说明一下Android和iOS平台的不同配置要求?如果遇到权限被拒绝或应用无法打开的情况,应该如何排查和解决?另外,是否有推荐的最佳实践或常见问题汇总可以参考?

3 回复

作为屌丝程序员,推荐使用url_launcher插件实现跳转。首先添加依赖:url_launcher: ^6.0.3

  1. 接口调用: 使用launch方法,如:

    import 'package:url_launcher/url_launcher.dart';
    
    void openUrl() async {
      const url = 'https://www.example.com';
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw '无法打开链接';
      }
    }
    
  2. 权限设置: 在Android上需在AndroidManifest.xml中添加:

    <uses-permission android:name="android.permission.INTERNET"/>
    

    iOS无需额外配置。

  3. 拨打电话或发送短信

    • 打电话:tel:+123456789
    • 发短信:sms:+123456789
  4. 注意事项

    • 检查URL是否合法。
    • 处理异常情况,如网络不可用。
    • Android 10及以上需处理Scoped Storage,但此功能不影响url_launcher

简单实用,祝你早日脱贫!

更多关于在Flutter中如何通过特定接口打开手机上的外部应用?的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


首先确保你的Flutter项目已添加url_launcher插件。在pubspec.yaml中加入:

dependencies:
  url_launcher: ^6.0.9

接着运行flutter pub get

使用时导入库:

import 'package:url_launcher/url_launcher.dart';

调用示例:

void _launchURL() async {
  const url = 'https://www.example.com';
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

权限:Android需在AndroidManifest.xml添加网络权限:

<uses-permission android:name="android.permission.INTERNET"/>

对于拨打电话或发短信,还需如下权限:

<uses-permission android:name="android.permission.CALL_PHONE"/>

iOS需要在Info.plist添加:

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>whatsapp</string>
</array>

注意iOS10+需设置LSApplicationQueriesSchemes以支持自定义URL Scheme查询。确保所有URL符合安全规范,并处理用户可能拒绝授权的情况。

Flutter打开外部应用教程

基本方法

在Flutter中,你可以使用url_launcher包来打开外部应用:

import 'package:url_launcher/url_launcher.dart';

// 打开URL (可以是http/https链接或自定义scheme)
void _launchURL(String url) async {
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}

// 示例用法
_launchURL('https://www.example.com'); // 打开网页
_launchURL('tel:123456789'); // 拨打电话
_launchURL('mailto:example@example.com'); // 发送邮件

常用URI schemes

  1. 电话tel:+123456789
  2. 短信sms:+123456789
  3. 邮件mailto:user@example.com
  4. 地图geo:latitude,longitude
  5. 市场应用market://details?id=com.example.app

Android配置

AndroidManifest.xml中添加查询权限:

<queries>
  <!-- 允许查询和启动浏览器 -->
  <intent>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="https" />
  </intent>
  
  <!-- 其他需要查询的intent -->
</queries>

iOS配置

Info.plist中添加LSApplicationQueriesSchemes(允许的URL schemes):

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>https</string>
  <string>http</string>
  <string>tel</string>
  <string>sms</string>
  <string>mailto</string>
</array>

注意事项

  1. 在iOS上,必须提前声明所有需要检查的URL schemes
  2. 测试时请使用真机,模拟器可能不支持某些功能
  3. 对于Android 11+,必须使用<queries>标签声明要交互的应用
回到顶部