package jackall.overlaymulticounter.utils import android.content.Context import android.util.Log import android.widget.FrameLayout import com.google.android.gms.ads.* import jackall.overlaymulticounter.Const import jackall.overlaymulticounter.common.PreferenceKeys import jackall.overlaymulticounter.common.PreferenceNames /** * Created by matsumoto_k on 2017/11/10. */ class AdUtil { companion object { private var mySharedPref: MySharedPref? = null fun startBannerAd(context: Context, frameLayout: FrameLayout, adSize: AdSize, unitId: String) { val adBannerView = AdView(context) adBannerView.adSize = adSize adBannerView.adUnitId = unitId frameLayout.addView(adBannerView) val adBannerRequest = AdRequest.Builder().build() adBannerView.loadAd(adBannerRequest) } fun startInterstitialAd(context: Context) { if (mySharedPref == null) { mySharedPref = MySharedPref(context, PreferenceNames.CONFIG) } val interstitialCount = (mySharedPref?.getValue(PreferenceKeys.interstitialCount, Int::class.java, 1) as Int) if (interstitialCount == Const.interstitialFrequency) { mySharedPref?.putValue(PreferenceKeys.interstitialCount, Int::class.java, 1) val interstitialAd = InterstitialAd(context) interstitialAd.adUnitId = Const.interstitialUnitId interstitialAd.adListener = object : AdListener() { override fun onAdLoaded() { interstitialAd.show() } override fun onAdFailedToLoad(errorCode: Int) { val message = String.format("onAdFailedToLoad (%s)", getErrorReason(errorCode)) Log.d("debug", message) } } val adRequest: AdRequest adRequest = AdRequest.Builder().build() interstitialAd.loadAd(adRequest) } else { mySharedPref?.putValue(PreferenceKeys.interstitialCount, Int::class.java, interstitialCount + 1) } } // Gets a string error reason from an error code. private fun getErrorReason(errorCode: Int): String { var errorReason = "" when (errorCode) { AdRequest.ERROR_CODE_INTERNAL_ERROR -> errorReason = "ERROR_CODE_INTERNAL_ERROR" AdRequest.ERROR_CODE_INVALID_REQUEST -> errorReason = "ERROR_CODE_INVALID_REQUEST" AdRequest.ERROR_CODE_NETWORK_ERROR -> errorReason = "ERROR_CODE_NETWORK_ERROR" AdRequest.ERROR_CODE_NO_FILL -> errorReason = "ERROR_CODE_NO_FILL" } return errorReason } } }