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

Flutter定时本地通知Android端前后台区分实现方法咨询

Android端实现Flutter前后台判断及通知逻辑切换

1. 实现应用前台状态检测工具类

在Android项目中创建工具类,用于判断当前应用是否处于前台运行状态:

import android.app.ActivityManager
import android.content.Context

object AppForegroundChecker {
    fun isAppInForeground(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningProcesses = activityManager.runningAppProcesses ?: return false
        
        val packageName = context.packageName
        for (processInfo in runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND 
                && processInfo.processName == packageName) {
                return true
            }
        }
        return false
    }
}

2. 自定义通知接收器拦截定时通知触发逻辑

flutterLocalNotifications在Android端默认会通过预设接收器处理定时通知,我们需要自定义接收器来替换默认逻辑:

首先在AndroidManifest.xml中注册自定义接收器:

<receiver
    android:name=".CustomNotificationReceiver"
    android:exported="false">
    <intent-filter>
        <action android:name="io.flutter.plugins.notifications.ACTION_SCHEDULED_NOTIFICATION" />
    </intent-filter>
</receiver>

然后创建CustomNotificationReceiver类,继承插件的默认接收器并改写逻辑:

import android.content.Context
import android.content.Intent
import io.flutter.plugins.localnotifications.schedule.ScheduledNotificationReceiver
import io.flutter.plugin.common.MethodChannel

class CustomNotificationReceiver : ScheduledNotificationReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        // 判断应用前台状态
        val isForeground = AppForegroundChecker.isAppInForeground(context)
        
        if (isForeground) {
            // 应用在前台,通过MethodChannel通知Flutter展示应用内通知
            val channel = MethodChannel(flutterEngine?.dartExecutor?.binaryMessenger, "app/notification_channel")
            channel.invokeMethod("showInAppNotification", mapOf(
                "title" to intent.getStringExtra("title"),
                "body" to intent.getStringExtra("body")
            ))
        } else {
            // 应用在后台/已关闭,执行父类逻辑发送系统通知
            super.onReceive(context, intent)
        }
    }
}

3. Flutter层接收指令并展示应用内通知

在Flutter侧初始化MethodChannel,监听原生发来的展示应用内通知的指令:

import 'package:flutter/services.dart';

class InAppNotificationManager {
  static const MethodChannel _channel = MethodChannel('app/notification_channel');

  static void initListener() {
    _channel.setMethodCallHandler((call) async {
      if (call.method == 'showInAppNotification') {
        final title = call.arguments['title'] as String?;
        final body = call.arguments['body'] as String?;
        // 调用你的应用内通知组件展示内容
        _displayInAppNotification(title, body);
      }
    });
  }

  static void _displayInAppNotification(String? title, String? body) {
    // 替换为你的应用内通知实现,比如自定义弹窗或第三方插件
    // 示例:
    // CustomInAppToast.show(
    //   title: title ?? '',
    //   content: body ?? '',
    // );
  }
}

在main.dart的入口函数中初始化监听:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  InAppNotificationManager.initListener();
  runApp(const MyApp());
}

注意事项

  • 不同版本的flutterLocalNotifications插件,默认接收器类名可能存在差异,若找不到ScheduledNotificationReceiver,可查看插件源码确认父类
  • Android 12及以上系统需动态申请POST_NOTIFICATIONS权限,确保系统通知能正常发送
  • 若应用被完全杀死,MethodChannel无法通信,此时会自动执行系统通知逻辑,符合需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:51:12