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 :) ?
EDIT : 2023
Isolate seems to be able to call platform channel with flutter 3.7 https://medium.com/flutter/introducing-background-isolate-channels-7a299609cad8 https://docs.google.com/document/d/1yAFw-6kBefuurXWTur9jdEUAckWiWJVukP1Iay8ehyU/edit#heading=h.722pnbmlqbkx
2020
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 :) !