Flutter应用被杀后推送通知插件notification_when_app_is_killed的使用

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

Flutter应用被杀后推送通知插件 notification_when_app_is_killed 的使用

概述

notification_when_app_is_killed 插件允许在Flutter应用被杀死时显示推送通知。本文将详细介绍如何在iOS平台上配置和使用该插件,并提供一个完整的示例代码。

依赖项

iOS 配置

1. 修改 ios/Podfile

为了获取通知权限,需要在 ios/Podfile 中添加以下内容:

post_install do |installer|
  installer.pods_project.targets.each do |target|
    flutter_additional_ios_build_settings(target)

    target.build_configurations.each do |config|
       config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
        '$(inherited)',
        # dart: PermissionGroup.notification
        'PERMISSION_NOTIFICATIONS=1',
      ]
    end
  end
end

2. 修改 ios/AppDelegate.swift

ios/AppDelegate.swift 文件中添加以下代码:

import UserNotifications
import notification_when_app_is_killed

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
   override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {

    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
    }

   // 其他初始化代码...

  }

  override func applicationWillTerminate(_ application: UIApplication) {
    let notificationWhenAppIsKilledInstance = NotificationWhenAppIsKilledPlugin.instance
    notificationWhenAppIsKilledInstance.applicationWillTerminate();
  }
}

参考 example AppDelegate.swift 获取更多细节。

如何使用

设置通知服务

final _notificationWhenAppIsKilledPlugin = NotificationWhenAppIsKilled();

ArgsForIos argsForIos = ArgsForIos(
  interruptionLevel: InterruptionLevel.critical,
  useDefaultSound: true,
);
await _notificationWhenAppIsKilledPlugin.setNotificationOnKillService(
  ArgsForKillNotification(
      title: 'The app is killed',
      description:
          'You can see this notification when the app is killed',
      argsForIos: argsForIos),
);

取消通知服务

final _notificationWhenAppIsKilledPlugin = NotificationWhenAppIsKilled();

await _notificationWhenAppIsKilledPlugin.cancelNotificationOnKillService();

示例代码

下面是一个完整的示例代码,展示了如何在Flutter应用中集成并使用 notification_when_app_is_killed 插件:

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

