How to handle android lifecycle in flutter android plugin package
Solution 1
Flutter doesn't provide hooks for these lifecycle events.
Android Jetpack (formerly Architecture Components) added a nice way to receive lifecycle events from an activity:
Handling Lifecycles with Lifecycle-Aware Components
Downside: It only works when the activity is an AppCompatActivity
. Flutter apps are usually based on a simple Activity
, so you have to tell your users to use an AppCompatActivity
instead.
Solution 2
Support for lifecycle callbacks in the android plugin is added. Please refer
public class MyPlugin implements FlutterPlugin, ActivityAware {
//...normal plugin behavior is hidden...
@Override
public void onAttachedToActivity(ActivityPluginBinding activityPluginBinding) {
// TODO: your plugin is now attached to an Activity
}
@Override
public void onDetachedFromActivityForConfigChanges() {
// TODO: the Activity your plugin was attached to was
// destroyed to change configuration.
// This call will be followed by onReattachedToActivityForConfigChanges().
}
@Override
public void onReattachedToActivityForConfigChanges(ActivityPluginBinding activityPluginBinding) {
// TODO: your plugin is now attached to a new Activity
// after a configuration change.
}
@Override
public void onDetachedFromActivity() {
// TODO: your plugin is no longer associated with an Activity.
// Clean up references.
}
}
Bob
Updated on December 08, 2022Comments
-
Bob over 1 year
I need to know the current state of the flutter app view in an android plugin package.
For now, I observe the state in the flutter view with https://docs.flutter.io/flutter/widgets/WidgetsBindingObserver-class.html and pass it then to my plugin.
As this seems sometimes not perfect (the first event is not passed on Android) I would like to get the state directly from the android plugin.
In the plugin I get the registrar and can its activity, but how do I observe the state of it?
-
Arto Bendiken almost 5 yearsDuplicate question also at: stackoverflow.com/q/56974192
-
-
Bob over 5 yearsOk, thanks for the suggestion. So I have to stay with my approach or the AppCompatActivity.