我正在尝试使用Android中的alarmmanager和通知,但我遇到了困难。基本上,这是我想要实现的行为:
我遇到的问题:
我在通知点击回调和应用启动时调用了这个本地函数。这要求我重新安排所有闹钟。 代码片段:
- 从sharedpreferences和/或firebase中获取alarmmanager必须触发的时间点。使用它来安排alarmmanager。
- 当alarmmanager触发时,从sharedpreferences和/或firebase中获取一些数据,并使用它创建一个通知。同时执行步骤1以安排下一个alarm。
- 按下通知后,必须打开特定页面。
我遇到的问题:
- 无法在单击通知时打开特定页面。
- 使用“返回”按钮关闭应用程序后,alarmmanager仍在触发,这是预期的。然而,当单击通知时,应用程序会打开并且alarmmanager不再触发。可能是因为它在另一个Isolate上运行?
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
(call, result) -> {
if (call.method.equals("resetAlarmManager")) {
try {
// Get field instance
Field field = io.flutter.plugins.androidalarmmanager.AlarmService.class.getDeclaredField("sStarted"); // NOTE: this field may change!!!
field.setAccessible(true); // Suppress Java language access checking
// Remove "final" modifier
Field modifiersField = Field.class.getDeclaredField("accessFlags");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
// Set value
field.set(null, new AtomicBoolean(false));
} catch (Exception ignored) {
Log.d("urenapp", "urenapp:reflection");
if (BuildConfig.DEBUG) {
throw new RuntimeException("REFLECTION ERROR, FIX DIT.");
}
}
}
});
我在通知点击回调和应用启动时调用了这个本地函数。这要求我重新安排所有闹钟。 代码片段:
import 'package:android_alarm_manager/android_alarm_manager.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class AlarmHelper {
static final int _REQUEST_CODE = 12377;
static final int _REQUEST_CODE_OVERTIME = 12376;
static void scheduleAlarm() async {
print('schedule');
//Read the desired time from sharedpreferences and/or firebase.
AndroidAlarmManager.cancel(_REQUEST_CODE);
AndroidAlarmManager.oneShot(Duration(seconds: 10), _REQUEST_CODE, clockIn, exact: true, wakeup: true);
}
}
void clockIn() async {
//Do Stuff
print('trigger');
//Read some stuff from sharedpreference and/or firebase.
setNotification();
//Schedule the next alarm.
AlarmHelper.scheduleAlarm();
}
void setNotification() async {
print('notification set');
//Read some more stuff from sharedpreference and/or firebase. Use that information for the notification text.
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
var androidPlatformChannelSpecifics = new AndroidNotificationDetails('test', 'test', 'test',
importance: Importance.Max, priority: Priority.Max, ongoing: true, color: Colors.blue[500]);
var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
var platformChannelSpecifics = new NotificationDetails(androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin
.show(0, 'test', 'time ' + DateTime.now().toIso8601String(), platformChannelSpecifics, payload: 'item id 2');
}