Flutter启动接收插件flutter_boot_receiver的使用

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

Flutter启动接收插件flutter_boot_receiver的使用

flutter_boot_receiver 是一个用于在 Android 设备启动时注册 Dart 回调的 Flutter 插件。以下是如何安装和使用该插件的详细步骤及示例代码。

平台支持

平台 支持
Android ✔️ Yes
iOS ❌ No
Web ❌ No
Windows ❌ No
Linux ❌ No
MacOS ❌ No

安装

  1. 在您的 pubspec.yaml 文件中添加插件:
dependencies:
  flutter:
    sdk: flutter
  flutter_boot_receiver: ^最新版本号

然后运行:

flutter pub get
  1. 在您的 AndroidManifest.xml 中,确保在 <manifest> 标签中添加了 android:installLocation="internalOnly"。只有安装在内部存储中的设备才能在 Android 上接收到 BOOT_COMPLETED 广播。
<manifest
    android:installLocation="internalOnly"
    >
  1. 添加所需的权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<!-- For API versions 25 and below -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
  1. <application> 标签内添加服务和接收器:
<service
    android:name="com.flux.flutter_boot_receiver.BootHandlerService"
    android:exported="false"
    android:permission="android.permission.BIND_JOB_SERVICE"
    />
<receiver
    android:enabled="true"
    android:exported="true"
    android:name="com.flux.flutter_boot_receiver.BootBroadcastReceiver"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
    </inten-filter>
</receiver>

完整的 AndroidManifest.xml 结构应如下所示:

<manifest
    android:installLocation="internalOnly"
    >
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <!-- For API versions 25 and below -->
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application>
        <service
            android:name="com.flux.flutter_boot_receiver.BootHandlerService"
            android:exported="false"
            android:permission="android.permission.BIND_JOB_SERVICE"
            />
        <receiver
            android:enabled="true"
            android:exported="true"
            android:name="com.flux.flutter_boot_receiver.BootBroadcastReceiver"
            android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

使用

在 Dart 代码中导入插件并设置回调函数:

import 'package:flutter_boot_receiver/flutter_boot_receiver.dart';

@pragma('vm:entry-point')
void callback() async {
  // 当设备启动时执行的代码
  print("Device has booted up!");
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await BootReceiver.initialize(callback);
  runApp(MyApp());
}

示例 Demo

下面是一个完整的 Flutter 应用程序示例,它在设备启动时打印一条消息:

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

@pragma('vm:entry-point')
void callback() async {
  print("Device has booted up!");
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await BootReceiver.initialize(callback);
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Boot Receiver Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Boot Receiver Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'This app will print a message when the device boots!',
            ),
          ],
        ),
      ),
    );
  }
}

通过以上步骤和示例代码,您可以在 Android 设备启动时触发特定的 Dart 回调函数。请根据您的具体需求调整回调函数中的逻辑。


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

1 回复

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


当然,下面是一个关于如何在Flutter应用中使用flutter_boot_receiver插件来接收启动意图(Boot Received)的示例代码。这个插件允许你在应用启动时执行一些特定的操作,比如处理启动参数或者执行初始化任务。

首先,确保你已经在pubspec.yaml文件中添加了flutter_boot_receiver依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_boot_receiver: ^最新版本号 # 请替换为实际的最新版本号

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

1. 配置Android原生代码

由于flutter_boot_receiver涉及到Android平台的启动接收器,你需要在android/app/src/main/AndroidManifest.xml中添加必要的配置。

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

    <application
        ... >
        <receiver android:name=".BootReceiver" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        ...
    </application>

    <!-- 添加权限以接收BOOT_COMPLETED广播 -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>

接下来,在android/app/src/main/kotlin/com/example/yourapp/(或Java目录,如果你使用的是Java)下创建一个名为BootReceiver.kt(或BootReceiver.java)的文件,并实现BroadcastReceiver

BootReceiver.kt:

package com.example.yourapp

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.plugin.common.MethodChannel

class BootReceiver : BroadcastReceiver() {
    companion object {
        private const val CHANNEL = "com.example.yourapp/boot_channel"
    }

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
            // 获取或创建FlutterEngine
            val flutterEngine = FlutterEngineCache
                .getInstance()
                .get(DartExecutor.DartExecutorType.UI)
                ?: FlutterEngine(context)

            // 设置MethodChannel以与Flutter代码通信
            MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).invokeMethod(
                "onBootCompleted",
                hashMapOf("message" to "Device booted")
            )

            // 如果FlutterEngine是新创建的,启动Dart执行器
            if (!FlutterEngineCache.getInstance().put(flutterEngine)) {
                flutterEngine.destroy()
            }
        }
    }
}

2. Flutter端代码

在Flutter代码中,你需要设置一个MethodChannel来监听来自BootReceiver的消息。

main.dart:

import 'package:flutter/material.dart';
import 'package:flutter_boot_receiver/flutter_boot_receiver.dart'; // 假设有一个这样的包名,实际使用时请替换为正确包名

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  // 设置MethodChannel
  const platform = MethodChannel('com.example.yourapp/boot_channel');

  // 监听来自BootReceiver的消息
  platform.setMethodCallHandler((call) async {
    if (call.method == "onBootCompleted") {
      final Map<String, dynamic> arguments = call.arguments as Map<String, dynamic>;
      print("Received from BootReceiver: ${arguments['message']}");
      // 在这里处理启动完成后的逻辑
    }
  });

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Text('Check the console for boot receiver messages.'),
      ),
    );
  }
}

注意:实际上,flutter_boot_receiver这个包名可能是虚构的,因为Flutter社区中可能没有直接名为flutter_boot_receiver的官方或广泛使用的插件。上面的示例展示了如何在Flutter应用中集成自定义的BroadcastReceiver并通过MethodChannel与Dart代码通信。如果你找到一个具体的第三方插件,其使用方法可能会有所不同,请参考该插件的官方文档。

此外,由于Android 7.0(API级别24)及更高版本对隐式广播接收器的限制,你可能需要在应用中动态注册接收器或使用JobScheduler/WorkManager来处理启动后的任务。

回到顶部