公式を参考に実装した備忘録です。
いつも書く場所が分からなかったりして右往左往するので、抜粋は抜粋ですが、全体を提示するスタイルでいきます。
スコープは適当ですので、適切に調整して下さい。また、何も保障するものではありません。もしかしたら、抜粋する過程で何かミスがあり動かない可能性もありますが、とりあえず動いてたソースです。
Admobの設定は済んでいることが前提です。
プロジェクトのbuild.gradleに以下を追加。
buildscript {
repositories {
google()
mavenCentral()
}
}
※公式にはallprojectsへの記載もありましたが、エラーが出たため削除しました。
アプリのbuild.gradleに以下を追加。
android{
compileSdk 31 //確か31でないとエラーが出たきがします
}
dependencies {
implementation 'com.google.android.gms:play-services-ads:20.4.0'
// For apps targeting Android 12, add WorkManager dependency.
constraints {
implementation('androidx.work:work-runtime:2.7.0') {
because '''androidx.work:work-runtime:2.1.0 pulled from play-services-ads
has a bug using PendingIntent without FLAG_IMMUTABLE or
FLAG_MUTABLE and will fail in apps targeting S+.'''
}
}
}
AndroidManifest.xml に AdmobのアプリIDを記載します。(本番用 or テスト用)
<application
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-ca-app-pub-3940256099942544~3347511713" /><!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
</application>
activity_main.xml に バナー用のレイアウトを記載。
<RelativeLayout
android:id="@+id/layout_forAd"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</RelativeLayout>
以下の処理で、起動と同時にバナーを表示し、リワードとリワードインタースティシャルのロードを開始しています。あとは、表示開始の関数を呼べば、ロードが成功していれば表示されます。
activity_main.java
//リワードの処理をオーバーライドするために、 implements OnUserEarnedRewardListener しています
public class MainActivity extends AppCompatActivity implements OnUserEarnedRewardListener {
String bannerId = "ca-app-pub-3940256099942544/6300978111";//テスト用
String interstitialId = "ca-app-pub-3940256099942544/8691691433";//テスト用
String rewardId = "ca-app-pub-3940256099942544/5224354917";//テスト用
String TAG = "Admob tag";
AdView mAdView = null;
InterstitialAd mInterstitialAd = null;
RewardedInterstitialAd rewardedInterstitialAd = null;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
////////////////////////////////////////////////////////////////////////////////////
// アドモブの初期化
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
////////////////////////////////////////////////////////////////////////////////////
// バナー
mAdView = new AdView(this);
mAdView.setAdSize(AdSize.BANNER);
mAdView.setAdUnitId(bannerId);
// AdMob用のLayout parameterを設定
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
// 画面の底に位置させるようにALIGN_PARENT_BOTTOMを設定
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
// AdMobのレイアウト属性を設定
mAdView.setLayoutParams(params);
// Relative layout インスタンス生成
RelativeLayout layout = findViewById(R.id.layout_forAd);
layout.addView(mAdView);
AdRequest bannerRequest = new AdRequest.Builder().build();
// バナーをロード
mAdView.loadAd(bannerRequest);
// ad's lifecycle: loading, opening, closing, and so on
mAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
@Override
public void onAdFailedToLoad(LoadAdError adError) {
// Code to be executed when an ad request fails.
}
@Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
@Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
@Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
////////////////////////////////////////////////////////////////////////////////////
// インタースティシャルをロード開始
loadInterstitial();
////////////////////////////////////////////////////////////////////////////////////
// リワードインタースティシャルをロード開始
loadReward();
}
////////////////////////////////////////////////////////////////////////////////////
// インタースティシャルをロード開始(任意のタイミングで)
public void loadInterstitial() {
InterstitialAd.load(this,interstitialId, new AdRequest.Builder().build(),
new InterstitialAdLoadCallback() {
@Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
//コールバックを登録する
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
@Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
Log.d("TAG", "The ad was dismissed.");
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
Log.d("TAG", "The ad failed to show.");
}
@Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
// Make sure to set your reference to null so you don't
// show it a second time.
mInterstitialAd = null;
Log.d("TAG", "The ad was shown.");
}
});
Log.i(TAG, "onAdLoaded");
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
mInterstitialAd = null;
}
});
}
////////////////////////////////////////////////////////////////////////////////////
//インタースティシャルの表示開始(任意のタイミングで)
public void StartInterstitial(){
if (mInterstitialAd != null) {
mInterstitialAd.show(this);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
}
////////////////////////////////////////////////////////////////////////////////////
// リワードインタースティシャルをロード開始(任意のタイミングで)
public void loadReward() {
RewardedInterstitialAd.load(MainActivity.this, rewardId,
new AdRequest.Builder().build(), new RewardedInterstitialAdLoadCallback() {
@Override
public void onAdLoaded(RewardedInterstitialAd ad) {
rewardedInterstitialAd = ad;
//コールバックを登録する
rewardedInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
/** Called when the ad failed to show full screen content. */
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
Log.i(TAG, "onAdFailedToShowFullScreenContent");
}
/** Called when ad showed the full screen content. */
@Override
public void onAdShowedFullScreenContent() {
Log.i(TAG, "onAdShowedFullScreenContent");
}
/** Called when full screen content is dismissed. */
@Override
public void onAdDismissedFullScreenContent() {
Log.i(TAG, "onAdDismissedFullScreenContent");
}
});
Log.e(TAG, "onAdLoaded");
}
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
Log.e(TAG, "onAdFailedToLoad");
rewardedInterstitialAd = null;
}
});
}
////////////////////////////////////////////////////////////////////////////////////
//インタースティシャルの表示開始(任意のタイミングで)
public void StartRewardInterstitial(){
if (rewardedInterstitialAd != null) {
rewardedInterstitialAd.show(MainActivity.this, MainActivity.this);
} else {
Log.d("TAG", "The rewardInterstitial ad wasn't ready yet.");
}
}
////////////////////////////////////////////////////////////////////////////////////
@Override
public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
Log.i(TAG, "onUserEarnedReward");
//リワードの報酬を与える処理
}
}
comment