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

如何在Flutter应用完全关闭(含移除后台)时启用通知?

解决Flutter应用被杀后无法触发充电器插拔通知的问题

当前你用battery_plus的onBatteryStateChanged监听是绑定在应用进程上的,应用从最近列表移除后进程直接终止,监听自然失效。要实现应用被杀后还能触发通知,必须用Android的系统级广播或者后台服务,下面是具体实现步骤:


1. 修改AndroidManifest.xml,添加权限和广播接收器

打开android/app/src/main/AndroidManifest.xml,补充权限和静态广播接收器:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 保留原有权限,新增以下权限 -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

    <application
        android:label="testbattery"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
        <!-- 保留原有Activity代码 -->
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:taskAffinity=""
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <!-- 添加静态广播接收器,监听充电器插拔事件 -->
        <receiver
            android:name=".ChargerBroadcastReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </receiver>

        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>

    <!-- 保留原有queries代码 -->
    <queries>
        <intent>
            <action android:name="android.intent.action.PROCESS_TEXT"/>
            <data android:mimeType="text/plain"/>
        </intent>
    </queries>
</manifest>

2. 编写安卓原生广播接收器

在你的安卓项目包路径下(比如android/app/src/main/kotlin/com/example/testbattery/)创建ChargerBroadcastReceiver.kt文件,代码如下:

package com.example.testbattery // 替换成你自己的应用包名

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat

class ChargerBroadcastReceiver : BroadcastReceiver() {
    private val CHANNEL_ID = "charger_channel"

    override fun onReceive(context: Context?, intent: Intent?) {
        context ?: return
        intent ?: return

        val (title, content) = when (intent.action) {
            Intent.ACTION_POWER_CONNECTED -> Pair("充电器已连接", "你的设备正在充电")
            Intent.ACTION_POWER_DISCONNECTED -> Pair("充电器已断开", "你的设备停止充电")
            else -> return
        }

        // 构建并发送通知
        val notification = NotificationCompat.Builder(context, CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(content)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()

        NotificationManagerCompat.from(context).notify(0, notification)
    }
}

3. 确保通知渠道已创建

Android 8.0+必须创建通知渠道才能显示通知,你原来的Flutter代码里的_initializeNotifications方法已经处理了这部分逻辑,保持不变即可。

4. 处理厂商后台限制(重中之重)

国内安卓厂商(小米、华为、OPPO等)都有严格的后台管控,就算配置了广播接收器,应用被杀后可能还是无法触发通知。必须引导用户给应用开启自启动权限和后台运行权限,可以在Flutter端添加按钮跳转到应用设置:

// 导入permission_handler包
import 'package:permission_handler/permission_handler.dart';

// 跳转应用设置页面
void _openAppSettings() async {
  await openAppSettings();
}

// 在UI中添加权限引导按钮
ElevatedButton(
  onPressed: _openAppSettings,
  child: const Text('开启后台运行权限'),
)

补充说明

  • 静态广播由Android系统直接触发,不依赖应用进程存活状态,所以应用被杀后依然能收到充电器插拔事件。
  • Android 12+对部分隐式广播有限制,但充电器插拔的这两个广播属于系统允许的范围,无需额外适配。
  • 如果需要结合Flutter代码处理更复杂的后台逻辑,可以使用flutter_background_service插件实现后台服务,再绑定广播监听。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 06:55:08