Flutter平台交互插件intent_launcher的使用

Flutter平台交互插件intent_launcher的使用

intent_launcher 是一个Flutter插件,它提供了一种简单的方式来通过Intents启动Android系统设置和其他活动。该包允许你轻松地打开各种Android系统设置屏幕,并从你的Flutter应用处理活动结果。

这个包受到并基于Expo团队的优秀工作,他们开发了expo-intent-launcher包。

特性

  • 启动Android系统设置屏幕(如Wi-Fi、蓝牙、位置等)
  • 使用自定义参数打开特定的Android活动
  • 处理活动启动结果
  • 支持意图附加项、标志和类别
  • 丰富的预定义活动动作集
  • 类型安全的API与强大的Flutter集成

平台支持

Android iOS MacOS Web Linux Windows

安装

运行以下命令来安装插件:

flutter pub add intent_launcher

使用

基本用法

// 打开位置设置
await startActivityAsync(ActivityAction.locationSourceSettings);

API 参考

startActivityAsync

启动一个Android活动并返回结果。

Future<IntentLauncherResult> startActivityAsync(
  String action, {
  IntentLauncherParams params = const IntentLauncherParams(),
})

IntentLauncherParams

用于启动活动的配置选项。

class IntentLauncherParams {
  final String? type;        // MIME类型
  final String? category;    // 意图类别
  final Map<String, dynamic>? extra;  // 附加键值对
  final String? data;        // URI数据
  final int? flags;          // 意图标志
  final String? packageName; // 目标包名
}

IntentLauncherResult

包含活动启动的结果。

class IntentLauncherResult {
  ResultCode? resultCode;  // 成功、取消或用户首次
  String? data;           // 结果数据URI
  Map<String, dynamic>? extra;  // 结果附加项
}

常见活动动作

该包提供了大量的预定义活动动作,包括但不限于:

  • ActivityAction.settings - 打开系统设置
  • ActivityAction.wifiSettings - 打开Wi-Fi设置
  • ActivityAction.bluetoothSettings - 打开蓝牙设置
  • ActivityAction.airplaneModeSettings - 打开飞行模式设置
  • ActivityAction.securitySettings - 打开安全设置
  • ActivityAction.locationSourceSettings - 打开位置设置
  • ActivityAction.displaySettings - 打开显示设置
  • ActivityAction.dateSettings - 打开日期和时间设置
  • ActivityAction.soundSettings - 打开声音设置
  • ActivityAction.privacySettings - 打开隐私设置
  • 更多…

示例代码

以下是一个完整的示例代码,展示了如何在Flutter应用中使用intent_launcher插件。

import 'package:flutter/material.dart';
import 'package:intent_launcher/intent_launcher.dart';

void main() {
  runApp(const Root());
}

class Root extends StatelessWidget {
  const Root({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Intent Launcher Example'),
        ),
        body: const IntentLauncherTest(),
      ),
    );
  }
}

class IntentLauncherTest extends StatelessWidget {
  const IntentLauncherTest({super.key});

  Future<void> _startActivityAsync({
    required BuildContext context,
    required String action,
    IntentLauncherParams params = const IntentLauncherParams(),
  }) async {
    final result = await startActivityAsync(
      action,
      params: params,
    );

    if (!context.mounted) return;
    debugPrint(result.toString());
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          ElevatedButton(
            onPressed: () {
              _startActivityAsync(
                context: context,
                action: ActivityAction.wirelessSettings,
                params: const IntentLauncherParams(),
              );
            },
            child: const Text('无线设置'),
          ),
          ElevatedButton(
            onPressed: () {
              _startActivityAsync(
                context: context,
                action: ActivityAction.settings,
                params: const IntentLauncherParams(),
              );
            },
            child: const Text('设置'),
          ),
          ElevatedButton(
            onPressed: () {
              _startActivityAsync(
                context: context,
                action: ActivityAction.applicationDetailsSettings,
                params: const IntentLauncherParams(
                  data: 'package:com.android.vending',
                ),
              );
            },
            child: const Text('Play Store 应用详情'),
          ),
          ElevatedButton(
            onPressed: () {
              _startActivityAsync(
                context: context,
                action: ActivityAction.applicationDetailsSettings,
                params: const IntentLauncherParams(
                  data: 'package:package.name.that.doesnt.exist',
                ),
              );
            },
            child: const Text('不存在的包的应用详情'),
          ),
          ElevatedButton(
            onPressed: () {
              _startActivityAsync(
                context: context,
                action: 'android.media.action.IMAGE_CAPTURE',
                params: const IntentLauncherParams(
                  flags: 100,
                ),
              );
            },
            child: const Text('相机'),
          ),
        ],
      ),
    );
  }
}

