|
|
@@ -5,18 +5,24 @@ import android.os.Looper
|
|
|
import com.atmob.keyboard_android.constant.PluginConfig
|
|
|
import com.atmob.keyboard_android.util.JsonUtil
|
|
|
import com.atmob.keyboard_android.util.LogUtil
|
|
|
+import com.atmob.keyboard_android.util.bridge.channel.ProxyMethodChannel
|
|
|
import com.atmob.keyboard_android.util.bridge.model.base.CallResult
|
|
|
import io.flutter.embedding.engine.FlutterEngine
|
|
|
import io.flutter.plugin.common.MethodChannel
|
|
|
+import java.util.concurrent.atomic.AtomicInteger
|
|
|
|
|
|
/**
|
|
|
* Flutter方法调用者
|
|
|
*/
|
|
|
class FlutterMethodCaller {
|
|
|
+ companion object {
|
|
|
+ private const val MAX_RETRY_COUNT = 3
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 用于与 Flutter 端通信的 MethodChannel
|
|
|
*/
|
|
|
- private lateinit var mMethodChannel: MethodChannel
|
|
|
+ private lateinit var mMethodChannel: ProxyMethodChannel
|
|
|
|
|
|
/**
|
|
|
* 主线程Handler,用于Flutter回调安卓端时,在主线程回调外部
|
|
|
@@ -27,7 +33,7 @@ class FlutterMethodCaller {
|
|
|
* 初始化
|
|
|
*/
|
|
|
fun init(engine: FlutterEngine) {
|
|
|
- mMethodChannel = MethodChannel(
|
|
|
+ mMethodChannel = ProxyMethodChannel(
|
|
|
engine.dartExecutor.binaryMessenger,
|
|
|
PluginConfig.FLUTTER_METHOD_CHANNEL_NAME
|
|
|
)
|
|
|
@@ -50,7 +56,8 @@ class FlutterMethodCaller {
|
|
|
onSuccess: ((resultObj: T) -> Unit)? = null,
|
|
|
onFail: ((errorCode: Int, errorMsg: String) -> Unit)? = null
|
|
|
) {
|
|
|
- mMethodChannel.invokeMethod(methodName, args, object : MethodChannel.Result {
|
|
|
+ val retryCount = AtomicInteger(0)
|
|
|
+ val result = object : MethodChannel.Result {
|
|
|
override fun success(result: Any?) {
|
|
|
if (isReturnJson) {
|
|
|
val resultJson = result.toString()
|
|
|
@@ -96,25 +103,35 @@ class FlutterMethodCaller {
|
|
|
|
|
|
override fun notImplemented() {
|
|
|
LogUtil.d("方法名:${methodName},调用失败,Flutter未实现该方法")
|
|
|
- runOnUIThread {
|
|
|
- onFail?.invoke(-1, "method not implemented")
|
|
|
+ val currentRetryCount = retryCount.incrementAndGet()
|
|
|
+ // 到达重试最大次数,回调结果
|
|
|
+ if (currentRetryCount >= MAX_RETRY_COUNT) {
|
|
|
+ runOnUIThread {
|
|
|
+ onFail?.invoke(-100, "")
|
|
|
+ }
|
|
|
+ } else {
|
|
|
+ // 重试
|
|
|
+ runOnUIThread(300, callback = {
|
|
|
+ mMethodChannel.invokeMethod(methodName, args, this)
|
|
|
+ })
|
|
|
}
|
|
|
}
|
|
|
- })
|
|
|
+ }
|
|
|
+ mMethodChannel.invokeMethod(methodName, args, result)
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 在主线程运行回调
|
|
|
*/
|
|
|
- private fun runOnUIThread(callback: () -> Unit) {
|
|
|
+ private fun runOnUIThread(delayTime: Long = 0, callback: () -> Unit) {
|
|
|
// 如果已经在主线程了,直接回调
|
|
|
if (Looper.getMainLooper().thread == Thread.currentThread()) {
|
|
|
callback.invoke()
|
|
|
} else {
|
|
|
// 不在主线程,则切到主线程后,再回调
|
|
|
- mMainHandler.post {
|
|
|
+ mMainHandler.postDelayed({
|
|
|
callback.invoke()
|
|
|
- }
|
|
|
+ }, delayTime)
|
|
|
}
|
|
|
}
|
|
|
}
|