相信看过官方更新日志的小伙伴都知道新版本的flutter和Android原生交互有一些改变,主要在以下部分
1.自定义的Plugin类需要实现FlutterPlugin的接口,并实现以下两个方法
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { //注册,等同于原来的registerWith
final MethodChannel channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "flutter_wx");
channel.setMethodCallHandler(new FlutterWxPlugin());
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
}
2.获取Flutter传递过来的数据(方法名)需要实现MethodCallHandler(和之前版本的一样)
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
Log.d(TAG, "onMethodCall:" + activity);
Toast.makeText(activity, "TestActivity", Toast.LENGTH_SHORT).show();
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
} else {
result.notImplemented();
}
}
3.现在有一个需求就是需要在onMethodCall方法中获取activity对象,新版本给我们提供了新的接口让我更好的来处理Plugin和Activity的一些交互,所以我们实现ActivityAware这个接口,重写下面的方法,在onAttachedToActivity中我们可以通过binding.getActivity()获取当前的activity对象,然后赋给我们定义的全局变量,这个时候问题来了,我们在onMethodCall方法中得到的activity的值始终为null
@Override
public void onAttachedToActivity(ActivityPluginBinding binding) {
Log.d(TAG, "onAttachedToActivity");
this.activity = binding.getActivity();
}
@Override
public void onDetachedFromActivityForConfigChanges() {
}
@Override
public void onReattachedToActivityForConfigChanges(ActivityPluginBinding binding) {
}
@Override
public void onDetachedFromActivity() {
}
4.解决方法,修改 onAttachedToEngine方法中的channel.setMethodCallHandler(new FlutterWxPlugin())为 channel.setMethodCallHandler(this);
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { //注册,等同于原来的registerWith
final MethodChannel channel = new MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "flutter_wx");
channel.setMethodCallHandler(this);//修改此处为this
}
网友评论