How to handle android lifecycle in flutter android plugin package

1,943

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.
  }
}
Share:
1,943
Bob
Author by

Bob

Updated on December 08, 2022

Comments

  • Bob
    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?

  • Bob
    Bob over 5 years
    Ok, thanks for the suggestion. So I have to stay with my approach or the AppCompatActivity.