Android Mopub Banner SDK8
跳至導覽
跳至搜尋
請建立一個Class並繼承Mopub所提供的BaseAd
Class實作內容如下:
package com.taiwanmobile.pt.adp.mediation
import android.app.Activity
import android.content.Context
import android.view.View
import com.mopub.common.LifecycleListener
import com.mopub.common.util.Views
import com.mopub.mobileads.AdData
import com.mopub.mobileads.BaseAd
import com.mopub.mobileads.MoPubErrorCode
import com.taiwanmobile.pt.adp.view.*
// 需將本class的完整類別名稱 com.taiwanmobile.pt.adp.mediation.TAMediaMopubBanner 填入後台的Custom Event Class欄位
class TAMediaMopubBanner : BaseAd() {
private var adUnitId = ""
private var adView: TWMAdView? = null
override fun onInvalidate() {
// Called when MoPubView is being invalidated or destroyed
Views.removeFromParent(adView)
adView?.setAdListener(null)
adView?.destroy()
}
private fun checkAdSize(width: Int, height: Int): TWMAdSize {
return if (width == TWMAdSize.BANNER.width && height == TWMAdSize.BANNER.height) {
TWMAdSize.BANNER
} else if (width == TWMAdSize.BANNER_300X250.width && height == TWMAdSize.BANNER_300X250.height) {
TWMAdSize.BANNER_300X250
} else if (width == TWMAdSize.BANNER_1200X627.width && height == TWMAdSize.BANNER_1200X627.height) {
TWMAdSize.BANNER_1200X627
} else if (width == TWMAdSize.SMART_BANNER.width && height == TWMAdSize.SMART_BANNER.height) {
TWMAdSize.SMART_BANNER
} else {
TWMAdSize.BANNER
}
}
override fun getLifecycleListener(): LifecycleListener? {
return null
}
override fun getAdNetworkId(): String {
return adUnitId
}
override fun checkAndInitializeSdk(launcherActivity: Activity, adData: AdData): Boolean {
return false
}
override fun load(context: Context, adData: AdData) {
try {
val width = adData.extras[KEY_MOPUB_WIDTH]?.toInt() ?: 0
val height = adData.extras[KEY_MOPUB_HEIGHT]?.toInt() ?: 0
adUnitId = adData.extras.getValue(KEY_AD_UNIT_ID)
//後台設定的adUnitId會透過此Key值取得
adView = TWMAdView(context as Activity, checkAdSize(width, height), adUnitId)
adView?.adListener = object : TWMAdViewListener {
override fun onReceiveAd(ad: TWMAd) {
mLoadListener?.onAdLoaded()
}
override fun onFailedToReceiveAd(ad: TWMAd, errorCode: TWMAdRequest.ErrorCode) {
mLoadListener?.onAdLoadFailed(MoPubErrorCode.NO_FILL)
}
override fun onPresentScreen(ad: TWMAd) {
mInteractionListener?.onAdImpression()
}
override fun onDismissScreen(ad: TWMAd) {
mInteractionListener?.onAdDismissed()
}
override fun onLeaveApplication(ad: TWMAd) {
mInteractionListener?.onAdClicked()
}
}
adView?.loadAd(TWMAdRequest())
} catch (e:Exception) {
e.printStackTrace()
}
}
override fun getAdView(): View? {
return adView
}
companion object {
private const val TAG = "TAMediaMopubBanner"
private const val KEY_AD_UNIT_ID = "adUnitId"
private const val KEY_MOPUB_WIDTH = "com_mopub_ad_width"
private const val KEY_MOPUB_HEIGHT = "com_mopub_ad_height"
}
}
MoPub後台設定
- 將上述class完整package設定置MoPub Custom event class
- 將TAmedia所提供的adUnitId設定於MoPub Custom event data(必要)
- com_mopub_ad_width為廣告寬(必要)
- com_mopub_ad_height為廣告高(必要)