我正在为Flutter开发具有背景功能的插件。
最近,我面临着一个关系出头 Flutter 的Android嵌入在android_alarm_manager插件。
README
说的一部分:
对于Flutter Android Embedding V1,必须为后台服务提供回调,以使用背景隔离注册插件。
Flutter发布了其Android嵌入的新版本。这是负责将Flutter集成到Android应用程序中的Android代码。它包括类,如FlutterActivity
,FlutterFragment
,FlutterView
,和FlutterEngine
。Android v2嵌入包括对标准Android生命周期事件的支持,以及Flutter执行与Android UI的分离,这在Android v1嵌入中是缺少的。在开发v2 Android嵌入的过程中,很明显,现有的Flutter插件API不足以处理v2 Android嵌入的新功能。需要一个新的Android插件API。
在旧的Android v1嵌入版本中,所有插件都在Android应用程序的一开始就进行了初始化和配置,并且只有一种Flutter体验。在v2嵌入中,我们不假设插件何时初始化,并且每个FlutterEngine插件必须初始化一次。因此,所有适用于Android的Flutter插件现在都必须支持实例化而不是静态初始化,并且它们必须支持与FlutterEngine进行连接和分离。以下代码示例演示了旧的v1插件初始化实现和新的v2插件初始化过程之间的区别。
旧插件初始化
class MyOldPlugin {
public static void registerWith(PluginRegistrar registrar) {
// Obtain any references that the plugin requires from the
// registrar.
//
// This plugin is now considered "initialized" and "attached"
// to a Flutter experience.
}
}
新插件初始化
class MyNewPlugin implements FlutterPlugin {
public MyNewPlugin() {
// All Android plugin classes must support a no-args
// constructor. A no-arg constructor is provided by
// default without declaring one, but we include it here for
// clarity.
//
// At this point your plugin is instantiated, but it
// isn't attached to any Flutter experience. You should not
// attempt to do any work here that is related to obtaining
// resources or manipulating Flutter.
}
@override
public void onAttachedToFlutterEngine(FlutterPluginBinding binding) {
// Your plugin is now attached to a Flutter experience
// represented by the given FlutterEngine.
//
// You can obtain the associated FlutterEngine with
// binding.getFlutterEngine()
//
// You can obtain a BinaryMessenger with
// binding.getBinaryMessenger()
//
// You can obtain the Application context with
// binding.getApplicationContext()
//
// You cannot access an Activity here because this
// FlutterEngine is not necessarily displayed within an
// Activity. See the ActivityAware interface for more info.
}
@override
public void onDetachedFromFlutterEngine(FlutterPluginBinding binding) {
// Your plugin is no longer attached to a Flutter experience.
// You need to clean up any resources and references that you
// established in onAttachedToFlutterEngine().
}
}
此外,你的插件不得依赖onAttachedToFlutterEngine()中的Activity引用。仅仅因为你的插件已附加到Flutter体验上,并不意味着Flutter体验正在活动中显示。这是新旧插件API之间最重要的区别之一。在旧的v1插件API中,插件作者可能依赖于活动可立即且永久可用。这不再是事实。
有关更多信息,请参见https://medium.com/flutter/modern-flutter-plugin-development-4c3ee015cf5a