Баннерная и межстраничная реклама Google AdMob в приложении Android Kotlin

В этом руководстве мы внедрим межстраничные и баннерные рекламные объявления Google AdMob в наше приложение для Android в Kotlin. Чтобы разместить Google AdMob в приложении Android, нам нужно создать идентификатор рекламного блока Google. Полный справочник по созданию учетной записи Google AdMod и генерации идентификатора рекламного блока описан в Android Google AdMob.

Межстраничная реклама — это полноэкранная реклама, которая охватывает весь макет активности. Это объявление отображается в точке перехода действия. Чтобы внедрить Google AdMob в приложение Android в Котлин, выберите «Активность рекламы Google AdMob» и выберите тип формата рекламы «Межстраничные объявления».

Мы также можем размещать рекламу Google AdMob в других действиях, таких как пустое действие.

Добавьте зависимость от объявлений Google «com.google.android.gms:play-services-ads:17.0.0» в файле build.gradle.

build.gradle

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.android.gms:play-services-ads:17.0.0'
    testImplementation 'junit:junit:4.12'
}

Activity_main.xml

Добавьте свой код пользовательского интерфейса в файл activity_main.xml. Компонент Button используется для загрузки рекламы.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.kotlininterstitialads.MainActivity">  
  
    <!-- view for AdMob Interstitial Ad -->  
    <TextView  
        android:id="@+id/app_title"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="50dp"  
        android:text="@string/interstitial_ad_sample"  
        android:textAppearance="?android:attr/textAppearanceLarge" />  
  
    <Button  
        android:id="@+id/load_ad_button"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_centerHorizontal="true"  
        android:layout_centerVertical="true"  
        android:text="@string/load_ad" />  
</RelativeLayout> 

strings.xml

Добавьте идентификатор созданного рекламного блока в файл string.xml.

<resources>  
    <string name="app_name">KotlinInterstitialAds</string>  
    <string name="action_settings">Settings</string>  
    <string name="interstitial_ad_sample">Interstitial Ad Sample</string>  
    <string name="load_ad">Load Ad</string>  
    <!-- -  
        This is an ad unit ID for an interstitial test ad. Replace with your own interstitial ad unit id.  
    -->  
    <string name="interstitial_ad_unit_id">ca-app-pub-3940256099942544/1033173712</string>  
</resources>

MainActivity.kt

Добавьте следующий код в класс MainActivity.kt. Чтобы загрузить рекламу в пользовательский интерфейс, создайте экземпляр InterstitialAd и инициализируйте идентификатор рекламного блока в InterstitialAd interstitialAd.adUnitId = getString(R.string.interstitial_ad_unit_id).

Переопределите прослушиватели InterstitialAd onAdLoaded(), onAdFailedToLoad(), onAdClosed. Чтобы загружать рекламу при нажатии кнопки, создайте экземпляр AdRequest и загрузите рекламу, вызвав InterstitialAd!!.loadAd(AdRequest).

package example.javatpoint.com.kotlininterstitialads

import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.InterstitialAd
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    private var mLoadAdButton: Button? = null
    private var mInterstitialAd: InterstitialAd? = null

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

        // Create the InterstitialAd and set the adUnitId(defined in values/strings.xml).
        mInterstitialAd = newInterstitialAd()
        loadInterstitial()

        // Create the load ad button, tries to show an interstitial when clicked.
        mLoadAdButton = findViewById(R.id.load_ad_button) as Button
        mLoadAdButton!!.isEnabled = false
        mLoadAdButton!!.setOnClickListener {
            showInterstitial()
        }
    }

    private fun newInterstitialAd(): InterstitialAd {
        val interstitialAd = InterstitialAd(this)
        interstitialAd.adUnitId = getString(R.string.interstitial_ad_unit_id)
        interstitialAd.adListener = object : AdListener() {
            override fun onAdLoaded() {
                mLoadAdButton!!.isEnabled = true
                Toast.makeText(applicationContext, "Ad Loaded", Toast.LENGTH_SHORT).show()
            }

            override fun onAdFailedToLoad(errorCode: Int) {
                mLoadAdButton!!.isEnabled = true
                Toast.makeText(applicationContext, "Ad Failed To Load", Toast.LENGTH_SHORT).show()
            }

            override fun onAdClosed() {
                // Proceed to the next level.
               // goToNextLevel()
                Toast.makeText(applicationContext, "Ad Closed", Toast.LENGTH_SHORT).show()
                tryToLoadAdOnceAgain()
            }
        }
        return interstitialAd
    }

    private fun loadInterstitial() {
        // Disable the load ad button and load the ad.
        mLoadAdButton!!.isEnabled = false
        val adRequest = AdRequest.Builder().build()
        mInterstitialAd!!.loadAd(adRequest)
    }

    private fun showInterstitial() {
        // Show the ad if it is ready. Otherwise toast and reload the ad.
        if(mInterstitialAd != null && mInterstitialAd!!.isLoaded) {
            mInterstitialAd!!.show()
        } else {
            Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show()
            tryToLoadAdOnceAgain()
        }
    }

    private fun tryToLoadAdOnceAgain() {
        mInterstitialAd = newInterstitialAd()
        loadInterstitial()
    }
}

