Flutter Android 中如何获取 Activity?

问题描述 投票:0回答:1

我正在创建 Flutter 插件,该插件使用 Kotlin 和 Swift 在 Flutter UI 中显示横幅和插页式广告。当尝试使用 Kotlin 显示插页式广告时,我需要使用 Activity,我正在尝试使用

onAttachedToActivity
,但我的 Activity 变量始终为 null。

我检查了与此相关的其他问题,但他们要么使用

configureFlutterEngine
,要么只有一门课程。

我使用

init
方法而不是
FlutterEngine
在 Kotlin 的 Flutter UI 中添加布局,稍后用于显示横幅(横幅工作没有任何问题,所以我删除了该代码部分)。我添加了用于显示广告的所有三个 Kotlin 类。

插件类:

class SecondPluginAttemptPlugin: FlutterPlugin {

  private var Tag: String = "MyTag"
  override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    Log.d(Tag, "SecondPluginAttemptPlugin attached to Flutter engine")
    try {
      binding.platformViewRegistry.registerViewFactory(
        "plugins.example/second_attempt", MyViewFactory(binding.binaryMessenger)
      )
      Log.d(Tag, "MyViewFactory registered")
    } catch (e: Exception) {
      Log.e(Tag, "Error during registration: ${e.message}")
    }
  }
  
  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    Log.d(Tag, "SecondPluginAttemptPlugin detached from Flutter engine")
  }
}

工厂类:

class MyViewFactory (private val messenger: BinaryMessenger): PlatformViewFactory(StandardMessageCodec.INSTANCE){
        override fun create(context: Context, id: Int, o: Any?) : PlatformView {
            return MyView(context, messenger, id)
        }
}

还有我的视图类

class MyView internal constructor(context: Context, messenger: BinaryMessenger, id: Int) :
    PlatformView, MethodCallHandler, ActivityAware {
    private var applicationContext: Context = context
    private var messageLayout: ViewGroup?
    private val channel = MethodChannel(messenger, "plugins.example/second_attempt_$id")

    private var mAdManagerInterstitialAd: AdManagerInterstitialAd? = null
    private lateinit var myActivity: Activity
    private val Tag = "MyTag"

    init {
        try {
            Log.d(Tag, "init")
            channel.setMethodCallHandler(this)

        } catch (e: Exception) {
            Log.e(Tag, "Error setting method call handler: $e")
        }
        messageLayout = FrameLayout(applicationContext)
        messageLayout?.setBackgroundColor(Color.BLUE)
        val params = FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )
        params.gravity = Gravity.BOTTOM
    }

    override fun getView(): View? {
        Log.d(Tag, "View")
        return messageLayout
    }

    override fun dispose() {
        Log.d(Tag, "Dispose")
        messageLayout = null
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        Log.d(Tag, "onMethodCall " )
        when (call.method) {
            "setParams" -> settingParameters(call)
            else -> result.notImplemented()
        }
    }

    private fun settingParameters(call: MethodCall) {
        val arguments = call.arguments as? Map<*, *>
        val accountId = arguments?.get("prebidAccountId") as? String ?: ""
        val adUnitId = arguments?.get("adUnitId") as? String ?: ""
        val configId = arguments?.get("configId") as? String ?: ""
        val width = arguments?.get("width") as? Int ?: 0
        val height = arguments?.get("height") as? Int ?: 0

        messageLayout?.removeAllViews()

        val textView = TextView(applicationContext)
        textView.setTextColor(Color.RED)
        textView.gravity = Gravity.CENTER

        //Skipped some code used to check if variables are not empty and if they are - a message is displayed inside messageLayout

        createInterstitial(adUnitId)
    }

    private fun createInterstitial(AD_UNIT_ID: String) {
        val adRequest = AdManagerAdRequest.Builder().build()

        AdManagerInterstitialAd.load(applicationContext, AD_UNIT_ID, adRequest,
            object : AdManagerInterstitialAdLoadCallback() {
                override fun onAdLoaded(interstitialAd: AdManagerInterstitialAd) {
                    mAdManagerInterstitialAd = interstitialAd
                    Log.i(Tag, "onAdLoaded")
                    showInterstitial()
                }

                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    Log.d(Tag, loadAdError.toString())
                    mAdManagerInterstitialAd = null
                }
            })
    }

    private fun showInterstitial() {
        if (mAdManagerInterstitialAd != null) {
            mAdManagerInterstitialAd?.show(myActivity)
        } else {
            Log.d("TAG", "The interstitial ad wasn't ready yet.")
        }
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        myActivity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {
        TODO("Not yet implemented")
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        TODO("Not yet implemented")
    }

    override fun onDetachedFromActivity() {
        TODO("Not yet implemented")
    }
}
flutter kotlin interstitial
1个回答
0
投票

使用ActivityAware

import io.flutter.embedding.engine.plugins.activity.ActivityAware



class SecondPluginAttemptPlugin : FlutterPlugin, ActivityAware {
    private var activity: Activity? = null

    //* * *

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
    }
    override fun onReattachedToActivityForConfigChanges(binding:ActivityPluginBinding) {
        activity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {}

    override fun onDetachedFromActivity() {}
}
© www.soinside.com 2019 - 2024. All rights reserved.