最终运行效果:
点击flutter和android界面的Text(TextView)之后的效果显示:
android代码:
- Java代码
public class MainActivity extends AppCompatActivity {
FlutterEngine mFlutter2Engine;
FlutterView mFlutter2View;
MethodChannel mFlutter2MethodChannel;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mFlutter2MethodChannel != null) {
//点击button2,安卓通过消息通道调用flutter方法
mFlutter2MethodChannel.invokeMethod("getFlutterMethod", null, new MethodChannel.Result() {
@Override
public void success(Object result) {
if (result != null) {
String str = result.toString();
tv.setText(str);
System.out.println("android调用Flutter - getFlutterMethod");
}
}
@Override
public void error(String errorCode, String errorMessage, Object errorDetails) {
}
@Override
public void notImplemented() {
}
});
}
}
});
initFlutterEngine();
mFlutter2View = createFlutterView();
mFlutter2View.attachToFlutterEngine(mFlutter2Engine);
}
private FlutterView createFlutterView() {
FlutterView flutterView = new FlutterView(this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
RelativeLayout rl = findViewById(R.id.rl);
rl.addView(flutterView, lp);
rl.setVisibility(View.INVISIBLE);
FlutterUiDisplayListener listener = new FlutterUiDisplayListener() {
@Override
public void onFlutterUiDisplayed() {
rl.setVisibility(View.VISIBLE);
}
@Override
public void onFlutterUiNoLongerDisplayed() {
}
};
flutterView.addOnFirstFrameRenderedListener(listener);
return flutterView;
}
private void initFlutterEngine() {
mFlutter2Engine = FlutterEngineCache.getInstance().get("flutter2");
if (mFlutter2Engine == null) {
mFlutter2Engine = new FlutterEngine(this);
initChannel(mFlutter2Engine);
mFlutter2Engine.getDartExecutor().executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
);
FlutterEngineCache.getInstance().put("flutter2", mFlutter2Engine);
}
}
/**
* 创建flutter消息通道
* @param flutter2Engine
*/
private void initChannel(FlutterEngine flutter2Engine) {
mFlutter2MethodChannel = new MethodChannel(flutter2Engine.getDartExecutor(), "flutter2/flutter2Java");
mFlutter2MethodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call == null || result == null) {
if (result != null) {
result.error("-1", "MethodCall is null", new Exception("MethodCall is null"));
}
return;
}
//flutter调用android的getJavaMethod方法
if ("getJavaMethod".equals(call.method)) {
result.success("flutter调用android - getJavaMethod方法成功");
} else {
result.success(" unKnow method");
}
}
});
}
@Override
protected void onResume() {
super.onResume();
mFlutter2Engine.getLifecycleChannel().appIsResumed();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onRestart() {
super.onRestart();
}
@Override
protected void onPause() {
super.onPause();
mFlutter2Engine.getLifecycleChannel().appIsInactive();
}
@Override
protected void onStop() {
super.onStop();
mFlutter2Engine.getLifecycleChannel().appIsPaused();
}
@Override
protected void onDestroy() {
super.onDestroy();
FlutterEngineCache.getInstance().remove("flutter2");
mFlutter2View = null;
}
}
- android xml代码
flutter代码
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyHomePage());
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
String str ='我是flutter界面Text';
static const platform = const MethodChannel("flutter2/flutter2Java");
Future _getJavaMethod() async {
try {
print("flutter调用android - getJavaMethod");
// 在通道上调用此方法
final String intValue = await platform.invokeMethod("getJavaMethod");
str = '$intValue';
} on Exception catch (e) {
str = "Failed to getJavaMethod: '${e.toString()}'.";
}
setState(() {
print("dart -setState");
});
}
//flutter设置回调
Future _platformCallHandler(MethodCall call) async {
switch (call.method) {
case "getFlutterMethod":
return "android调用Flutter - getFlutterMethod'方法成功";
default:
return "call.method not getFlutterName";
}
}
@override
Widget build(BuildContext context) {
platform.setMethodCallHandler(_platformCallHandler);
return new MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
InkWell(
child: Text(str,
),
onTap: ()async {
_getJavaMethod();
},
),
],
),
),
)
);
}
}
如果想要跳转到不同的flutter界面,只需要在创建FlutterEngine的时候,设置不同的路由标志就行了,然后在flutter界面根据设置的路由标志,加载不同的widget。
代码如下:
- android
private void initFlutterEngine() {
mFlutter2Engine = FlutterEngineCache.getInstance().get("flutter2");
if (mFlutter2Engine == null) {
mFlutter2Engine = new FlutterEngine(this);
//设置跳转不同的flutter界面的路由标志
mFlutter2Engine.getNavigationChannel().setInitialRoute("route2");
initChannel(mFlutter2Engine);
mFlutter2Engine.getDartExecutor().executeDartEntrypoint(
DartExecutor.DartEntrypoint.createDefault()
);
FlutterEngineCache.getInstance().put("flutter2", mFlutter2Engine);
}
}
- flutter
void main(){
//flutter入口代码,通过路由标识,加载不同的布局
var defaultRouteName = window.defaultRouteName;
if("route1" == defaultRouteName){
runApp(MyHomePage());
} else if("route2" == defaultRouteName){
runApp(Page1());
}else if("route3" == defaultRouteName){
runApp(Page2());
}
}