更多关于Flutter平台交互插件intent_launcher的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter平台交互插件intent_launcher的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用intent_launcher插件进行平台交互的代码案例。intent_launcher插件允许Flutter应用启动系统级别的Intent(在Android上)或者URL Scheme(在iOS上),从而实现与其他应用的交互。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加intent_launcher依赖:

dependencies:
  flutter:
    sdk: flutter
  intent_launcher: ^0.7.0  # 请注意版本号,使用最新版本

然后运行flutter pub get来安装依赖。

2. 配置AndroidManifest.xml(仅Android)

如果你需要调用一些特定的Intent(例如拨打电话、发送短信等),你可能需要在AndroidManifest.xml中声明相应的权限。例如,拨打电话需要<uses-permission android:name="android.permission.CALL_PHONE" />

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yourapp">

    <uses-permission android:name="android.permission.CALL_PHONE" />
    <!-- 其他权限根据需要添加 -->

    <application
        ... >
        ...
    </application>
</manifest>

3. 请求权限(仅Android)

在运行时请求权限(如果适用)。例如,拨打电话前请求CALL_PHONE权限:

import 'package:permission_handler/permission_handler.dart';

Future<void> requestCallPhonePermission() async {
  var status = await Permission.phone.status;
  if (!status.isGranted) {
    var result = await Permission.phone.request();
    if (!result.isGranted) {
      throw Exception('Call phone permission is denied');
    }
  }
}

注意:这里使用了permission_handler插件来处理权限请求。你可能需要在pubspec.yaml中添加这个依赖。

4. 使用intent_launcher插件

以下是一些使用intent_launcher插件的示例代码:

import 'package:flutter/material.dart';
import 'package:intent_launcher/intent_launcher.dart';
import 'package:permission_handler/permission_handler.dart';  // 如果需要请求权限

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Intent Launcher Demo'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                onPressed: () async {
                  try {
                    // 请求权限(如果需要)
                    await requestCallPhonePermission();

                    // 拨打电话
                    await IntentLauncher()
                        .canLaunchUrl('tel:+1234567890')
                        .then((bool result) {
                      if (result) {
                        IntentLauncher().launchUrl('tel:+1234567890');
                      } else {
                        throw 'Could not launch URL';
                      }
                    });
                  } catch (e) {
                    print(e);
                  }
                },
                child: Text('拨打电话'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  try {
                    // 发送短信
                    await IntentLauncher()
                        .canLaunchUrl('sms:+1234567890')
                        .then((bool result) {
                      if (result) {
                        IntentLauncher().launchUrl('sms:+1234567890?body=Hello%20World');
                      } else {
                        throw 'Could not launch URL';
                      }
                    });
                  } catch (e) {
                    print(e);
                  }
                },
                child: Text('发送短信'),
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () async {
                  try {
                    // 打开网页
                    await IntentLauncher()
                        .canLaunchUrl('https://www.example.com')
                        .then((bool result) {
                      if (result) {
                        IntentLauncher().launchUrl('https://www.example.com');
                      } else {
                        throw 'Could not launch URL';
                      }
                    });
                  } catch (e) {
                    print(e);
                  }
                },
                child: Text('打开网页'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

总结

上述代码展示了如何在Flutter应用中使用intent_launcher插件进行平台交互,包括拨打电话、发送短信和打开网页等操作。请根据实际情况调整代码,并注意处理权限请求和异常捕获。

回到顶部