AdMobのアプリIDおよび広告ユニットIDを安全かつ柔軟に管理し、開発・本番環境に応じた広告表示を実現するための設定手順です。
1. テスト用IDの設定(gradle.properties)
プロジェクトルートの gradle.properties に以下を追加します:
admob.test.app.id=ca-app-pub-3940256099942544~3347511713
admob.test.banner.id=ca-app-pub-3940256099942544/6300978111
2. 公開用IDの設定(local.properties)
プロジェクトルートの local.properties に以下を追加します:
admob.app.id=ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy
admob.banner.id=ca-app-pub-xxxxxxxxxxxxxxxx/zzzzzzzzzz
⚠️
local.propertiesはバージョン管理(Gitなど)に含めないでください。
3. ビルドスクリプトの設定(app/build.gradle.kts)
以下のように build.gradle.kts を編集します。
import java.util.Properties
import java.io.FileInputStream
val localProperties = Properties().apply {
val file = rootProject.file("local.properties")
if (file.exists()) {
load(FileInputStream(file))
}
}
android {
buildTypes {
debug {
manifestPlaceholders["admob_app_id"] = project.properties["admob.test.app.id"]
}
release {
manifestPlaceholders["admob_app_id"] = localProperties["admob.app.id"]
}
}
// 必要であれば buildConfigField にも値を渡す
defaultConfig {
buildConfigField(
"String",
"ADMOB_TEST_BANNER_ID",
"\"${project.properties["admob.test.banner.id"]}\""
)
buildConfigField(
"String",
"ADMOB_BANNER_ID",
"\"${localProperties["admob.banner.id"]}\""
)
}
}
4. AndroidManifest.xml の設定
以下を <application> タグ内に追加します:
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="${admob_app_id}" />
5. KotlinコードでのAdMob初期化
Application クラスなどで MobileAds.initialize() を呼び出します:
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
MobileAds.initialize(this)
}
}
6. 広告ユニットIDの管理(リソース化)
res/values-debug/strings.xml と res/values-release/strings.xml を使い、バナーIDを切り替えます。
res/values-debug/strings.xml
<resources>
<string name="admob_banner_id">ca-app-pub-3940256099942544/6300978111</string>
</resources>
res/values-release/strings.xml
<resources>
<string name="admob_banner_id">ca-app-pub-xxxxxxxxxxxxxxxx/zzzzzzzzzz</string>
</resources>
ActivityまたはFragmentで:
val adView: AdView = findViewById(R.id.adView)
adView.adUnitId = getString(R.string.admob_banner_id)
val adRequest = AdRequest.Builder().build()
adView.loadAd(adRequest)
7. AdMob SDK の依存関係(最新版)
app/build.gradle.kts の dependencies に以下を追加:
dependencies {
implementation("com.google.android.gms:play-services-ads:23.1.0") // 最新を確認すること
}
8. ProGuard 設定(リリースビルド時)
proguard-rules.pro に以下を追加:
-keep public class com.google.android.gms.ads.** {
public *;
}
✅ まとめ
| ビルドタイプ | App ID 読み込み元 | Banner ID の指定方法 |
|---|---|---|
| Debug | gradle.properties | res/values-debug/strings.xml |
| Release | local.properties | res/values-release/strings.xml |
この設定により、開発中はテスト広告、本番では本物の広告が安全に表示されるようになります。