简体   繁体   中英

Flutter - Call dart function from kotlin

I'm building an app with flutter that gives you a notification with action buttons every 5 minutes. I use the android_alarm_manager and local_notifications package to implement that. Everything works fine and the alarm manager also works when I terminate the app but there is one problem. When I receive a notification and then clean the memory or wait too long the actions buttons don't work anymore.

I figured out that that's not a problem from Android because the listener is actually called (I tested it with a sysout), but because I cleaned the memory and so all apps were terminated, the MethodChannel (is set when initializing the local_notifiactions plugin) with that you can access the dart classes of flutter project is null. Consequently, the app can't access the notification action button clicked callback that I defined in my dart code.

So how can I initialize flutter from kotlin so that I can access the dart code of my project (without actually starting the app)?

Here is the code from the local_notifications library that calls the action button callback function in dart

private static boolean invokeCallback(String callbackName, String payload) {
    // getSharedChannel = null, because the app were terminated
    MethodChannel channel = LocalNotificationsService.getSharedChannel();

    if (channel != null) {
        /* I need the MethodChannel to call this function (invokeMethod)
           which calls my action button callback function in dart */
        channel.invokeMethod(callbackName, payload); 
        return true;
    } else {
        customLog("MethodChannel was null");
        return false;
    }
}

The getSharedChannel function just returns the variable, that was been set in the registerWith function, but that variable was reset because the memory has been cleared (but I want that my app also works when that happens)

public static MethodChannel getSharedChannel() {
    return sSharedChannel;
}

.

public static void registerWith(Registrar registrar) {
    final MethodChannel channel = new MethodChannel(registrar.messenger(), LocalNotificationsPlugin.CHANNEL_NAME);
    LocalNotificationsPlugin plugin = new LocalNotificationsPlugin(registrar);
    channel.setMethodCallHandler(plugin);
    registrar.addNewIntentListener(plugin);

    //The MethodChannel is set here, which can then be accessed with getSharedChannel
    LocalNotificationsService.setSharedChannel(channel);
}

The Flutter engine is bounded to Activity, that's why you can't use the channel when the activity destroyed. I guess you should send an intent by tap on your notification which starts an activity and invoke the channel there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM