I'm trying to call Dart code from Android when either the Activity is in de background or when there is no activity at all. For example, when the alarmmanager has triggered.
This is my dart code:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
const MethodChannel _kChannel =
MethodChannel('mychannel');
_kChannel.setMethodCallHandler((call) {
if (call.method == 'method1') {
return ...;
}
if (call.method == 'method2') {
return ...;
}
return Future.value();
});
}
From Java:
Application.channel.invokeMethod(method, arguments, new MethodChannel.Result() {...});
channel
is a static variable that is initialized from my mainactivity.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
Application.channel = new MethodChannel(getFlutterView(), CHANNEL_ID);
}
This works when the activity is in the foreground. But when it is in the background I get the following notification: FlutterView.send called on a detached view, channel=mychannel
The call does not get executed. How do I call Dart from Android in the background?
EDIT:
My usecase is a purely Android usecase. This is basically the flow:
- The alarmmanager fires and the broadcast event is received. Dit is done native without libraries. This mostly happens when the app is not active.
- In the broadcastreceiver, read some data from Firebase and set a notification.
- Schedule a new alarm based on data from Firebase.
Within flutter/dart I already got the business logic to fetch the data from Firebase. Obviously I don't want to write al of that again, but now in Java.
I don't want to use the alarmmanager plugin and the local notifciations plugin because the both run in different isolates causing trouble.