package jackall.moncalc.model import android.content.Context import android.util.Log import com.google.android.gms.ads.AdListener import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.InterstitialAd import jackall.moncalc.Const import jackall.moncalc.common.PreferenceKeys import jackall.moncalc.common.PreferenceNames import jackall.moncalc.utils.MySharedPref /** * Created by matsumoto_k on 2017/11/07. */ class AdInterstitial(val context: Context) { private val EmulatorTest = false private var UnitID: String? = null // publisher ID private val AdMobID = Const.interStitialUnitId // Test ID private val EmulatorTestID = Const.interStitialUnitId private val mySharedPref = MySharedPref(context, PreferenceNames.CONFIG) fun showInterstitial() { if (mySharedPref.getValue(PreferenceKeys.INSTECOUNT, Int::class.java, 1) as Int == Const.interstitialFrequency) { mySharedPref.putValue(PreferenceKeys.INSTECOUNT, Int::class.java, 1) if (EmulatorTest) { UnitID = EmulatorTestID } else { UnitID = AdMobID } Log.d("debug", UnitID) // インタースティシャルを作成する。 val interstitialAd = InterstitialAd(context) interstitialAd.adUnitId = UnitID // Set the AdListener. 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 if (EmulatorTest) { // Test adRequest = AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .addTestDevice(EmulatorTestID) .build() } else { // 広告リクエストを作成する (本番) println("本番") adRequest = AdRequest.Builder().build() } // Load the interstitial ad. interstitialAd.loadAd(adRequest) } else { mySharedPref.putValue(PreferenceKeys.INSTECOUNT, Int::class.java, mySharedPref.getValue(PreferenceKeys.INSTECOUNT, Int::class.java, 1) as Int + 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 } }