You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI向Flutter通过Intent传值:如何提取传递的文本内容?

解决方案:从MAUI向Flutter通过Intent传递文本并提取内容

一、MAUI端代码修正

你当前的MAUI代码中重复设置了Intent的Action,Intent.ActionSend会被后续的"RECEIVE_INTENT_EXAMPLE_ACTION"覆盖,虽目前能唤起应用,但建议只保留自定义Action以避免潜在问题:

public static async Task SendTextToFlutter()
{
    try
    {
        Intent sendIntent = new Intent();
        // 移除重复的Intent.ActionSend,仅保留自定义Action
        sendIntent.SetAction("RECEIVE_INTENT_EXAMPLE_ACTION");
        sendIntent.PutExtra(Intent.ExtraText, "text from MAUI");
        MainActivity.StartActivity(sendIntent);
    }
    catch (Exception ex) { };
}

二、Flutter端提取Intent携带的文本

使用receive_intent包时,需要处理冷启动唤起和后台唤起两种场景,同时从Intent的extras中提取传递的文本:

1. 完整代码实现

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

class YourFlutterPage extends StatefulWidget {
  const YourFlutterPage({super.key});

  @override
  State<YourFlutterPage> createState() => _YourFlutterPageState();
}

class _YourFlutterPageState extends State<YourFlutterPage> {
  String _receivedText = "暂无收到文本";

  @override
  void initState() {
    super.initState();
    _initReceiveIntent();
    _listenToIntentStream();
  }

  // 处理冷启动时的初始Intent
  Future<void> _initReceiveIntent() async {
    try {
      final receivedIntent = await ReceiveIntent.getInitialIntent();
      _extractTextFromIntent(receivedIntent);
    } on PlatformException {
      // 按需处理异常
    }
  }

  // 监听后台运行时的Intent
  void _listenToIntentStream() {
    ReceiveIntent.receivedIntentStream.listen((receivedIntent) {
      _extractTextFromIntent(receivedIntent);
    }, onError: (err) {
      // 按需处理错误
    });
  }

  // 从Intent中提取文本
  void _extractTextFromIntent(ReceivedIntent? intent) {
    if (intent != null && intent.action == "RECEIVE_INTENT_EXAMPLE_ACTION") {
      // 对应MAUI中Intent.ExtraText的系统key
      final text = intent.extras?["android.intent.extra.TEXT"];
      if (text is String) {
        setState(() {
          _receivedText = text;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("接收MAUI文本")),
      body: Center(child: Text(_receivedText)),
    );
  }
}

2. 关键说明

  • 冷启动场景:当Flutter应用未运行,通过MAUI的Intent唤起时,getInitialIntent会返回触发启动的Intent,从中提取文本。
  • 后台场景:若Flutter应用已在后台运行,需要通过receivedIntentStream监听新的Intent,确保能实时接收MAUI传递的文本。
  • 文本提取:MAUI中Intent.ExtraText对应的Android系统key是android.intent.extra.TEXT,直接从Intent的extrasMap中取值即可。

三、验证Intent Filter配置

确保Flutter应用的AndroidManifest.xml中已正确配置对应的Intent Filter,匹配自定义Action:

<intent-filter>
  <action android:name="RECEIVE_INTENT_EXAMPLE_ACTION" />
  <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

内容的提问来源于stack exchange,提问作者Ani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 23:03:22