如果插件需要與UI 進行互動,例如請求權限或更改Android UI ,那麼您就需要一些附加步驟來構建您的插件。您必須實現 ActivityAware,Flutter 提供了 ActivityAware 用於 Activity 的生命週期管理和獲取
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.
}
}
onAttachedToEngine
和onDetachedFromEngine
是FlutterPlugin
的介面方法,是flutter新的載入Plugin 的方式,onAttachedToActivity
和onDetachedFromActivity
是ActivityAware
的介面方法,主要是用於獲取當前flutter 頁面所處的Activity.
我們可以將Plugin 設計將MethodHandler
在 onAttachedToEngine
方法中被初始化和構建,在 onDetachedFromEngine
方法中釋放;同時 Activity 相關的四個實現方法也提供了相應的操作邏輯