How to call MethodChannel from an isolate created by android_alarm_manager?

1,341

It seem impossible to call directly MethodChannel through an isolate.

But, with the creation of a plugin i can achieve what i want. So the solution is to create a plugin :) !

Share:
1,341
Eng
Author by

Eng

Updated on December 21, 2022

Comments

  • Eng
    Eng over 1 year

    I tried to schedule background service. For that i used https://pub.dev/packages/android_alarm_manager. It works well.

    For my example, I tried to get from my isolate (android_alarm_manager's callback) the battery level following the flutter tutorial : https://flutter.dev/docs/development/platform-integration/platform-channels?tab=android-channel-java-tab.

    If I call manualy my callback it works (so I well do the Android part). If android_alarm_manager call it, I got the following error appear :

    Unhandled Exception: MissingPluginException(No implementation found for method getBatteryLevel on channel net.example.com/battery)
    

    It's weird because, from an other isolate where I used https://pub.dev/packages/flutter_downloader to download file, this plugin used MethodChannel...

    Here is my code for android_alarm_manager :

    import 'package:flutter/services.dart';
    
    class AndroidManagerCallBack {
      static Future<void> main() async {
        _AndroidManagerCallBack test = _AndroidManagerCallBack();
        await test.getBatteryLevel();
      }
    }
    
    class _AndroidManagerCallBack {
      static const platform = const MethodChannel('net.example.com/battery');
    
      Future<void> getBatteryLevel() async {
        String batteryLevel;
        try {
          final int result = await platform.invokeMethod('getBatteryLevel');
          batteryLevel = 'Battery level at $result % .';
        } on PlatformException catch (e) {
          batteryLevel = "Failed to get battery level: '${e.message}'.";
        }
        print(batteryLevel);
      }
    }
    
    

    I simply call the callback like :

    AndroidAlarmManager.periodic(
          Duration(seconds: 20),
          0,
          AndroidManagerCallBack.main(),
          rescheduleOnReboot: true,
          wakeup: false,
        );
    

    In android_alarm_manager's callback, I can call plugins which used somee MethodChannel but when I tried with my MethodChannel, I got errors...

    Someone can guide me :) ?

  • pitazzo
    pitazzo over 3 years
    Did you managed to solve this? I want to call native code from an isolate, but I can't see the way of doing that, even with a plugin
  • Eng
    Eng over 3 years
    flutter.dev/docs/development/packages-and-plugins/… I've followed doc to create plugin :)