Flutter多分享意图接收插件receive_multi_sharing_intent的使用

发布于 1周前 作者 itying888 来自 Flutter

Flutter多分享意图接收插件receive_multi_sharing_intent的使用

插件介绍

receive_multi_sharing_intent 是一个用于接收来自其他应用的共享内容(如图片、文本等)的Flutter插件。该插件支持同时处理多个不同类型的共享意图。

配置

Android配置

AndroidManifest.xml 文件中添加 ActivityAlias 来定义不同的共享意图:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    .....
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <application
        android:name="io.flutter.app.FlutterApplication"
        ...
        >
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            ...
            ...
        </activity>
        <activity-alias
            android:name="com.example.myapp.ImageShareIntent"
            android:targetActivity=".MainActivity"
            android:label="My App Label"
            android:icon="@mipmap/ic_launcher">
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="image/*" />
            </intent-filter>
        </activity-alias>
        <activity-alias
            android:name="com.example.myapp.TextShareIntent"
            android:targetActivity=".MainActivity"
            android:label="My App Label"
            android:icon="@mipmap/ic_launcher">
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:mimeType="text/plain" />
            </intent-filter>
        </activity-alias>
    </application>
</manifest>

注意 <activity-alias> 中的 android:name 属性需要是一个完全限定域名(Fully Qualified Domain Name, FQDN),并且每个别名都需要定义一个独立的意图过滤器来处理特定类型的共享数据。

Dart代码实现

在Dart代码中,我们需要监听共享意图流,并处理接收到的数据。

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:receive_multi_sharing_intent/receive_sharing_intent.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late StreamSubscription _intentDataStreamSubscription;
  List<SharedMediaFile>? _sharedFiles;
  String? _sharedText;

  [@override](/user/override)
  void initState() {
    super.initState();

    // 监听来自外部应用的图像共享意图
    _intentDataStreamSubscription = ReceiveSharingIntent.getMediaStream("com.example.myapp.ImageShareIntent")
        .listen((List<SharedMediaFile> value) {
      setState(() {
        _sharedFiles = value;
        print("Shared:" + (_sharedFiles?.map((f) => f.path).join(",") ?? ""));
      });
    }, onError: (err) {
      print("getIntentDataStream error: $err");
    });

    // 处理应用启动时接收到的初始图像共享数据
    ReceiveSharingIntent.getInitialMedia("com.example.myapp.ImageShareIntent").then((List<SharedMediaFile> value) {
      setState(() {
        _sharedFiles = value;
        print("Shared:" + (_sharedFiles?.map((f) => f.path).join(",") ?? ""));
      });
    });

    // 监听来自外部应用的文本共享意图
    _intentDataStreamSubscription = ReceiveSharingIntent.getTextStream("com.example.myapp.TextShareIntent")
        .listen((String value) {
          setState(() {
            _sharedText = value;
            print("Shared: $_sharedText");
          });
        }, onError: (err) {
          print("getTextStream error: $err");
        });

    // 处理应用启动时接收到的初始文本共享数据
    ReceiveSharingIntent.getInitialText("com.example.myapp.TextShareIntent").then((String? value) {
      setState(() {
        _sharedText = value;
        print("Shared: $_sharedText");
      });
    });
  }

  [@override](/user/override)
  void dispose() {
    _intentDataStreamSubscription.cancel();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    const textStyleBold = const TextStyle(fontWeight: FontWeight.bold);
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: <Widget>[
              Text("Shared files:", style: textStyleBold),
              Text(_sharedFiles
                  ?.map((f) =>
              "{Path: ${f.path}, Type: ${f.type.toString().replaceFirst("SharedMediaType.", "")}}\n")
                  .join(",\n") ??
                  ""),
              SizedBox(height: 100),
              Text("Shared text:", style: textStyleBold),
              Text(_sharedText ?? "")
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter多分享意图接收插件receive_multi_sharing_intent的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter多分享意图接收插件receive_multi_sharing_intent的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter应用中使用receive_multi_sharing_intent插件来接收多分享意图的示例代码。这个插件允许你的Flutter应用接收来自其他应用分享的数据,并且支持接收多个分享项。

步骤 1: 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  receive_multi_sharing_intent: ^x.y.z  # 请替换为最新版本号

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

步骤 2: 配置AndroidManifest.xml

对于Android平台,你需要在android/app/src/main/AndroidManifest.xml中添加相应的intent-filter来声明你的应用可以接收分享意图:

<activity
    android:name=".MainActivity"
    android:launchMode="singleTop"
    android:theme="@style/LaunchTheme"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
    android:hardwareAccelerated="true"
    android:windowSoftInputMode="adjustResize">
    <intent-filter>
        <action android:name="android.intent.action.SEND_MULTIPLE" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="*/*" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.SEND" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:mimeType="*/*" />
    </intent-filter>
</activity>

步骤 3: 使用插件接收分享数据

在你的Flutter代码中,你可以使用ReceiveSharingIntent类来监听和处理分享的数据。以下是一个简单的示例:

import 'package:flutter/material.dart';
import 'package:receive_multi_sharing_intent/receive_sharing_intent.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<SharedMediaFile> sharedFiles = [];

  @override
  void initState() {
    super.initState();
    _initReceiveSharingIntent();
  }

  Future<void> _initReceiveSharingIntent() async {
    ReceiveSharingIntent.getTextStream().listen((String text) {
      print("Received text: $text");
      // 处理接收到的文本数据
    });

    ReceiveSharingIntent.getMediaFilesStream().listen((List<SharedMediaFile> files) {
      setState(() {
        sharedFiles = files;
      });
      print("Received files: $files");
      // 处理接收到的文件数据
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Receive Sharing Intent Demo'),
        ),
        body: Column(
          children: [
            if (sharedFiles.isNotEmpty)
              Expanded(
                child: ListView.builder(
                  itemCount: sharedFiles.length,
                  itemBuilder: (context, index) {
                    final file = sharedFiles[index];
                    return ListTile(
                      title: Text(file.mimeType ?? 'Unknown Type'),
                      subtitle: Text(file.path ?? 'No Path'),
                    );
                  },
                ),
              ),
            if (sharedFiles.isEmpty)
              Center(
                child: Text('No shared files received yet.'),
              ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们监听了文本和媒体文件的分享流。当应用接收到分享意图时,它会打印出接收到的数据,并在UI中显示接收到的文件信息。

注意事项

  1. 权限处理:确保你的应用有适当的权限来访问接收到的文件(如读取存储权限)。
  2. 错误处理:在实际应用中,你应该添加错误处理逻辑来优雅地处理可能的异常情况。
  3. 插件版本:检查并更新到最新的插件版本,以确保兼容性和功能完整性。

这个示例提供了一个基本的框架,你可以根据实际需求进行扩展和定制。

回到顶部