import 'package:flutter/services.dart';
import 'package:notification_when_app_is_killed/model/args_for_ios.dart';
import 'package:notification_when_app_is_killed/model/args_for_kill_notification.dart';
import 'package:notification_when_app_is_killed/notification_when_app_is_killed.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  bool _isServiceOn = false;
  final _notificationWhenAppIsKilledPlugin = NotificationWhenAppIsKilled();

  Future<void> setNotificationOnKill() async {
    bool success;
    try {
      ArgsForIos argsForIos = ArgsForIos(
        interruptionLevel: InterruptionLevel.critical,
        useDefaultSound: true,
      );
      success =
          await _notificationWhenAppIsKilledPlugin.setNotificationOnKillService(
                ArgsForKillNotification(
                    title: 'The app is killed',
                    description:
                        'You can see this notification when the app is killed',
                    androidIcon: '@raw/ic_launcher',
                    argsForIos: argsForIos),
              ) ??
              false;
    } on PlatformException {
      success = false;
    }
    if (!success) return;
    setState(() {
      _isServiceOn = true;
    });
  }

  Future<void> cancelNotificationOnKill() async {
    bool success;
    try {
      success = await _notificationWhenAppIsKilledPlugin
              .cancelNotificationOnKillService() ??
          false;
    } on PlatformException {
      success = false;
    }
    if (!success) return;
    setState(() {
      _isServiceOn = false;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Notification when app is killed example app'),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextButton(
                  onPressed: setNotificationOnKill,
                  child: const Text('Set notification when app is killed')),
              TextButton(
                  onPressed: cancelNotificationOnKill,
                  child: const Text('Cancel notification when app is killed')),
              const SizedBox(height: 20),
              Text('Service is on: '),
              Switch(
                  value: _isServiceOn,
                  onChanged: (value) {
                    if (value) {
                      setNotificationOnKill();
                    } else {
                      cancelNotificationOnKill();
                    }
                  })
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter应用被杀后推送通知插件notification_when_app_is_killed的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter应用被杀后推送通知插件notification_when_app_is_killed的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter应用中,处理应用被杀后仍然能够接收推送通知的需求,可以使用flutter_local_notificationsfirebase_messaging等插件结合notification_when_app_is_killed的概念来实现。不过需要注意的是,notification_when_app_is_killed并不是一个具体的Flutter插件名称,而是一个功能描述。实际实现这一功能通常依赖于后台消息(Background Messaging)的处理。

以下是一个结合firebase_messagingflutter_local_notifications的示例代码,展示了如何在Flutter应用中处理应用被杀后的推送通知:

1. 添加依赖

首先,在你的pubspec.yaml文件中添加必要的依赖:

dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.10.0 # 确保使用最新版本
  firebase_messaging: ^11.2.0 # 确保使用最新版本
  flutter_local_notifications: ^9.2.0 # 确保使用最新版本

2. 配置Firebase

在Firebase控制台中为你的应用创建项目,并下载google-services.json文件,将其放置在android/app/目录下。

3. 初始化Firebase Messaging和Local Notifications

在你的main.dart文件中初始化这些服务:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

const AndroidInitializationSettings androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
const IOSInitializationSettings iosSettings = IOSInitializationSettings(
  requestAlertPermission: true,
  requestSoundPermission: true,
  requestBadgePermission: true,
);
const InitializationSettings initializationSettings = InitializationSettings(android: androidSettings, iOS: iosSettings);

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  flutterLocalNotificationsPlugin.initialize(initializationSettings,
      onSelectNotification: (String? payload) async {
    if (payload != null) {
      // handle payload when tap on notification
      debugPrint('Notification payload: $payload');
    }
  });

  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    RemoteNotification? notification = message.notification;
    AndroidNotification? android = message.notification?.android;
    if (notification != null && android != null && !kIsWeb) {
      flutterLocalNotificationsPlugin.show(
        notification.hashCode,
        notification.title,
        notification.body,
        NotificationDetails(
          android: AndroidNotificationDetails(
            channel.id,
            channel.name,
            channel.description,
            icon: '@mipmap/ic_launcher',
            sound: RawResourceAndroidNotificationSound('notification_sound'),
            priority: Priority.high,
            importance: Importance.max,
            autoCancel: true,
          ),
        ),
      );
    }
  });

  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    print('A new onMessageOpenedApp event was published!');
  });

  // Handle background messages
  FirebaseMessaging.backgroundMessage(firebaseMessagingBackgroundHandler);

  runApp(MyApp());
}

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  if (message.data.isNotEmpty) {
    // Handle data message
    print('A background message was received: ${message.data}');
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Firebase Messaging Demo'),
        ),
        body: Center(
          child: Text('Check your console/terminal for messages!'),
        ),
      ),
    );
  }
}

4. 创建通知渠道(仅Android)

在Android上,你需要创建一个通知渠道:

AndroidNotificationChannel channel = AndroidNotificationChannel(
  'high_importance_channel', // id
  'High Importance Notifications', // title
  'This channel is used for important notifications.', // description
  importance: Importance.high,
  priority: Priority.high,
);

final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

void configureLocalNotifications() {
  flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
      AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);
}

在你的main()函数中调用configureLocalNotifications()来设置渠道。

5. 测试推送通知

你可以使用Firebase Cloud Messaging控制台发送测试消息,或者通过代码发送消息来测试应用被杀后是否能接收到推送通知。

注意事项

  • 确保你的应用已经在后台被杀的情况下进行测试。
  • 对于iOS,需要确保应用具有后台运行和接收远程通知的权限。
  • 对于Android,确保应用具有显示通知的权限,并且通知渠道已经正确配置。

通过上述步骤,你可以在Flutter应用中实现应用被杀后仍然能够接收推送通知的功能。

回到顶部