个性化阅读
专注于IT技术分析

Kotlin Android Google AdMob横幅广告示例

点击下载

在本教程中, 我们在Android应用程序中实施Google AdMob标语广告。要将Google AdMob放置在Android应用程序中, 我们需要创建Google广告单元ID。有关创建Google AdMod帐户和生成广告单元ID的完整参考, 请参见Android Google AdMob。

横幅广告是矩形文字或图像广告, 在活动布局中占据一小部分。要在Android应用程序中实现Google AdMob, 请选择Google AdMob广告活动, 然后将广告格式类型选择为横幅。此活动将添加默认的必需库依赖项, “广告视图”显示, Internet权限以及其他必需的代码。

我们还可以将Google AdMob广告放置在其他活动(例如空白活动)上。

在build.gradle文件中添加Google广告依赖项“ com.google.android.gms:play-services-ads:17.0.0”:

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.srcmini02.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文件中添加创建的广告单元ID。

<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.loadAd(AdRequest)在AdView中加载广告。

覆盖AdView监听器onAdFailedToLoad(), onAdLoaded(), onAdOpened(), onAdClicked(), onAdClosed()等。

package example.srcmini02.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<View>(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:无法获取提供程序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.srcmini02.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>

输出:

Kotlin Android Google AdMob横幅广告示例
Kotlin Android Google AdMob横幅广告示例
Kotlin Android Google AdMob横幅广告示例
Kotlin Android Google AdMob横幅广告示例
赞(0)
未经允许不得转载:srcmini » Kotlin Android Google AdMob横幅广告示例

评论 抢沙发

评论前必须登录!