我使用flutter_local_notification
和workmanager
插件,以便在生成通知时运行一些后台代码(仅限Android).Ffltter_LOCAL_NOTIFICATION的初始化方式如下:
final StreamController<ReceivedNotification> didReceiveLocalNotificationSubject = StreamController<ReceivedNotification>.broadcast();
Future<void> init() async {
await _configureLocalTimeZone();
notificationAppLaunchDetails = await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
if (notificationAppLaunchDetails!.didNotificationLaunchApp) {
selectedNotificationPayload = notificationAppLaunchDetails!.notificationResponse?.payload;
}
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
InitializationSettings initializationSettings = const InitializationSettings(
android: initializationSettingsAndroid,
);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onDidReceiveNotificationResponse:
(NotificationResponse notificationResponse) {
switch (notificationResponse.notificationResponseType) {
case NotificationResponseType.selectedNotification:
case NotificationResponseType.selectedNotificationAction:
// if (notificationResponse.actionId == navigationActionId) {
selectNotificationSubject.add(notificationResponse.payload);
selectedNotificationPayload = notificationResponse.payload;
// }
didReceiveLocalNotificationSubject.add(
ReceivedNotification(
id: notificationResponse.id!,
title: notificationResponse.actionId,
body: 'stuff',
payload: notificationResponse.payload,
),
);
break;
}
},
// onDidReceiveBackgroundNotificationResponse: notificationTapBackground,
);
_notificationsEnabled = await _isAndroidPermissionGranted();
_notificationsEnabled = await _requestPermissions();
_configureDidReceiveLocalNotificationSubject();
}
下面是使用WorkManager执行的代码:
void _configureDidReceiveLocalNotificationSubject() {
didReceiveLocalNotificationSubject.stream
.listen((ReceivedNotification receivedNotification) async {
var title = receivedNotification.title ?? 'UNKNOWN';
Workmanager().registerOneOffTask(
"my.simpleTask",
"my.simpleTask",
inputData: <String, dynamic>{
'string': title,
},
);
});
}
目前,我对该代码有两个问题:
- 仅当用户轻触通知时,工作管理器的任务才会运行
- 如果用户首先终止应用程序,则即使生成(并点击)通知,也不会执行工作经理的任务
如何在应用程序终止或未终止的情况下,在生成通知(无需用户点击)后立即执行WorkManager的任务?