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

时间:2019-09-05 10:56:05

标签: android flutter dart

我有一个警报,它每天触发一次并比较两个值。如果这些值相等,我将发送通知。因此,我创建了特定于平台的方法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.");
      }
    });

  }
}

1 个答案:

答案 0 :(得分:0)

在执行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
  }