gpt4 book ai didi

android - 在AlarmManager中调用平台特定的代码

转载 作者:行者123 更新时间:2023-12-03 04:00:14 25 4
gpt4 key购买 nike

我有一个警报,它每天触发一次并比较两个值。如果这些值相等,我将发送通知。因此,我创建了特定于平台的方法send_reminder(仅适用于Android)。

我的问题:如果我在应用运行时以“常规”代码调用Method,那么一切正常。但是,如果我尝试在警报中调用该方法,则会得到此异常。

MissingPluginException(No implementation found for method send_reminder on channel reminder_channel)

checkForReminders方法:
void checkForReminders() async{
print("alarm called");

if (Platform.isAndroid) {
try {
var platform = const MethodChannel("reminder_channel");
final String result =
await platform.invokeMethod("send_reminder");
print("Result of platform: $result");
} catch (e) {
print("Exception while calling platformspecific code: ");
print(e);
}
}
}

我如何在main.dart中设置警报:
final int dailyAlarmID = 0;
if (firstOpen) {
await AndroidAlarmManager.initialize();
}

runApp(...);

DateTime currentDate = new DateTime.now();

if (firstOpen) {
AndroidAlarmManager.periodic(
Duration(days: 1), dailyAlarmID, checkForReminders,
rescheduleOnReboot: true,
exact: true,
startAt: DateTime(
currentDate.year, currentDate.month, currentDate.day, 11, 30, 10));
}

MainActivity.java:
public class MainActivity extends FlutterActivity{
private static final String REMINDERCHANNEL = "reminder_channel";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);

new MethodChannel(getFlutterView(),REMINDERCHANNEL).setMethodCallHandler(new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall, Result result) {
result.success("String returned correctly.");
}
});

}
}

最佳答案

您只需要在执行if(Platform.isAndroid)的核心之前检查checkForReminders()
因此您将拥有类似以下内容:

  import 'dart:io';//todo import in top

checkForReminders() {
//... other code

if (Platform.isAndroid) {
// Android-specific code
var platform = const MethodChannel("reminder_channel");
try {
//This is just Hello World! String to see if it is working correctly
final String result = await platform.invokeMethod("send_reminder");
print("Result of platform: $result");
} catch (e) {
print("Exception while calling platformspecific code");
print(e);
}
}

//... other code
}

关于android - 在AlarmManager中调用平台特定的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57803937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com