![見出し画像](https://assets.st-note.com/production/uploads/images/132750199/rectangle_large_type_2_f5f9d711b826e0a008385d76334aea3b.png?width=1200)
【Android】アプリ内広告(AdMob)実装方法例_2024年1月時点
この度、久しぶりにアプリを作ってリリースすることにしました。
その中で、アプリ内広告(AdMob)を実装しましたので、
その実装方法を記録しておきます。
まず、AdMobのサイトでアプリ情報・広告情報を登録して、
「アプリID」「広告ユニットID」を取得します。
![](https://assets.st-note.com/img/1709438127145-XSmxLFLDfF.png?width=1200)
次に、アプリの設定ファイルに必要な情報を記載します。
○build.gradle
//admob
implementation 'com.google.android.gms:play-services-ads:21.0.0'
○AndroidManifest.xml
<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-〜〜〜〜〜〜〜〜〜〜-"/>
次に、方法はいくつかありますが、
僕はレイアウトの適切な所に記載して、ソースで呼び出す方法にしました。
○レイアウトファイル(xml)
<com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
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="ca-app-pub-〜〜〜〜〜〜〜〜〜〜">
</com.google.android.gms.ads.AdView>
○MainActivity.java
AdView mAdView = null;
//アプリ内広告表示
MobileAds.initialize(this);
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
基本的には、上の内容で広告が表示されます。
(テスト用の広告IDで表示テストも可能です。)
後は、不要の時はmAdViewを操作して消してmAdView周りのレイアウトを調整するなど、必要な操作をします。
アプリ内広告の表示方法は以上になります。
また、アプリも使ってみて頂けると嬉しいです。
最後までお読みいただき、ありがとうございました。