需要在APP杀死的情况下在指定的时间进行推送
最近项目中有需求是需要点击按钮后在某一个时间点进行本地推送消息,于是研究了一下相关资料,用了一个小demo实验了一下,直接上代码
在新建的项目中安卓目录下对build.gradle文件修改
1.首先在安卓文件夹中添加推送时需要的图片和声音文件
2.main.dart文件中代码
首先在pubspec.yaml中添加第三方库 flutter_local_notifications
flutter项目终端执行命令 flutter pub add flutter_local_notifications
main.dart添加代码
因为会用到延迟执行所以用zonedSchedule这个方法
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
void main() async {
tz.initializeTimeZones();
if (Platform.isAndroid) {
WidgetsFlutterBinding.ensureInitialized();
var initializationSettingsAndroid = const AndroidInitializationSettings(
'playstoreicon',
);
var initializationSettings = InitializationSettings(
android: initializationSettingsAndroid,
);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onDidReceiveNotificationResponse: (details) async {
if (details.payload != null) {
debugPrint(
'notification payload: ${details.payload}',
);
}
},
);
}
AndroidNotificationDetails _androidNotificationDetails =
const AndroidNotificationDetails(
'channel1 ID',
'channel1 name',
channelDescription: 'channel description',
icon: 'playstoreicon',
sound: RawResourceAndroidNotificationSound('alongcoldsting'),
largeIcon: DrawableResourceAndroidBitmap('playstoreicon'),
importance: Importance.max,
priority: Priority.high,
);
NotificationDetails platformChannelSpecifics = NotificationDetails(
android: _androidNotificationDetails,
);
/*
解决报错问题
https://github.com/dart-lang/sdk/issues/46259
*/
await flutterLocalNotificationsPlugin.zonedSchedule(
1,
'本地推送提示',
'延迟30秒执行',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 30)),
platformChannelSpecifics,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true,
payload: 'Notification Payload',
);
runApp(MyApp());
}