需要在APP殺死的情況下在指定的時間進行推送
最近項目中有需求是需要點擊按鈕后在某一個時間點進行本地推送消息平项,于是研究了一下相關(guān)資料弟蚀,用了一個小demo實驗了一下译柏,直接上代碼
在新建的項目中安卓目錄下對build.gradle文件修改
1.首先在安卓文件夾中添加推送時需要的圖片和聲音文件
2.main.dart文件中代碼
首先在pubspec.yaml中添加第三方庫 flutter_local_notifications
flutter項目終端執(zhí)行命令 flutter pub add flutter_local_notifications
main.dart添加代碼
因為會用到延遲執(zhí)行所以用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秒執(zhí)行',
tz.TZDateTime.now(tz.local).add(const Duration(seconds: 30)),
platformChannelSpecifics,
uiLocalNotificationDateInterpretation:
UILocalNotificationDateInterpretation.absoluteTime,
androidAllowWhileIdle: true,
payload: 'Notification Payload',
);
runApp(MyApp());
}