Google Admob으로 전면광고 표시하기

이번 포스팅에서는 구글 애드몹을 이용해서 전면광고를 표시하는 법에 대해 알아보도록 하겠습니다.

우선은 애드몹 디펜던시를 추가합니다. 현재 애드몹 라이브러리의 최신버전은 19.7.0인데요, 19.6.0 버전과는 사용법이 많이 다르기 때문에 두 방법 모두 설명하도록 하겠습니다.

# Google Admob Version 19.6.0 이하에서의 구현

1
2
3
dependencies {
    implementation 'com.google.android.gms:play-services-ads:19.6.0'
}

AndroidManifest.xml 안에 애드몹 사이트에서 부여받는 앱 ID를 입력합니다. 여기서는 구글에서 테스트용으로 제공하는 ID를 입력하였습니다.

1
2
3
4
5
6
7
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713" />
    </application>

다음은 화면에 광고를 표시하는 버튼을 추가합니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<androidx.constraintlayout.widget.ConstraintLayout
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show AD"
        android:id="@+id/button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

View Binding을 설정하고 애드몹 라이브러리를 초기화합니다. setRequestConfiguration을 사용해서 테스트용으로 사용할 기기에 대해서는 애드몹이 카운트하여 어뷰징으로 판단하지 않도록 제외하여 줍니다.

광고를 불러오는 작업은 loadInterstitialAd에서 수행하고 광고를 표시하는 작업은 showInterstitialad에서 수행하도록 합니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
private var mInterstitialAd: InterstitialAd? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)

    MobileAds.initialize(this)

    val testDeviceIds = listOf("My device ID1", "My device ID2")
    MobileAds.setRequestConfiguration(
        RequestConfiguration.Builder()
            .setTestDeviceIds(testDeviceIds)
            .build()
    )

    loadInterstitialAd()

    binding.button.setOnClickListener {
        showInterstitialad()
    }
}

우선은 광고를 불러오는 부분을 작성하겠습니다.

adUnitId에는 애드몹 사이트에서 제공하는 전면광고 아이디를 기입합니다. 여기서는 구글에서 제공하는 테스트 ID를 사용했습니다.

그리고 adListener를 붙여주는데 onAdClosed로 광고를 닫으면 다음광고를 다시 로딩하도록 합니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
private fun loadInterstitialAd() {
    val adRequest = AdRequest.Builder().build()

    mInterstitialAd = InterstitialAd(this)
    mInterstitialAd?.adUnitId = "ca-app-pub-3940256099942544/1033173712"
    mInterstitialAd?.loadAd(adRequest)
    mInterstitialAd?.adListener = object : AdListener() {
        override fun onAdLoaded() {
            Toast.makeText(applicationContext, "Ad loading succeed",  Toast.LENGTH_SHORT).show()
        }

        override fun onAdFailedToLoad(p0: LoadAdError?) {
            Toast.makeText(applicationContext, "Ad loading failed",  Toast.LENGTH_SHORT).show()
            mInterstitialAd = null
        }

        override fun onAdClosed() {
            mInterstitialAd?.loadAd(adRequest)
        }
    }
}

다음은 광고를 보여주는 부분입니다. 광고가 잘 불러와졌는지 확인하고 show로 표시하면 됩니다.

1
2
3
4
5
6
private fun showInterstitialad() {
    if (mInterstitialAd != null) {
        if (mInterstitialAd!!.isLoaded) {
            mInterstitialAd?.show()
        }
}

# Google Admob Version 19.7.0 이상에서의 구현

구현은 loadInterstitialAdshowInterstitialad의 내용만 변경하면 됩니다. 우선 loadInterstitialAd는 다음과 같이 변경됩니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
private fun loadInterstitialAd() {
    val adRequest = AdRequest.Builder().build()

    InterstitialAd.load(
        this, "ca-app-pub-3940256099942544/1033173712", adRequest, object : InterstitialAdLoadCallback() {
            override fun onAdFailedToLoad(p0: LoadAdError) {
                Toast.makeText(applicationContext, "Ad loading failed", Toast.LENGTH_SHORT).show()
                mInterstitialAd = null
            }

            override fun onAdLoaded(p0: InterstitialAd) {
                Toast.makeText(applicationContext, "Ad loading succeed", Toast.LENGTH_SHORT).show()
                mInterstitialAd = p0
            }
        }
    )
}

그리고 showInterstitialad는 다음과 같이 변경합니다. mInterstitialAd에 대해 null체크를 수행한 뒤 fullScreenContentCallback 프로퍼티를 작성해주고 show로 광고를 보여주면 됩니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private fun showInterstitialad() {
    if (mInterstitialAd != null) {

        mInterstitialAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
            override fun onAdDismissedFullScreenContent() {
                Log.d("TAG", "Ad was dismissed.")
                mInterstitialAd = null
                loadInterstitialAd()
            }

            override fun onAdFailedToShowFullScreenContent(p0: AdError?) {
                Log.d("TAG", "Ad failed to show.")
                mInterstitialAd = null
            }

            override fun onAdShowedFullScreenContent() {
                Log.d("TAG", "Ad showed fullscreen content")
            }
        }
        mInterstitialAd?.show(this)
    } else {
        Log.d("TAG", "The interstitial ad was not ready yet")
    }
}

이렇게 해서 Google Admob 라이브러리로 앱에 전면광고를 표시하는 법에 대해 알아보았습니다.

Built with Hugo
Theme Stack designed by Jimmy