如何在Flutter Android插件包中处理Android生命周期

时间:2018-12-21 11:13:24

标签: android flutter android-lifecycle

我需要知道android插件包中flutter应用程序视图的当前状态。

现在,我用https://docs.flutter.io/flutter/widgets/WidgetsBindingObserver-class.html在flutter视图中观察状态,然后将其传递给我的插件。

有时似乎并不完美(第一个事件未在Android上传递),我想直接从android插件获取状态。

在插件中,我可以获得注册商,并且可以注册其活动,但是如何观察其状态?

3 个答案:

答案 0 :(得分:1)

添加了对Android插件中生命周期回调的支持。请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.
  }
}

答案 1 :(得分:0)

Flutter不提供这些生命周期事件的挂钩。

Android Jetpack(以前称为Architecture Components)添加了一种从活动接收生命周期事件的好方法:

Handling Lifecycles with Lifecycle-Aware Components

缺点:仅当活动为AppCompatActivity时有效。 Flutter应用程序通常基于简单的Activity,因此您必须告诉用户使用AppCompatActivity

答案 2 :(得分:0)

Kotlin 版本

在您的插件代码中:

class MyFlutterPlugin: FlutterPlugin, MethodCallHandler, ActivityAware {

/// onAttachedToEngine, onMethod call was hidden due to irrelevance in this example

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        (binding.lifecycle as HiddenLifecycleReference)
                .lifecycle
                .addObserver(LifecycleEventObserver { source, event ->
                    Log.e("Activity state: ", event.toString())
                })

    }
}

不要忘记取消注册并重新附加观察者

<块引用>

onDetachedFromActivity

<块引用>

onReattachedToActivityForConfigChanges

<块引用>

onDetachedFromActivityForConfigChanges

方法