0
1

More than 3 years have passed since last update.

Androidアプリに広告を貼る方法 

Posted at

ソースコード設定

下記適切なバージョンを使用
https://developers.google.com/admob/android/quick-start?hl=ja

build.gradle
dependencies {
    implementation 'com.google.android.gms:play-services-ads:19.3.0'
}

ネットワーク権限などを設定

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

レイアウト記入

activity_main.xml
    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
    </com.google.android.gms.ads.AdView>

Activityに記入

MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
        // Test App ID
        MobileAds.initialize(activity, "ca-app-pub-3940256099942544~3347511713")

        val adRequest: AdRequest = AdRequest.Builder().build()
        adView.loadAd(adRequest)

        // ad's lifecycle: loading, opening, closing, and so on
        adView.adListener = object:AdListener(){
            override fun onAdLoaded() {
                Log.d("debug","Code to be executed when an ad finishes loading.");
            }

            override fun onAdFailedToLoad(errorCode : Int) {
                Log.d("debug","Code to be executed when an ad request fails.");
            }

            override fun onAdOpened() {
                Log.d("debug","Code to be executed when an ad opens an overlay that covers the screen.");
            }

            override fun onAdLeftApplication() {
                Log.d("debug","Code to be executed when the user has left the app.");
            }

            override fun onAdClosed() {
                Log.d("debug","Code to be executed when when the user is about to return to the app after tapping on an ad.");
            }
        }
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1