Flutter 调用原生
Android 定义插件
class MyFlutterPlugin implements MethodChannel.MethodCallHandler {
private final Activity activity;
public MyFlutterPlugin(Activity activity) {
this.activity = activity;
}
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("getUser")) {
Integer userId = methodCall.argument("userId");
String mockUser = String.format("{\"name\":\"Wiki\",\"id\":%s}", userId);
result.success(mockUser);
}
}
public static void registerWith(PluginRegistry registry) {
String CHANNEL = "com.example.flutter_app/plugin";
PluginRegistry.Registrar registrar = registry.registrarFor(CHANNEL);
MethodChannel methodChannel = new MethodChannel(registrar.messenger(), CHANNEL);
MyFlutterPlugin myFlutterPlugin = new MyFlutterPlugin(registrar.activity());
methodChannel.setMethodCallHandler(myFlutterPlugin);
}
}
Android 插件注册
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
MyFlutterPlugin.registerWith(this);
}
}
Flutter 调用原生插件
static const myPlugin = const MethodChannel('com.example.flutter_app/plugin');
void getUser() async {
Map<String, Object> map = {"userId": 101};
String result = await myPlugin.invokeMethod("getUser", map);
print(result);
}
原生调用 Flutter
Android 定义插件
class MyFlutterEventPlugin implements EventChannel.StreamHandler {
public EventChannel.EventSink eventSink;
public static MyFlutterEventPlugin registerWith(PluginRegistry registry) {
String CHANNEL = "com.example.flutter_app/event_plugin";
PluginRegistry.Registrar registrar = registry.registrarFor(CHANNEL);
EventChannel eventChannel = new EventChannel(registrar.messenger(), CHANNEL);
MyFlutterEventPlugin myFlutterEventPlugin = new MyFlutterEventPlugin();
eventChannel.setStreamHandler(myFlutterEventPlugin);
return myFlutterEventPlugin;
}
@Override
public void onListen(Object o, EventChannel.EventSink eventSink) {
this.eventSink = eventSink;
}
@Override
public void onCancel(Object o) {
}
}
Android 插件注册 & 调用
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
MyFlutterPlugin.registerWith(this);
MyFlutterEventPlugin eventPlugin = MyFlutterEventPlugin.registerWith(this);
new Thread(new Runnable() {
@Override
public void run() {
int counter = 0;
while (true){
try {
if (eventPlugin.eventSink != null) {
eventPlugin.eventSink.success(counter++);
}
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
eventPlugin.eventSink.error("计时器异常","计时器异常",e.getMessage());
}
}
}
}).start();
}
}
Flutter 注册监听器接收来自原生的消息
static const myEventPlugin = const EventChannel('com.example.flutter_app/event_plugin');
@override
void initState() {
super.initState();
myEventPlugin.receiveBroadcastStream().listen(_onEvent, onError: _onError);
}
void _onEvent(Object event) {
print("onEvent: $event");
}
void _onError(Object error) {
print("onError: $error");
}
完整代码
Android
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
MyFlutterPlugin.registerWith(this);
MyFlutterEventPlugin eventPlugin = MyFlutterEventPlugin.registerWith(this);
new Thread(new Runnable() {
@Override
public void run() {
int counter = 0;
while (true){
try {
if (eventPlugin.eventSink != null) {
eventPlugin.eventSink.success(counter++);
}
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
eventPlugin.eventSink.error("计时器异常","计时器异常",e.getMessage());
}
}
}
}).start();
}
}
class MyFlutterPlugin implements MethodChannel.MethodCallHandler {
private final Activity activity;
public MyFlutterPlugin(Activity activity) {
this.activity = activity;
}
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("getUser")) {
Integer userId = methodCall.argument("userId");
String mockUser = String.format("{\"name\":\"Wiki\",\"id\":%s}", userId);
result.success(mockUser);
}
}
public static void registerWith(PluginRegistry registry) {
String CHANNEL = "com.example.flutter_app/plugin";
PluginRegistry.Registrar registrar = registry.registrarFor(CHANNEL);
MethodChannel methodChannel = new MethodChannel(registrar.messenger(), CHANNEL);
MyFlutterPlugin myFlutterPlugin = new MyFlutterPlugin(registrar.activity());
methodChannel.setMethodCallHandler(myFlutterPlugin);
}
}
class MyFlutterEventPlugin implements EventChannel.StreamHandler {
public EventChannel.EventSink eventSink;
public static MyFlutterEventPlugin registerWith(PluginRegistry registry) {
String CHANNEL = "com.example.flutter_app/event_plugin";
PluginRegistry.Registrar registrar = registry.registrarFor(CHANNEL);
EventChannel eventChannel = new EventChannel(registrar.messenger(), CHANNEL);
MyFlutterEventPlugin myFlutterEventPlugin = new MyFlutterEventPlugin();
eventChannel.setStreamHandler(myFlutterEventPlugin);
return myFlutterEventPlugin;
}
@Override
public void onListen(Object o, EventChannel.EventSink eventSink) {
this.eventSink = eventSink;
}
@Override
public void onCancel(Object o) {
}
}
Flutter 代码
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyHomePageState extends State<MyHomePage> {
static const myPlugin = const MethodChannel('com.example.flutter_app/plugin');
static const myEventPlugin = const EventChannel('com.example.flutter_app/event_plugin');
@override
void initState() {
super.initState();
myEventPlugin.receiveBroadcastStream().listen(_onEvent, onError: _onError);
}
void _onEvent(Object event) {
print("onEvent: $event");
}
void _onError(Object error) {
print("onError: $error");
}
void getUser() async {
Map<String, Object> map = {"userId": 101};
String result = await myPlugin.invokeMethod("getUser", map);
print(result);
}
@override
Widget build(BuildContext context) {
return new Center(
child: new RaisedButton(
onPressed: () {
getUser();
},
child: new Text("调用原生"),
),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return new MyHomePageState();
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Welcome to Flutter',
home: new Scaffold(
appBar: new AppBar(
title: new Text('Welcome to Flutter'),
),
body: MyHomePage(),
),
);
}
}
网友评论