이 가이드에서는 적응형 앵커 배너 광고를 Android 앱에 로드하는 방법을 설명합니다.
기본 요건
- 시작 가이드에 따라 필요한 과정을 완료합니다.
항상 테스트 광고로 테스트
앱을 제작하고 테스트할 때는 운영 중인 실제 광고 대신 테스트 광고를 사용하세요. 이렇게 하지 않으면 계정이 정지될 수 있습니다.
테스트 광고를 로드하는 가장 쉬운 방법은 Android 배너 광고의 테스트 전용 광고 단위 ID를 사용하는 것입니다.
ca-app-pub-3940256099942544/9214589741
이 ID는 모든 요청에 대해 테스트 광고를 반환하도록 특별히 구성되었으며, 코딩, 테스트 및 디버깅 중에 앱에서 사용할 수 있습니다. 앱을 게시하기 전에 이 ID를 자체 광고 단위 ID로 바꿔야 합니다.
Google 모바일 광고 SDK (베타) 테스트 광고가 작동하는 방식을 자세히 알아보려면 테스트 광고 사용 설정을 참고하세요.
광고 뷰 정의
XML 레이아웃
적응형 앵커 배너 광고의 컨테이너 역할을 하는 뷰를 레이아웃 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">
<FrameLayout
android:id="@+id/banner_view_container"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Jetpack Compose
Compose UI 내에 AndroidView
요소를 포함하고 배너 광고를 보유할 mutableStateOf<BannerAd?>
변수를 정의합니다.
// Initialize required variables.
val context = LocalContext.current
var bannerAdState by remember { mutableStateOf<BannerAd?>(null) }
// The AdView is placed at the bottom of the screen.
Column(modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom) {
bannerAdState?.let { bannerAd ->
Box(modifier = Modifier.fillMaxWidth()) {
// Display the ad within an AndroidView.
AndroidView(
modifier = modifier.wrapContentSize(),
factory = { bannerAd.getView(requireActivity()) },
)
}
}
}
광고 로드
- 광고 단위 ID와 고정된 적응형 광고 크기를 사용하여
BannerAdRequest
객체를 만듭니다. BannerAd.load()
을 호출합니다.BannerAd.getView()
을 뷰 계층 구조에 추가합니다.
Kotlin
import com.google.android.libraries.ads.mobile.sdk.banner.AdSize
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAd
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdEventCallback
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRefreshCallback
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRequest
import com.google.android.libraries.ads.mobile.sdk.common.AdLoadCallback
import com.google.android.libraries.ads.mobile.sdk.common.LoadAdError
class MainActivity : Activity() {
private var bannerAd: BannerAd? = null
private lateinit var binding: ActivityMainBinding
private lateinit var adSize: AdSize
private lateinit var bannerViewContainer: FrameLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// 320 is a placeholder value. Replace 320 with your banner container width.
adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 320)
// Give the banner container a placeholder height to avoid a sudden layout
// shifts when the ad loads.
bannerViewContainer = binding.bannerViewContainer
val bannerLayoutParams = bannerViewContainer.layoutParams
bannerLayoutParams.height = adSize.getHeightInPixels(requireContext())
bannerViewContainer.layoutParams = bannerLayoutParams
// Step 1 - Create a BannerAdRequest object with ad unit ID and size.
val adRequest = BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build()
// Step 2 - Load the ad.
BannerAd.load(
adRequest,
object : AdLoadCallback<BannerAd> {
override fun onAdLoaded(ad: BannerAd) {
// Assign the loaded ad to the BannerAd object.
bannerAd = ad
// Step 3 - Call BannerAd.getView() to get the View and add it
// to view hierarchy on the UI thread.
activity?.runOnUiThread {
binding.bannerViewContainer.addView(ad.getView(requireActivity()))
}
}
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
bannerAd = null
}
},
)
}
}
Java
import com.google.android.libraries.ads.mobile.sdk.banner.AdSize;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAd;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdEventCallback;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRefreshCallback;
import com.google.android.libraries.ads.mobile.sdk.banner.BannerAdRequest;
import com.google.android.libraries.ads.mobile.sdk.common.AdLoadCallback;
import com.google.android.libraries.ads.mobile.sdk.common.LoadAdError;
public class MainActivity extends AppCompatActivity {
private BannerAd bannerAd;
private ActivityMainBinding binding;
private AdSize adSize;
private FrameLayout bannerViewContainer;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// 320 is a placeholder value. Replace 320 with your banner container width.
adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, 320);
// Give the banner container a placeholder height to avoid a sudden layout
// shifts when the ad loads.
bannerViewContainer = binding.bannerViewContainer;
LayoutParams bannerLayoutParams = bannerViewContainer.getLayoutParams();
bannerLayoutParams.height = adSize.getHeightInPixels(this);
bannerViewContainer.setLayoutParams(bannerLayoutParams);
// Step 1 - Create a BannerAdRequest object with ad unit ID and size.
BannerAdRequest adRequest = new BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741",
adSize).build();
// Step 2 - Load the ad.
BannerAd.load(
adRequest,
new AdLoadCallback<BannerAd>() {
@Override
public void onAdLoaded(@NonNull BannerAd ad) {
// Assign the loaded ad to the BannerAd object.
bannerAd = ad;
// Step 3 - Call BannerAd.getView() to get the View and add it
// to view hierarchy on the UI thread.
runOnUiThread(
() -> binding.bannerViewContainer.addView(ad.getView(MainActivity.this)));
}
@Override
public void onAdFailedToLoad(@NonNull LoadAdError adError) {
bannerAd = null;
}
});
}
}
Jetpack Compose
// Request an anchored adaptive banner with a width of 360.
val adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(requireContext(), 360)
// Load the ad when the screen is active.
val coroutineScope = rememberCoroutineScope()
val isPreviewMode = LocalInspectionMode.current
LaunchedEffect(context) {
bannerAdState?.destroy()
if (!isPreviewMode) {
coroutineScope.launch {
when (val result = BannerAd.load(BannerAdRequest.Builder(AD_UNIT_ID, adSize).build())) {
is AdLoadResult.Success -> {
bannerAdState = result.ad
}
is AdLoadResult.Failure -> {
showToast("Banner failed to load.")
Log.w(Constant.TAG, "Banner ad failed to load: $result.error")
}
}
}
}
}
광고 새로고침
광고 단위가 새로고침되도록 설정한 경우 광고 로드에 실패했을 때 다른 광고를 요청하지 않아도 됩니다. Google 모바일 광고 SDK (베타)는 AdMob UI에 지정된 새로고침 빈도를 따릅니다. 새로고침을 사용 설정하지 않았다면 새로 요청하세요. 배너 광고에 자동 새로고침 사용에서 새로고침 빈도 설정과 같은 광고 단위 새로고침에 대한 자세한 내용을 참고하세요.
광고 리소스 해제
배너 광고 사용이 끝나면 배너 광고의 리소스를 해제할 수 있습니다.
광고의 리소스를 해제하려면 뷰 계층 구조에서 광고를 삭제하고 모든 참조를 삭제하세요.
Kotlin
// Remove banner from view hierarchy.
val parentView = adView?.parent
if (parentView is ViewGroup) {
parentView.removeView(adView)
}
// Destroy the banner ad resources.
adView?.destroy()
// Drop reference to the banner ad.
adView = null
Java
// Remove banner from view hierarchy.
if (adView.getParent() instanceof ViewGroup) {
((ViewGroup) adView.getParent()).removeView(adView);
}
// Destroy the banner ad resources.
adView.destroy();
// Drop reference to the banner ad.
adView = null;
Jetpack Compose
// Destroy the ad when the screen is disposed.
DisposableEffect(Unit) { onDispose { bannerAdState?.destroy() } }
광고 이벤트
광고 노출 및 클릭, 광고 열기 및 닫기를 비롯한 광고 수명 주기의 여러 이벤트를 수신 대기할 수 있습니다. 배너를 표시하기 전에 콜백을 설정하는 것이 좋습니다.Kotlin
BannerAd.load(
BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
object : AdLoadCallback<BannerAd> {
override fun onAdLoaded(ad: BannerAd) {
ad.adEventCallback =
object : BannerAdEventCallback {
override fun onAdImpression() {
// Banner ad recorded an impression.
}
override fun onAdClicked() {
// Banner ad recorded a click.
}
override fun onAdShowedFullScreenContent() {
// Banner ad showed.
}
override fun onAdDismissedFullScreenContent() {
// Banner ad dismissed.
}
override fun onAdFailedToShowFullScreenContent(
fullScreenContentError: FullScreenContentError
) {
// Banner ad failed to show.
}
}
}
// ...
}
)
자바
BannerAd.load(
new BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
new AdLoadCallback<BannerAd>() {
@Override
public void onAdLoaded(@NonNull BannerAd ad) {
ad.setAdEventCallback(new BannerAdEventCallback() {
@Override
public void onAdImpression() {
// Banner ad recorded an impression.
}
@Override
public void onAdClicked() {
// Banner ad recorded a click.
}
@Override
public void onAdShowedFullScreenContent() {
// Banner ad showed.
}
@Override
public void onAdDismissedFullScreenContent() {
// Banner ad dismissed.
}
@Override
public void onAdFailedToShowFullScreenContent(
@NonNull FullScreenContentError fullScreenContentError) {
// Banner ad failed to show.
}
});
// ...
}
});
광고 새로고침 콜백
배너 광고에 자동 새로고침을 사용하는 경우 BannerAdRefreshCallback
가 광고 새로고침 이벤트를 처리합니다. 뷰 계층 구조에 광고 뷰를 추가하기 전에 콜백을 설정해야 합니다. 광고 새로고침에 대한 자세한 내용은 광고 새로고침을 참고하세요.
Kotlin
BannerAd.load(
BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
object : AdLoadCallback<BannerAd> {
override fun onAdLoaded(ad: BannerAd) {
ad.bannerAdRefreshCallback =
object : BannerAdRefreshCallback {
// Set the ad refresh callbacks.
override fun onAdRefreshed() {
// Called when the ad refreshes.
}
override fun onAdFailedToRefresh(loadAdError: LoadAdError) {
// Called when the ad fails to refresh.
}
}
// ...
}
}
)
자바
BannerAd.load(
new BannerAdRequest.Builder("ca-app-pub-3940256099942544/9214589741", adSize).build(),
new AdLoadCallback<BannerAd>() {
@Override
public void onAdLoaded(@NonNull BannerAd ad) {
ad.setBannerAdRefreshCallback(
// Set the ad refresh callbacks.
new BannerAdRefreshCallback() {
@Override
public void onAdRefreshed() {
// Called when the ad refreshes.
}
@Override
public void onAdFailedToRefresh(@NonNull LoadAdError adError) {
// Called when the ad fails to refresh.
}
});
// ...
}
});
동영상 광고의 하드웨어 가속
배너 광고 뷰에 동영상 광고가 제대로 표시되려면 하드웨어 가속이 사용 설정되어 있어야 합니다.
하드웨어 가속은 기본적으로 사용 설정되지만, 일부 앱에서는 이를 사용 중지할 수 있습니다. 앱에서 하드웨어 가속이 사용 중지되었다면 광고를 사용하는 Activity
클래스에 하드웨어 가속을 사용 설정할 것을 권장합니다.
하드웨어 가속 사용 설정
하드웨어 가속이 전체적으로 사용 중인 상태에서 앱이 제대로 작동하지 않으면 개별 활동에 맞게 하드웨어 가속을 설정할 수 있습니다. 하드웨어 가속을 사용 설정하거나 중지하려면 AndroidManifest.xml
에서 <application>
및 <activity>
요소에 android:hardwareAccelerated
속성을 사용하세요. 다음 예에서는 앱 전체에서 하드웨어 가속을 사용하고 있지만, 활동 하나에 대해서는 하드웨어 가속을 사용 중지했습니다.
<application android:hardwareAccelerated="true">
<!-- For activities that use ads, hardwareAcceleration should be true. -->
<activity android:hardwareAccelerated="true" />
<!-- For activities that don't use ads, hardwareAcceleration can be false. -->
<activity android:hardwareAccelerated="false" />
</application>
하드웨어 가속을 관리하는 옵션에 대해 자세히 알아보려면 하드웨어 가속 관련 가이드를 참고하세요. 활동이 중지된 경우에는 개별 광고 뷰에서 하드웨어 가속을 사용 설정할 수 없으므로 활동 자체에 하드웨어 가속이 사용 설정되어야 합니다.
Google 모바일 광고 SDK (베타)의 사용을 보여 주는 예시 앱을 다운로드하여 실행합니다.