// 定义通道
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 通道名称必须和flutter一致
        methodChannel = new MethodChannel(getFlutterEngine().getDartExecutor().getBinaryMessenger(), "com.pad.getcode/text"); // 通道名称
    }

    // 发送信息
    private static void sendCode(String msg) {
        Map<String, String> map = new HashMap<>();
        map.put("content", msg);
        methodChannel.invokeMethod("showText", map, new MethodChannel.Result() {
            @Override
            public void success(Object o) {
                Log.d(TAG, "发送成功 ==> " + msg);
            }

            @Override
            public void error(String errorCode, String errorMsg, Object errorDetail) {
                Log.d(TAG, "发送错误代码");
            }

            @Override
            public void notImplemented() {
                Log.d(TAG, "未实现");
            }
        });
    }

    //定义通道 
    static const platformChannel = const MethodChannel('com.pad.getcode/text');  //通道名称和java中一致 

    // 接收消息
    void initState() {
        super.initState();
        platformChannel.setMethodCallHandler((methodCall) async {
        switch (methodCall.method) {
            case 'showText':
            String content = await methodCall.arguments['content'];
            if (content != null && content.isNotEmpty) {
                print(content); //来自安卓的消息
                return 'success';
            } else {
                throw PlatformException(
                code: 'error',
                message: '解码信息接收失败',
                );
            }
            break;
            default:
            throw MissingPluginException();
        }
    });
  }
上一篇 下一篇