アプリにAdMobのバナー広告を取り付ける方法

アプリにAdMobのバナー広告を取り付ける方法を説明します。 Firebase を使用した方法となります。

AdMobにアプリを登録して、広告ユニットをバナーで作成して、アプリIDと広告ユニットIDを取得します。

AndroidManifest.xmlにAdmobより取得したAPPLICATION_IDを登録します。

<manifest>
    <application>
    ・・・
        <!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
        <meta-data
                android:name="com.google.android.gms.ads.APPLICATION_ID"
                android:value="ca-app-pub-xxxxxxxxxxxxxxx"/>
    </application>
</manifest>

MainActivity.ktでアプリ ID を指定して  Mobile Ads SDK を初期化 (MobileAds.initialize()) します。

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
        MobileAds.initialize(this, "ca-app-pub-xxxxxxxxxx")

        val adView = findViewById<AdView>(R.id.admob);
        val adRequest =  AdRequest.Builder().build();
        adView.loadAd(adRequest);

Firebaseにプロジェクトを作成してアプリを登録して、構成ファイルをダウンロードしてandroidstudioのプロジェクトのappフォルダの直下に置きます。

プロジェクトレベルのbuild.gradleに以下を追加します。

buildscript {
     ・・・
    dependencies {
     ・・・
        classpath 'com.google.gms:google-services:4.2.0'  // Google Services plugin
    }
}

アプリレベルのbuild.gradleに以下を追加します。

dependencies {
  ・・・
    implementation 'com.google.firebase:firebase-ads:17.2.0'
}

アプリレベルの build.gradleの一番下に以下を追加します。

// Add the following line to the bottom of the file:
apply plugin: 'com.google.gms.google-services'  // Google Play services Gradle plugin

res/layout/activity_main.xmlに広告用のviewを作成します。

<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

・・・

    <com.google.android.gms.ads.AdView
            android:id="@+id/admob"
            android:layout_width="320dp"
            android:layout_height="50dp"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            ads:adSize="BANNER"
            ads:adUnitId="ca-app-pub-xxxxxxxxxxxxxxxxxx"

            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginLeft="1dp" 
            android:layout_marginStart="1dp" 
            android:layout_marginBottom="1dp"
            android:layout_marginRight="1dp" 
            android:layout_marginEnd="1dp">
    </com.google.android.gms.ads.AdView>

</androidx.constraintlayout.widget.ConstraintLayout>

これでバナー広告が表示されます。

メール

Follow me!