AndroidManifest.xml

Добавьте следующий код в файл AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="example.javatpoint.com.kotlininterstitialads">  
    <!-- Include required permissions for Google Mobile Ads to run. -->  
    <uses-permission android:name="android.permission.INTERNET" />  
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  
    <application  
        android:allowBackup="true"  
        android:icon="@mipmap/ic_launcher"  
        android:label="@string/app_name"  
        android:roundIcon="@mipmap/ic_launcher_round"  
        android:supportsRtl="true"  
        android:theme="@style/AppTheme"> <!-- This meta-data tag is required to use Google Play Services. -->  
        <meta-data  
            android:name="com.google.android.gms.version"  
            android:value="@integer/google_play_services_version" />  
  
        <activity  
            android:name=".MainActivity"  
            android:label="@string/app_name">  
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" />  
  
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </activity> <!-- Include the AdActivity configChanges and theme. -->  
        <activity  
            android:name="com.google.android.gms.ads.AdActivity"  
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"  
            android:theme="@android:style/Theme.Translucent" />  
        <meta-data  
            android:name="com.google.android.gms.ads.AD_MANAGER_APP"  
            android:value="true"/>  
    </application>  
  
</manifest>

Вывод:

загрузка рекламыМежстраничная реклама Google AdMob
Пример рекламы Google AdMobВывод

 

Баннерная реклама Google AdMob в приложение Android

Баннерная реклама – это прямоугольная текстовая или графическая реклама, занимающая небольшое место в макете активности. Чтобы внедрить Google AdMob в приложение Android, выберите «Активность рекламы Google AdMob» и выберите тип формата рекламы «Баннер». Это действие добавляет требуемую по умолчанию зависимость библиотеки, отображение View for Ads, разрешение на доступ в Интернет и другой необходимый код.

Добавьте зависимость от объявлений Google «com.google.android.gms:play-services-ads:17.0.0» в файле build.gradle.

build.gradle

 
dependencies { 
    implementation fileTree(dir: 'libs', include: ['*.jar']) 
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 
    implementation 'com.android.support:appcompat-v7:26.1.0' 
    implementation 'com.android.support.constraint:constraint-layout:1.1.3' 
    implementation 'com.google.android.gms:play-services-ads:17.0.0' 
    testImplementation 'junit:junit:4.12' 
} 

Activity_main.xml

Добавьте представление Google Ads в тот макет, в котором мы хотим отображать наши объявления. Здесь мы добавили в наш файл activity_main.xml.

Чтобы отобразить рекламный баннер, нам нужно добавить элемент com.google.android.gms.ads.AdView в наш XML-макет. Баннеры выравниваются по нижней части экрана.

<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:ads="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.kotlinbannerads.MainActivity">  
  
    <TextView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentTop="true"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="215dp"  
        android:text="@string/banner_ad_sample"  
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>  
  
    <!-- view for AdMob Banner Ad -->  
    <com.google.android.gms.ads.AdView  
        android:id="@+id/adView"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentBottom="true"  
        android:layout_centerHorizontal="true"  
        ads:adSize="BANNER"  
        ads:adUnitId="@string/banner_ad_unit_id" />  
  
</RelativeLayout>

strings.xml

Добавьте идентификатор созданного рекламного блока в файл string.xml.

<resources>  
    <string name="app_name">Kotlin Banner Ads</string>  
    <string name="banner_ad_sample">Banner Ad Sample</string>  
    <!-- -  
        This is an ad unit ID for a banner test ad. Replace with your own banner ad unit id.  
    -->  
    <string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>  
  <!--  <string name="title_activity_banner">BannerActivity</string>-->  
</resources>

MainActivity.kt

Добавьте следующий код в класс MainActivity.kt. Чтобы загрузить рекламу в пользовательский интерфейс, создайте экземпляр AdRequest и загрузите рекламу в AdView, вызвав AdView.loadAd(AdRequest).

