Android项目中集成Admob横幅/插页/激励广告
一.项目配置
app\build.gradle
dependencies {
implementation 'com.google.android.gms:play-services-ads:20.5.0'
}
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544~3347511713(应用ID)" />
</application>
二.横幅广告
1.编程方式创建广告布局
activity_main.xml
<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">
<RelativeLayout
android:id="@+id/adMobView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private AdView mAdView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化广告
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
//用编程的方式创建布局加载读取广告
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
mAdView = new AdView(this);
mAdView.setAdSize(AdSize.BANNER);
//mAdView.setAdSize(new AdSize(300,50));
mAdView.setAdUnitId("ca-app-pub-3940256099942544/6300978111(测试横幅广告ID)");
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
layout.addView(mAdView);
mAdView.loadAd(adRequestBuilder.build());
setContentView(layout);
//广告事件
mAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
//广告完成加载时要执行的代码。
Toast.makeText(getApplicationContext(), "Admob广告加载成功!", Toast.LENGTH_LONG).show();
}
@Override
public void onAdFailedToLoad(LoadAdError adError) {
// 当广告请求失败时要执行的代码。
Toast.makeText(getApplicationContext(), "Admob广告加载失败!", Toast.LENGTH_LONG).show();
}
@Override
public void onAdOpened() {
// 当广告打开叠加层时要执行的代码
// 覆盖屏幕。
}
@Override
public void onAdClicked() {
// 当用户点击广告时执行的代码。
}
@Override
public void onAdClosed() {
// 用户即将返回时执行的代码
// 点击广告后进入应用程序。
}
});
}
2.xml方式创建广告布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<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"
app:adSize="BANNER"
app:adUnitId="ca-app-pub-3940256099942544/6300978111(横幅广告ID)"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.494"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="39dp">
</com.google.android.gms.ads.AdView>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private AdView mAdView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化广告
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
//绑定xml布局id并加载横幅广告
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
//广告事件
mAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
//广告完成加载时要执行的代码。
Toast.makeText(getApplicationContext(), "Admob广告加载成功!", Toast.LENGTH_LONG).show();
}
@Override
public void onAdFailedToLoad(LoadAdError adError) {
// 当广告请求失败时要执行的代码。
Toast.makeText(getApplicationContext(), "Admob广告加载失败!", Toast.LENGTH_LONG).show();
}
@Override
public void onAdOpened() {
// 当广告打开叠加层时要执行的代码
// 覆盖屏幕。
}
@Override
public void onAdClicked() {
// 当用户点击广告时执行的代码。
}
@Override
public void onAdClosed() {
// 用户即将返回时执行的代码
// 点击广告后进入应用程序。
}
});
}
}
三.插页广告
activity_two.xml
<RelativeLayout 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"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".TwoActivity"
tools:ignore="MergeRootFrame">
<TextView
android:id="@+id/game_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="@string/impossible_game"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/game_title"
android:layout_centerHorizontal="true"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/retry_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="重试"
app:backgroundTint="#009688" />
</RelativeLayout>
twoActivity.java
public class TwoActivity extends AppCompatActivity {
private static final long GAME_LENGTH_MILLISECONDS = 3000;
private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712(插页广告ID)";
private static final String TAG = "TwoActivity";
private InterstitialAd interstitialAd;
private CountDownTimer countDownTimer;
private Button retryButton;
private boolean gameIsInProgress;
private long timerMilliseconds;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
// 初始化移动广告SDK。
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
loadAd();
//创建“重试”按钮,尝试在游戏之间显示间隙
retryButton = findViewById(R.id.retry_button);
retryButton.setVisibility(View.INVISIBLE);
retryButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showInterstitial();
}
});
startGame();
}
public void loadAd() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(
this,
AD_UNIT_ID,
adRequest,
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
// 插页式广告参考将为空,直到
// 广告已加载。
TwoActivity.this.interstitialAd = interstitialAd;
Log.i(TAG, "广告已加载");
Toast.makeText(TwoActivity.this, "广告已加载", Toast.LENGTH_SHORT).show();
interstitialAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
@Override
public void onAdDismissedFullScreenContent() {
//当全屏内容被关闭时调用。
//确保将您的引用设置为空,这样您就不会
//显示第二次。
TwoActivity.this.interstitialAd = null;
Log.d("TAG", "该广告被驳回。");
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
//当全屏内容无法显示时调用。
//确保将您的引用设置为空,这样您就不会
//显示第二次。
TwoActivity.this.interstitialAd = null;
Log.d("TAG", "广告未能展示。");
}
@Override
public void onAdShowedFullScreenContent() {
// 当显示全屏内容时调用。
Log.d("TAG", "广告被展示了。");
}
});
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
//处理错误
Log.i(TAG, loadAdError.getMessage());
interstitialAd = null;
String error =
String.format(
"领域: %s, 代码: %d, 信息: %s",
loadAdError.getDomain(), loadAdError.getCode(), loadAdError.getMessage());
Toast.makeText(
TwoActivity.this, "在AdFailedToLoad()上出现错误: " + error, Toast.LENGTH_SHORT)
.show();
}
});
}
//时间
private void createTimer(final long milliseconds) {
//创建游戏计时器,倒计时到关卡结束
//并显示“重试”按钮。
if (countDownTimer != null) {
countDownTimer.cancel();
}
final TextView textView = findViewById(R.id.timer);
countDownTimer = new CountDownTimer(milliseconds, 50) {
@Override
public void onTick(long millisUnitFinished) {
timerMilliseconds = millisUnitFinished;
textView.setText("剩余秒数: " + ((millisUnitFinished / 1000) + 1));
}
@Override
public void onFinish() {
gameIsInProgress = false;
textView.setText("完毕!");
retryButton.setVisibility(View.VISIBLE);
}
};
}
@Override
public void onResume() {
// 开始或恢复游戏。
super.onResume();
if (gameIsInProgress) {
resumeGame(timerMilliseconds);
}
}
@Override
public void onPause() {
// 如果游戏暂停,则取消计时器。
countDownTimer.cancel();
super.onPause();
}
private void showInterstitial() {
//如果广告准备好了,就显示它。否则就重新启动游戏
if (interstitialAd != null) {
interstitialAd.show(this);
} else {
Toast.makeText(this, "广告没有加载", Toast.LENGTH_SHORT).show();
startGame();
}
}
private void startGame() {
//如果一个新广告尚未加载,则请求一个新广告,隐藏按钮,并启动计时器。
if (interstitialAd == null) {
loadAd();
}
retryButton.setVisibility(View.INVISIBLE);
resumeGame(GAME_LENGTH_MILLISECONDS);
}
private void resumeGame(long milliseconds) {
// 为正确的长度创建一个新的计时器并启动它。
gameIsInProgress = true;
timerMilliseconds = milliseconds;
createTimer(milliseconds);
countDownTimer.start();
}
}
四.激励广告
activity_jl.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".JlActivity">
<TextView
android:id="@+id/game_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/impossible_game"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_marginTop="50dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<TextView
android:id="@+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="@id/game_title"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
/>
<Button
android:id="@+id/retry_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
app:layout_constraintTop_toBottomOf="@id/timer"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:text="@string/retry_button_text" />
<Button
android:id="@+id/show_video_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintTop_toBottomOf="@id/retry_button"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:text="@string/watch_video_button_text" />
<TextView
android:id="@+id/coin_count_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginLeft="16dp"
android:text="@string/default_coin_text"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:textAppearance="?android:attr/textAppearanceLarge" />
</androidx.constraintlayout.widget.ConstraintLayout>
JlActivity.java
public class JlActivity extends AppCompatActivity {
private static final String AD_UNIT_ID = "ca-app-pub-3940256099942544/5224354917";
private static final long COUNTER_TIME = 10;
private static final int GAME_OVER_REWARD = 1;
private static final String TAG = "JlActivity";
private int coinCount;
private TextView coinCountText;
private CountDownTimer countDownTimer;
private boolean gameOver;
private boolean gamePaused;
private RewardedAd rewardedAd;
private Button retryButton;
private Button showVideoButton;
private long timeRemaining;
boolean isLoading;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jl);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
loadRewardedAd();
// Create the "retry" button, which tries to show a rewarded ad between game plays.
retryButton = findViewById(R.id.retry_button);
retryButton.setVisibility(View.INVISIBLE);
retryButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
startGame();
}
});
// Create the "show" button, which shows a rewarded video if one is loaded.
showVideoButton = findViewById(R.id.show_video_button);
showVideoButton.setVisibility(View.INVISIBLE);
showVideoButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
showRewardedVideo();
}
});
// Display current coin count to user.
coinCountText = findViewById(R.id.coin_count_text);
coinCount = 0;
coinCountText.setText("硬币: " + coinCount);
startGame();
}
@Override
public void onPause() {
super.onPause();
pauseGame();
}
@Override
public void onResume() {
super.onResume();
if (!gameOver && gamePaused) {
resumeGame();
}
}
private void pauseGame() {
countDownTimer.cancel();
gamePaused = true;
}
private void resumeGame() {
createTimer(timeRemaining);
gamePaused = false;
}
private void loadRewardedAd() {
if (rewardedAd == null) {
isLoading = true;
AdRequest adRequest = new AdRequest.Builder().build();
RewardedAd.load(
this,
AD_UNIT_ID,
adRequest,
new RewardedAdLoadCallback() {
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
// Handle the error.
Log.d(TAG, loadAdError.getMessage());
rewardedAd = null;
JlActivity.this.isLoading = false;
Toast.makeText(JlActivity.this, "onAdFailedToLoad", Toast.LENGTH_SHORT).show();
}
@Override
public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
JlActivity.this.rewardedAd = rewardedAd;
Log.d(TAG, "onAdLoaded");
JlActivity.this.isLoading = false;
Toast.makeText(JlActivity.this, "onAdLoaded", Toast.LENGTH_SHORT).show();
}
});
}
}
private void addCoins(int coins) {
coinCount += coins;
coinCountText.setText("硬币: " + coinCount);
}
private void startGame() {
// Hide the retry button, load the ad, and start the timer.
retryButton.setVisibility(View.INVISIBLE);
showVideoButton.setVisibility(View.INVISIBLE);
if (rewardedAd != null && !isLoading) {
loadRewardedAd();
}
createTimer(COUNTER_TIME);
gamePaused = false;
gameOver = false;
}
// Create the game timer, which counts down to the end of the level
// and shows the "retry" button.
private void createTimer(long time) {
final TextView textView = findViewById(R.id.timer);
if (countDownTimer != null) {
countDownTimer.cancel();
}
countDownTimer =
new CountDownTimer(time * 1000, 50) {
@Override
public void onTick(long millisUnitFinished) {
timeRemaining = ((millisUnitFinished / 1000) + 1);
textView.setText("剩余秒数: " + timeRemaining);
}
@Override
public void onFinish() {
if (rewardedAd != null) {
showVideoButton.setVisibility(View.VISIBLE);
}
textView.setText("你输了!");
addCoins(GAME_OVER_REWARD);
retryButton.setVisibility(View.VISIBLE);
gameOver = true;
}
};
countDownTimer.start();
}
private void showRewardedVideo() {
if (rewardedAd == null) {
Log.d("TAG", "The rewarded ad wasn't ready yet.");
return;
}
showVideoButton.setVisibility(View.INVISIBLE);
rewardedAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
@Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "onAdShowedFullScreenContent");
Toast.makeText(JlActivity.this, "onAdShowedFullScreenContent", Toast.LENGTH_SHORT)
.show();
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.d(TAG, "onAdFailedToShowFullScreenContent");
// Don't forget to set the ad reference to null so you
// don't show the ad a second time.
rewardedAd = null;
Toast.makeText(
JlActivity.this, "onAdFailedToShowFullScreenContent", Toast.LENGTH_SHORT)
.show();
}
@Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Don't forget to set the ad reference to null so you
// don't show the ad a second time.
rewardedAd = null;
Log.d(TAG, "onAdDismissedFullScreenContent");
Toast.makeText(JlActivity.this, "onAdDismissedFullScreenContent", Toast.LENGTH_SHORT)
.show();
// Preload the next rewarded ad.
JlActivity.this.loadRewardedAd();
}
});
Activity activityContext = JlActivity.this;
rewardedAd.show(
activityContext,
new OnUserEarnedRewardListener() {
@Override
public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
// Handle the reward.
Log.d("TAG", "The user earned the reward.");
int rewardAmount = rewardItem.getAmount();
String rewardType = rewardItem.getType();
}
});
}
}
strings.xml
<resources>
<string name="app_name">Admob</string>
<string name="hello_world">跳转到插页广告界面!</string>
<string name="hello_world1">跳转到激励广告界面!</string>
<string name="action_settings">设置</string>
<string name="impossible_game">不可能的游戏</string>
<string name="retry_button_text">重试</string>
<string name="watch_video_button_text">观看视频可额外获得1个硬币</string>
<string name="default_coin_text">金币: 0</string>
</resources>