flutter-从android活动调用方法

时间:2020-03-18 08:55:41

标签: flutter

我试图在Flutter-Android上进行应用程序到应用程序的通信。

首先,Android应用程序(A)绑定了Flutter服务,而Android Service(B)绑定了Flutter服务。 然后,A对B和B的呼叫开始活动。 其次,使用MethodChannel在Flutter上进行活动调用方法。 但是我遇到了例外。

如何在以Android服务开头的Android活动上调用flutter方法。

例外

E/flutter (12950): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method getDatabasesPath on channel com.tekartik.sqflite)

E/flutter (12950): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method getAll on channel plugins.flutter.io/shared_preferences)

MyService.kt

class MyService : Service() {
    private lateinit var mMessenger: Messenger

    internal class IncomingHandler(context: Context,
                                   private val applicationContext: Context = context.applicationContext
    ) : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)

            when (msg.what) {
                WHAT_REQ_VP -> {
                    applicationContext.startActivity(Intent(applicationContext, 
                        TempActivity::class.java)
                            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
                }
            }
        }
    }

    override fun onBind(intent: Intent): IBinder {
        mMessenger = Messenger(IncomingHandler(this))
        return mMessenger.binder
    }
}

TempActivity.kt

class TempActivity : FlutterActivity() {
    private lateinit var channel: MethodChannel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_temp)

        val backgroundFlutterView = FlutterNativeView(baseContext, true)
        channel = MethodChannel(backgroundFlutterView, "com.example.test")

        GeneratedPluginRegistrant.registerWith(this)

        channel.setMethodCallHandler { call, result -> run {
            when (call.method) {
                "result" -> {
                    print(call.argument<String>("result"))
                }
                else -> {}
            }
        } }

        findViewById<Button>(R.id.btn_confirm).setOnClickListener {
            val arguments = HashMap<String, String>()
            arguments["message"] = "From Android"
            channel.invokeMethod("test", arguments)
        }
    }
}

temp.dart

import 'package:flutter/services.dart';

class Temp {
  static final _singleton = Temp._internal();
  static const MethodChannel _channel = const MethodChannel('com.example.test');

  factory Temp() {
    return _singleton;
  }

  Temp._internal() {
    _channel.setMethodCallHandler(_handleMethod);
  }

  _handleMethod(MethodCall call) {
    switch (call.method) {
      case 'test':
        print('_handleMethod: ${call.method}');
        _channel.invokeMethod('result', 'Result from flutter client');
    }
  }
}

0 个答案:

没有答案