Переопределить прослушиватели AdView onAdFailedToLoad(), onAdLoaded(), onAdOpened(), onAdClicked(), onAdClosed() и т. д.

 
package example.javatpoint.com.kotlinbannerads 
 
import android.support.v7.app.AppCompatActivity 
import android.os.Bundle 
import android.view.View 
import android.widget.Toast 
import com.google.android.gms.ads.AdListener 
import com.google.android.gms.ads.AdRequest 
import com.google.android.gms.ads.AdView 
 
class MainActivity : AppCompatActivity() { 
    lateinit var adView : AdView 
 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState) 
        setContentView(R.layout.activity_main) 
        // Load an ad into the AdMob banner view. 
        adView = findViewById(R.id.adView) as AdView 
        val adRequest = AdRequest.Builder().build() 
        adView.loadAd(adRequest) 
 
        adView.adListener = object : AdListener(){ 
            override fun onAdFailedToLoad(p0: Int) { 
                super.onAdFailedToLoad(p0) 
                val toastMessage: String = "ad fail to load" 
                Toast.makeText(applicationContext, toastMessage.toString(), Toast.LENGTH_LONG).show() 
            } 
            override fun onAdLoaded() { 
                super.onAdLoaded() 
                val toastMessage: String = "ad loaded" 
                Toast.makeText(applicationContext, toastMessage.toString(), Toast.LENGTH_LONG).show() 
            } 
            override fun onAdOpened() { 
                super.onAdOpened() 
                val toastMessage: String = "ad is open" 
                Toast.makeText(applicationContext, toastMessage.toString(), Toast.LENGTH_LONG).show() 
            } 
            override fun onAdClicked() { 
                super.onAdClicked() 
                val toastMessage: String = "ad is clicked" 
                Toast.makeText(applicationContext, toastMessage.toString(), Toast.LENGTH_LONG).show() 
            } 
 
            override fun onAdClosed() { 
                super.onAdClosed() 
                val toastMessage: String = "ad is closed" 
                Toast.makeText(applicationContext, toastMessage.toString(), Toast.LENGTH_LONG).show() 
            } 
            override fun onAdImpression() { 
                super.onAdImpression() 
                val toastMessage: String = "ad impression" 
                Toast.makeText(applicationContext, toastMessage.toString(), Toast.LENGTH_LONG).show() 
            } 
            override fun onAdLeftApplication() { 
                super.onAdLeftApplication() 
                val toastMessage: String = "ad left application" 
                Toast.makeText(applicationContext, toastMessage.toString(), Toast.LENGTH_LONG).show() 
            } 
        } 
    } 
 
    override fun onPause() { 
        if(adView!=null) { 
            adView.pause(); 
        } 
        super.onPause() 
    } 
 
    override fun onResume() { 
        super.onResume() 
        if(adView != null) { 
            adView.resume(); 
        } 
    } 
 
    override fun onDestroy() { 
        if(adView != null) { 
            adView.destroy(); 
        } 
        super.onDestroy(); 
    } 
} 

Примечание. Если вы получили исключение типа java.lang.RuntimeException: Unable to get provider com.google.android.gms.ads.MobileAdsInitProvider: java.lang.IllegalStateException: добавьте

 <meta-data  
            android:name="com.google.android.gms.ads.AD_MANAGER_APP"  
            android:value="true"/>

в файле AndroidManifest.

AndroidManifest.xml

Добавьте следующий код в файл AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
    package="example.javatpoint.com.kotlinbannerads">  
  
    <!-- Include required permissions for Google Mobile Ads to run. -->  
    <uses-permission android:name="android.permission.INTERNET" />  
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  
    <application  
        android:allowBackup="true"  
        android:icon="@mipmap/ic_launcher"  
        android:label="@string/app_name"  
        android:roundIcon="@mipmap/ic_launcher_round"  
        android:supportsRtl="true"  
        android:theme="@style/AppTheme">  
        <activity android:name=".MainActivity">  
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" />  
  
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </activity>  
        <!-- This meta-data tag is required to use Google Play Services. -->  
        <meta-data  
            android:name="com.google.android.gms.version"  
            android:value="@integer/google_play_services_version" />  
        <meta-data  
            android:name="com.google.android.gms.ads.AD_MANAGER_APP"  
            android:value="true"/>  
        <activity  
            android:name="com.google.android.gms.ads.AdActivity"  
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"  
            android:theme="@android:style/Theme.Translucent" />  
    </application>  
  
</manifest> 

Вывод:

Баннерная реклама
показ рекламы

Вывод 3
Вывод 4

Оцените статью