gpt4 book ai didi

android - android 应用程序类启动时运行 flutter 代码

转载 作者:IT王子 更新时间:2023-10-29 07:07:06 36 4
gpt4 key购买 nike

我正在为 Flutter 制作一个插件,以使用 android native 库处理 fcm 消息。

正如我们所知,当 FCM 收到一条消息时,它会启动应用程序(它是应用程序类)并运行 Application#onCreate block 中的代码,因此我们可以在应用程序启动时运行 native 代码fcm 在后台。

我的问题是,是否可以在应用程序启动时运行 flutter 代码?
例如,如果收到消息:

应用类:

public class Application extends FlutterApplication {

@Override
public void onCreate() {
super.onCreate();
// Start flutter engine
// Invoke a dart code in the Plugin using methodChannel or etc.
}
}

最佳答案

简短回答,

您可以使用它的句柄键在后台调用 Dart 方法。

1。在后台注册你的插件

实现自定义应用程序类(覆盖 FlutterApplication )

public class MyApp extends FlutterApplication implements PluginRegistry.PluginRegistrantCallback {

@Override
public void registerWith(io.flutter.plugin.common.PluginRegistry registry) {
// For apps using FlutterEmbedding v1
GeneratedPluginRegistrant.registerWith(registry);
// App with V2 will initialize plugins automatically, you might need to register your own however
}
}

记得在AndroidManifest中注册类(class)通过添加 android:name=".MyApp"<application>属性。

What is embedding v2?

2。在您的 Flutter 代码中创建一个设置函数作为顶级函数

/// Define this TopLevel or static
void _setup() async {
MethodChannel backgroundChannel = const MethodChannel('flutter_background');
// Setup Flutter state needed for MethodChannels.
WidgetsFlutterBinding.ensureInitialized();

// This is where the magic happens and we handle background events from the
// native portion of the plugin.
backgroundChannel.setMethodCallHandler((MethodCall call) async {
if (call.method == 'handleBackgroundMessage') {
final CallbackHandle handle =
CallbackHandle.fromRawHandle(call.arguments['handle']);
final Function handlerFunction =
PluginUtilities.getCallbackFromHandle(handle);
try {
var dataArg = call.arguments['message'];
if (dataArg == null) {
print('Data received from callback is null');
return;
}
await handlerFunction(dataArg);
} catch (e) {
print('Unable to handle incoming background message.\n$e');
}
}
return Future.value();
});

3。创建一个顶级回调,它将获取后台消息并调用它

_bgFunction(dynamic message) {
// Message received in background
// Remember, this will be a different isolate. So, no widgets
}

4。获取后台函数的handle key和setup通过MethodChannel发送给native

// dart:ui needed
CallbackHandle setup PluginUtilities.getCallbackHandle(_setup);
CallbackHandle handle PluginUtilities.getCallbackHandle(_bgFunction);

_channel.invokeMethod<bool>(
'handleFunction',
<String, dynamic>{
'handle': handle.toRawHandle(),
'setup': setup.toRawHandle()
},
);

5。保存到原生端的SharedPref中

public void onMethodCall(MethodCall call, MethodChannel.Result result) {
String methodName = call.method
if (methodName == "handleFunction") {
long handle = call.argument("handle");
long setup = call.argument("setup");
// save them
}
}

6。后台唤醒后,启动后台隔离

FlutterMain.ensureInitializationComplete(context, null)
val appBundlePath = FlutterMain.findAppBundlePath()
val flutterCallback = FlutterCallbackInformation.lookupCallbackInformation(setupHandleYouHadSaved)

FlutterNativeView backgroundFlutterView = FlutterNativeView(context, true)

val args = FlutterRunArguments()
args.bundlePath = appBundlePath
args.entrypoint = flutterCallback.callbackName
args.libraryPath = flutterCallback.callbackLibraryPath

backgroundFlutterView?.runFromBundle(args)

// Initialize your registrant in the app class
pluginRegistrantCallback?.registerWith(backgroundFlutterView?.pluginRegistry)

7.当您的插件注册后,创建一个后台 channel 并将其传递给

val backgroundChannel = MethodChannel(messenger, "pushe_flutter_background")

8.调用将调用的设置方法并将消息提供给回调

private fun sendBackgroundMessageToExecute(context: Context, message: String) {
if (backgroundChannel == null) {
return
}

val args: MutableMap<String, Any?> = HashMap()
if (backgroundMessageHandle == null) {
backgroundMessageHandle = getMessageHandle(context)
}
args["handle"] = backgroundMessageHandle
args["message"] = message
// The created background channel at step 7
backgroundChannel?.invokeMethod("handleBackgroundMessage", args, null)
}

sendBackgroundMessageToExecute将执行飞镖 _setup函数并传递消息和回调句柄。在第2步中,将调用回调。

Note: There are still certain corner cases you may want to consider (for instance thread waiting and ...). Checkout the samples and see the source code.

有几个项目支持应用在后台启动时后台执行。

FirebaseMessaging

Pushe

WorkManager

关于android - android 应用程序类启动时运行 flutter 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57283923/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com