How to call MethodChannel from an isolate created by android_alarm_manager?

Issue

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 🙂 ?

Solution

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 🙂 !

Answered By – Eng

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *