在flutter 1.22版本之后注意使用FlutterEngine
public class MainActivity2 extends AppCompatActivity {
private static final String CHANMEL = "io.flutter.plugins";
private FlutterEngine flutterEngine;
private FlutterView flutterView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
flutterEngine = createFlutterEngine();
MethodChannel nativeChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANMEL);
nativeChannel.setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
if(call.method.equals("goActivity")){
goActivity();
}
}
}
);
//方式一 FutterActivity显示的路由名称为"/",不可设置
//startActivity(FlutterActivity.createDefaultIntent(this));
//方式二、FutterActivity显示的路由名称可设置,每次都创建一个新的FlutterEngine对象
// startActivity(
// FlutterActivity.withNewEngine().initialRoute("route1?{\"id\":123456}").build(this)
// );
// 方式三、FutterActivity显示的路由名称可设置,使用缓存好的FlutterEngine对象
startActivity(
FlutterActivity
.withCachedEngine("my_engine_id")
.build(this)
);
}
public void goActivity(){
Log.i("MainActivity2","测试跳转");
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
}
/**
* 创建可缓存的FlutterEngine
*
* @return
*/
private FlutterEngine createFlutterEngine() {
// 实例化FlutterEngine对象
FlutterEngine flutterEngine = new FlutterEngine(this);
// 设置初始路由
flutterEngine.getNavigationChannel().setInitialRoute("route1?{\"name\":\"" + "测试参数" + "\"}");
// 开始执行dart代码来pre-warm FlutterEngine
flutterEngine.getDartExecutor().executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
);
// 缓存FlutterEngine
FlutterEngineCache.getInstance().put("my_engine_id", flutterEngine);
return flutterEngine;
}
}