当前位置:网站首页>[Flutter] Flutter preloading of mixed development solves the problem of slow page loading for the first time
[Flutter] Flutter preloading of mixed development solves the problem of slow page loading for the first time
2022-07-30 00:46:00 【It-zhai male】
Native
和Flutter
混合开发,通过FlutterFragment
加载Flutter
页面,但Flutter
The page is very slow when it first loads,可以通过Flutter
The way of preloading reduces the time-consuming of the first load.
预备知识:
- 一个
Native
进程只有一个DartVM
- 第一个
FlutterEngine
初始化时,会创建并初始化DartVM
- 一个
DartVM
可以有多个FlutterEngine
,每个FlutterEngine
都运行在自己的Isolate
中,Their memory data is not shared,需要通过Isolatepre-setport(顶级函数)通讯.
实现方式:Flutter
When the page is called for the first time,会初始化Flutter
相关的东西,比如FlutterEngine
,DartVM
等等,So it can be initialized in advanceFlutter
related things to reduce the time-consuming of the first startup:
- 提前预加载
- 全局使用同一个
FlutterEngine
App
每个进程中创建第一个 FlutterEngine
实例的时候会加载 Flutter
引擎的原生库并启动 Dart VM
(VM 存活生命周期跟随进程),随后同进程中其他的 FlutterEngine
将在同一个 VM 实例上运行,The first startup time is mainly spent on loading Flutter The engine's native library and startup Dart VM
.So one can be initialized in advanceFlutterEngine
to reduce the time it takes to load for the first time.
1. 提前预加载
1.1 FlutterHelper
FlutterHelperMainly used for preloadingFlutterEngine,初始化FlutterEngine,获取FlutterEngine.预加载时,它会在Handlerfree timeFlutterEngine初始化.
/** * Created by : yds * Time: 2022-07-27 10:02 */
import android.content.Context;
import android.os.Looper;
import android.os.MessageQueue;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.loader.FlutterLoader;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class FlutterHelper {
private FlutterHelper() {
}
//FlutterEngine缓存的key
public static final String FLUTTER_ENGINE = "flutter_engine";
//flutterInitialization success message
public static final String FLUTTER_ENGINE_INIT_FINISH = "flutter_engine_init_finish";
private static volatile FlutterHelper instance;
public static FlutterHelper getInstance() {
if (instance == null) {
synchronized (FlutterHelper.class) {
if (instance == null) {
instance = new FlutterHelper();
}
}
}
return instance;
}
public void preloadFlutterEngine(Context context) {
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
initFlutterEngine(context);
return true;
}
});
}
public synchronized FlutterEngine initFlutterEngine(Context context){
if (!FlutterEngineCache.getInstance().contains(FLUTTER_ENGINE)) {
//这里建议用FlutterEngineGroup来创建FlutterEngine
FlutterEngine engine = new FlutterEngine(context.getApplicationContext());
System.out.println("flutterEngine:"+engine);
GeneratedPluginRegistrant.registerWith(engine);
//Channel Registration follows engine initialization,否则会有在dart中调用 Channel Timing problems caused by not yet initialized
//FlutterBridge用于将Channel封装,统一提供服务
FlutterBridge.init(engine);
engine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
FlutterEngineCache.getInstance().put(FLUTTER_ENGINE, engine);
return engine;
} else {
return getFlutterEngine();
}
}
public FlutterEngine getFlutterEngine(){
if (isInitFinish()) {
return FlutterEngineCache.getInstance().get(FLUTTER_ENGINE);
} else {
try {
throw new Exception("请先初始化 FlutterEngine!");
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
public boolean isInitFinish() {
return FlutterEngineCache.getInstance().get(FLUTTER_ENGINE) != null;
}
}
1.2 FlutterBridge
FlutterBridgeMainly used for management and Flutter通信的Channel
/** * Created by : yds * Time: 2022-07-27 10:13 */
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.StandardMessageCodec;
public class FlutterBridge implements MethodChannel.MethodCallHandler, BasicMessageChannel.MessageHandler<Object> {
private static final String FLUTTER_MESSAGE_CHANNEL = "message_channel";
private static final String FLUTTER_SEARCH_DATA_CHANNEL = "searchflutterfragment/searchscandata";
private static volatile FlutterBridge instance;
private static List<MethodChannel> mMethodChannels = new ArrayList<>();
public static BasicMessageChannel<Object> mChannel;
private FlutterBridge() {
}
public static FlutterBridge getInstance() {
if (instance == null) {
synchronized (FlutterBridge.class) {
if (instance == null) {
instance = new FlutterBridge();
}
}
}
return instance;
}
public static FlutterBridge init(FlutterEngine flutterEngine) {
MethodChannel channel = new MethodChannel(flutterEngine.getDartExecutor(), FLUTTER_MESSAGE_CHANNEL);
channel.setMethodCallHandler(getInstance());
mChannel = new BasicMessageChannel<>(
flutterEngine.getDartExecutor().getBinaryMessenger(), FLUTTER_SEARCH_DATA_CHANNEL,
StandardMessageCodec.INSTANCE
);
mChannel.setMessageHandler(getInstance());
mMethodChannels.add(channel);
return getInstance();
}
public static <T> void send(@Nullable T message,@Nullable final BasicMessageChannel.Reply<Object> callback){
mChannel.send(message,callback);
}
/** * MethodChannel回调 * <p> * 用于接收从flutter向native发送消息 * * @param call * @param result */
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
}
/** * BasicMessageChannel回调 * <p> * 用于接收从flutter向native发送消息 * * @param message * @param reply */
@Override
public void onMessage(@Nullable Object message, @NonNull BasicMessageChannel.Reply reply) {
}
}
1.3 使用
- 首先在Applicationpreload in
public class MyApplication extends Application {
public void onCreate() {
super.onCreate();
FlutterHelper.getInstance().preloadFlutterEngine(this);
}
}
2. 全局使用同一个FlutterEngine
FlutterHelper
One is created when preloadingFlutterEngine
,然后会将FlutterEngine
存储在FlutterEngineCache
中.FlutterFragment
通过withCachedEngine
获取FlutterHelper
创建的FlutterEngine
,并通过build
方法创建FlutterFragment
.
public class SearchFragment extends Fragment implements OnScanDataListener {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initFlutterEngine();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.search_fragment_layout,container,false);
}
private void initFlutterEngine(){
FlutterFragment flutterFragment = FlutterFragment.withCachedEngine(FlutterHelper.FLUTTER_ENGINE).build();
getChildFragmentManager().beginTransaction().replace(R.id.container,flutterFragment).commit();
}
@Override
public void onScanData(String data) {
FlutterBridge.send(data,new BasicMessageChannel.Reply<Object>() {
@Override
public void reply(@Nullable Object reply) {
if (reply != null) {
long endTime = System.currentTimeMillis();
System.out.println("endTime:" + endTime);
System.out.println("onScanData:" + reply.toString());
}
}
});
}
}
边栏推荐
- 低压差线性稳压器MPQ2013A-AEC1品牌MPS国产替代
- Baidu Intelligent Cloud Zhangmiao: Detailed explanation of enterprise-level seven-layer load balancing open source software BFE
- 二叉排序树(C语言)
- Nacos配置中心用法详细介绍
- Detailed introduction of @RequestParam annotation
- 重新定义分析 - EventBridge 实时事件分析平台发布
- MySql的初识感悟,以及sql语句中的DDL和DML和DQL的基本语法
- 转发和重定向的区别及使用场景
- Worthington dissociating enzyme: detailed analysis of neutral protease (dispase)
- 【Flutter】Flutter inspector 工具使用详解,查看Flutter布局,widget树,调试界面等
猜你喜欢
@RequestParam注解的详细介绍
Chinese semantic matching
[Training DAY16] ALFA [convex hull] [computational geometry]
Worthington用于细胞收获的胰蛋白酶&细胞释放程序
Worthington解离酶:胰蛋白酶及常见问题
Navicat for mysql破解版安装
Worthington dissociating enzyme: detailed analysis of neutral protease (dispase)
循环神经网络(RNN)
Toutiao We-Media Operation: How to Gain 500+ Fans in Toutiao Today?
自媒体人如何打造出爆文?这3种类型的文章最容易爆
随机推荐
STM32——OLED显示实验
The solution to the bug, the test will no longer be blamed
如何在AWS里面的SQL server设置混合登陆
Worthington Dissociation Enzymes: Trypsin and Frequently Asked Questions
基于SSM开发实现校园疫情防控管理系统
自学HarmonyOS应用开发(56)- 用Service保证应用在后台持续运行
【集训DAY16】KC‘s Can 【动态规划】
News text classification
He cell separation technology 丨 basic primary cell separation methods and materials
微信开发者工具设置制表符大小为2
Worthington酶促细胞收获&细胞粘附和收获
【集训DAY16】ALFA【凸壳】【计算几何】
旋转数组的最小数字
自学HarmonyOS应用开发(53)- 获取当前位置
Worthington经过使用测试的细胞分离系统方案
Music theory & guitar skills
BEVDetNet: Bird's Eye View LiDAR Point Cloud based Real-time 3D Object Detection for Autonomous Drivi
Recurrent Neural Network (RNN)
Filebeat如何保证在日志文件被切割(或滚动rolling)时依然正确读取文件
Internship in a group