安卓 |适用于 Android Studio 的 AdMob 插页式广告
插页式广告是覆盖应用整个 UI 的全屏广告。本文向您展示了如何将 AdMob 中的插页式广告集成到 Android 应用中。
例子 -
首先在 Android Studio 中新建一个 Project 并添加以下代码以导入 google Mobile Ads SDK。在项目级 build.gradle文件中,将突出显示的代码添加到allprojects部分。
allprojects
{
repositories
{
google()
jcenter()
maven
{
url "https://maven.google.com"
}
}
}
在应用级 build.gradle文件中,将突出显示的代码添加到依赖项部分。
dependencies
{
implementation fileTree (dir : 'libs', include : [ '*.jar' ])
implementation 'com.android.support:appcompat-v7:26.1.0'
compile 'com.google.android.gms:play-services-ads:15.0.0'
将以下代码添加到Main Activity以初始化 Mobile Ads SDK(只需在应用生命周期中执行一次)。您可以在 AdMob 控制台中找到该应用的 App ID。
package org.geeksforgeeks.geeksforgeeks;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.gms.ads.MobileAds;
public class MainActivity extends AppCompatActivity
{
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
// Initialize the Mobile Ads SDK
MobileAds.initialize (this, getString (R.string.admob_app_id));
}
}
将突出显示的代码添加到Main Activity以显示 Interstitial Ad:
MainActivity.class –
package org.geeksforgeeks.geeksforgeeks;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
public class MainActivity extends AppCompatActivity
{
private InterstitialAd interstitial;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the Mobile Ads SDK
MobileAds.initialize(this, getString(R.string.admob_app_id));
AdRequest adIRequest = new AdRequest.Builder().build();
// Prepare the Interstitial Ad Activity
interstitial = new InterstitialAd(MainActivity.this);
// Insert the Ad Unit ID
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
// Interstitial Ad load Request
interstitial.loadAd(adIRequest);
// Prepare an Interstitial Ad Listener
interstitial.setAdListener(new AdListener()
{
public void onAdLoaded()
{
// Call displayInterstitial() function when the Ad loads
displayInterstitial();
}
});
}
public void displayInterstitial()
{
// If Interstitial Ads are loaded then show else show nothing.
if (interstitial.isLoaded()) {
interstitial.show();
}
}
}
将 Admob 应用 ID 和插页式广告 ID 添加到字符串.xml
字符串.xml –
ca-app-pub-3940256099942544~3347511713
ca-app-pub-3940256099942544/1033173712