You need to enable JavaScript to run this app. FlutterMain已被废弃,其替代方案是什么,如何在后台服务中执行Dart回调?
优惠活动
大模型
产品
解决方案
定价
更多

FlutterMain已被废弃,其替代方案是什么,如何在后台服务中执行Dart回调?

Flutter Android 废弃FlutterMain后执行后台Dart回调的实现方案

原代码中FlutterMain.findAppBundlePath()方法废弃后,官方推荐使用FlutterInjector类替代获取App bundle路径,具体修改方式如下:

核心修改点

  1. 导入官方提供的FlutterInjector类,无需额外引入第三方依赖
  2. 替换原有bundle路径获取逻辑

修改后完整代码片段

import io.flutter.FlutterInjector;

public class PushService extends JobIntentService implements MethodCallHandler {
    private static FlutterEngine backgroundFlutterEngine = null;

    private void startPushService(Context context) {
        synchronized (serviceStarted) {
            if (backgroundFlutterEngine == null) {
                final Long callbackHandle = PushStore.getInstance().getPreferenceLongValue(
                        PushPlugin.CALLBACK_DISPATCHER_ID, 0L);
                if (callbackHandle == 0L) {
                    Log.e(TAG, "Fatal: no callback registered.");
                    return;
                }

                final FlutterCallbackInformation callbackInfo =
                        FlutterCallbackInformation.lookupCallbackInformation(callbackHandle);
                if (callbackInfo == null) {
                    Log.e(TAG, "Fatal: failed to find callback info.");
                    return;
                }
                Log.i(TAG, "Starting PushService...");
                backgroundFlutterEngine = new FlutterEngine(context);
                // 替换原有FlutterMain相关逻辑
                FlutterInjector injector = FlutterInjector.instance();
                String appBundlePath = injector.flutterLoader().findAppBundlePath();
                DartCallback args = new DartCallback(context.getAssets(), appBundlePath, callbackInfo);
                backgroundFlutterEngine.getDartExecutor().executeDartCallback(args);
                // 原有剩余逻辑保留
                ...
            }
        }
    }
}

注意事项

  • 新的路径获取逻辑自动适配debug、release等不同编译模式,与原有FlutterMain的逻辑完全兼容,无需额外适配
  • 该方案适用于Flutter 2.10及以上所有版本,3.0+版本可直接使用
  • 后台任务执行完成后建议及时调用backgroundFlutterEngine.destroy()销毁引擎实例,避免不必要的内存占用

内容的提问来源于stack exchange,提问作者ccd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 06:57:04