应用程序进入后台时在 Flutter 上显示本地通知

Posted

技术标签:

【中文标题】应用程序进入后台时在 Flutter 上显示本地通知【英文标题】:Display Local Notifications on Flutter the moment the App goes to the background 【发布时间】:2021-09-07 14:05:21 【问题描述】:

由于某些奇怪的原因,我的 Flutter 应用退出时无法收到通知。

我想要的是,当用户存在应用程序时,我想显示一条通知,告诉用户该应用程序当前已进入后台。

我目前正在使用flutter_local_notifications 插件来实现这一点,但它不起作用。

这是我尝试过的:

class HomePage extends StatefulWidget 
  static const routePath = "/home";

  @override
  _HomePageState createState() => _HomePageState();


class _HomePageState extends State<HomePage > with WidgetsBindingObserver 

  @override
  initState() 
    WidgetsBinding.instance!.addObserver(this);
    super.initState();
  

  @override
  void dispose() 
    WidgetsBinding.instance!.removeObserver(this);
    super.dispose();
  

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) 
    super.didChangeAppLifecycleState(state);
    bool inBackground = state == AppLifecycleState.paused;
    if (inBackground) 
displayNotification("AppName","App has gone into the background",null); //This is not displaying at all when the app goes into the background. It only displays when the app is in the foreground. I want it to display the moment the user exits the app.
    
  

Future<void> displayNotification(
  String title,
  String description,
  dynamic payload, 
  bool ongoing = false,
) async 
.....

非常感谢任何解决此问题的见解。

【问题讨论】:

我测试过,当我想在 AppLifecycleStes 的状态等于 paused 时显示通知时,它不起作用,但是当我将其更改为非活动状态时,它对我有用.我会告诉你我的答案。 【参考方案1】:

我对此进行了测试并为我工作

ma​​in.dart

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

void main() 
  runApp(MyApp());


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


class HomePage extends StatefulWidget 
  const HomePage(Key? key) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();


class _HomePageState extends State<HomePage> with WidgetsBindingObserver 
  @override
  void initState() 
    super.initState();
    WidgetsBinding.instance?.addObserver(this);
  

  @override
  void dispose() 
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) 
    super.didChangeAppLifecycleState(state);
    var appInBackground = (state == AppLifecycleState.inactive);
    if (appInBackground)
      showNotificationMessage('App has gone into the background', 'FlutterApp');
  

  @override
  Widget build(BuildContext context) 
    return Scaffold(
      body: Center(
        child: Text(
          'Testing app local notification\r\n'
          ' in background mode!',
          style: TextStyle(fontSize: 28),
        ),
      ),
    );
  


local_notification.dart

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

//define this method in global scope not a class scope
void showNotificationMessage(String? description, String? title) 
  FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
  var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
  var ios = new IOSInitializationSettings();
  var initSettings = new InitializationSettings(android: android, iOS: iOS);
  flutterLocalNotificationsPlugin.initialize(initSettings,
      onSelectNotification: null);

  String groupKey = 'com.example.general-notification-channel';
  var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
    'general-notification-channel',
    'general-notification-channel',
    'general-notification-channel',
    importance: Importance.max,
    priority: Priority.high,
    groupKey: groupKey,
    //   setAsGroupSummary: true
  );

  var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
  NotificationDetails platformChannelSpecifics = new NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics);
  flutterLocalNotificationsPlugin.show(
      0, title, description, platformChannelSpecifics);


pubspec.yaml

name: local_notification
description: A new Flutter project.
publish_to: 'none'
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.3
  flutter_local_notifications: ^6.0.0

dev_dependencies:
  flutter_test:
    sdk: flutter


flutter:
  uses-material-design: true

【讨论】:

非常感谢。您添加的这一行 var appInBackground = (state == AppLifecycleState.inactive); 是秘密

以上是关于应用程序进入后台时在 Flutter 上显示本地通知的主要内容,如果未能解决你的问题,请参考以下文章

Flutter - 如何在应用程序处于后台时在特定时间执行功能?

当应用程序处于后台/终止并收到 FCM 通知时,如何在 Flutter 中显示本地通知?

当应用程序关闭时在 Flutter 中推送通知

如何在应用程序关闭时在颤动中执行后台任务?

Flutter:当应用程序在后台时使用路径提供程序

FLutter:迭代列表时在 null 上调用了方法“[]”