Flutter广播发送插件sendbroadcast的使用

Flutter广播发送插件sendbroadcast的使用

概述

sendbroadcast 是一个用于在 Flutter 中实现广播发送功能的插件。它允许开发者通过 Android 和 iOS 平台进行广播消息的注册和发送。


使用步骤

以下是 sendbroadcast 插件的基本使用方法,包含完整的示例代码。

1. 添加依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  sendbroadcast: ^1.0.0  # 替换为最新版本号

然后运行以下命令以安装依赖:

flutter pub get

2. 完整示例代码

以下是一个完整的示例代码,展示了如何使用 sendbroadcast 插件进行广播注册和发送。

示例代码:lib/main.dart

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

import 'package:flutter/services.dart';
import 'package:sendbroadcast/sendbroadcast.dart'; // 引入 sendbroadcast 插件

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown'; // 平台版本信息
  final sendBroadcast = SendBroadcast(); // 初始化 SendBroadcast 实例

  @override
  void initState() {
    super.initState();
    // initPlatformState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('sendbroadcast 示例'), // 设置标题
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center, // 主轴方向居中
          children: [
            // 注册广播接收器按钮
            Center(
              child: ElevatedButton(
                onPressed: () async {
                  // 注册广播接收器
                  await sendBroadcast.registerReceiver(
                      action: "NEW_NEW", param: "message");
                  print("广播接收器已注册");
                },
                child: const Text("注册广播接收器"),
              ),
            ),
            const SizedBox(height: 20), // 增加间距
            // 发送广播按钮
            Center(
              child: ElevatedButton(
                onPressed: () async {
                  // 发送广播消息
                  await sendBroadcast.send(
                      value: 'asdasdsadasdas', // 广播值
                      action: 'NEW_NEW', // 广播动作
                      param: 'message'); // 广播参数
                  print("广播已发送");
                  setState(() {}); // 更新 UI
                },
                child: const Text("发送广播"),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

3. 运行效果

运行上述代码后,您将看到一个简单的 Flutter 页面,其中包含两个按钮:

  • 注册广播接收器:点击后会注册一个广播接收器。
  • 发送广播:点击后会发送一条广播消息。

代码说明

  1. 导入依赖

    import 'package:sendbroadcast/sendbroadcast.dart';
    

    导入 sendbroadcast 插件以便使用其功能。

  2. 初始化插件实例

    final sendBroadcast = SendBroadcast();
    
  3. 注册广播接收器

    await sendBroadcast.registerReceiver(
        action: "NEW_NEW", param: "message");
    

    通过调用 registerReceiver 方法注册广播接收器。

  4. 发送广播消息

    await sendBroadcast.send(
        value: 'asdasdsadasdas', action: 'NEW_NEW', param: 'message');
    

更多关于Flutter广播发送插件sendbroadcast的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter广播发送插件sendbroadcast的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,sendBroadcast 是用于发送系统广播的方法。通常,这种广播是Android平台特有的功能,因此在使用 sendBroadcast 时,你需要与Android原生代码进行交互。

以下是如何在Flutter中使用 sendBroadcast 的步骤:

1. 创建Flutter项目

首先,确保你已经创建了一个Flutter项目。

2. 添加Android原生代码

你需要在 android/app/src/main/kotlin/com/example/your_app/ 目录下创建一个新的Kotlin类,或者如果你使用的是Java,则创建一个Java类。

例如,创建一个 BroadcastHelper.kt 文件:

package com.example.your_app

import android.content.Context
import android.content.Intent
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar

class BroadcastHelper(private val context: Context) : MethodCallHandler {

    companion object {
        @JvmStatic
        fun registerWith(registrar: Registrar) {
            val channel = MethodChannel(registrar.messenger(), "com.example.your_app/broadcast")
            channel.setMethodCallHandler(BroadcastHelper(registrar.context()))
        }
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        when (call.method) {
            "sendBroadcast" -> {
                val action = call.argument<String>("action")
                if (action != null) {
                    val intent = Intent(action)
                    context.sendBroadcast(intent)
                    result.success(null)
                } else {
                    result.error("INVALID_ARGUMENT", "Action cannot be null", null)
                }
            }
            else -> result.notImplemented()
        }
    }
}

3. 在Flutter中调用原生代码

在你的Flutter代码中,你可以通过 MethodChannel 来调用这个原生方法。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Send Broadcast Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              const platform = MethodChannel('com.example.your_app/broadcast');
              try {
                await platform.invokeMethod('sendBroadcast', {'action': 'com.example.your_app.MY_ACTION'});
              } on PlatformException catch (e) {
                print("Failed to send broadcast: '${e.message}'.");
              }
            },
            child: Text('Send Broadcast'),
          ),
        ),
      ),
    );
  }
}

4. 注册插件

MainActivity.kt 中注册这个插件:

package com.example.your_app

import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine)
        BroadcastHelper.registerWith(flutterEngine.dartExecutor.binaryMessenger, applicationContext)
    }
}

5. 定义广播接收器(可选)

如果你想要接收这个广播,你可以在AndroidManifest.xml中定义一个广播接收器:

<receiver android:name=".MyBroadcastReceiver">
    <intent-filter>
        <action android:name="com.example.your_app.MY_ACTION" />
    </intent-filter>
</receiver>

然后创建一个 MyBroadcastReceiver.kt 文件:

package com.example.your_app

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent

class MyBroadcastReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        // Handle the broadcast here
    }
}
回到顶部