# AdMob

## 1. 기본 요건

* [<mark style="color:blue;">ADX Unity SDK</mark>](/adx/unity/integrate.md)를 프로젝트에 추가합니다.
* Rewarded Ad용으로 발급받은 <mark style="color:red;">**AdMob Ad Unit ID**</mark>를 사용합니다.
* 광고를 요청하기 전에 [<mark style="color:blue;">SDK 초기화</mark>](/adx/unity/sdk-integration/initialize.md)를 먼저 진행합니다.
  * **SDK 초기화는 앱 실행 시 한 번만 호출**하여 주시고, **광고 요청은 초기화가 완료된 후**에 이뤄져야 합니다.
* Unity > Assets > Google Mobile Ads > Settings를 선택하여 각 필드에 Android 및 iOS App ID를 입력합니다.

![](/files/S4hxQCWkuGjtrCU0C7cM)

## 2. 구현

{% hint style="info" %}
보상 광고 로드에 시간이 걸릴 수 있으니, 미리 로드 해두신 다음 사용하시는 것을 권장드립니다.
{% endhint %}

1\) Android와 iOS 모두 배포된 경우 플랫폼 별로 발급받은 Ad Unit ID를 입력합니다.

```csharp
#if UNITY_ANDROID
    string admobRewardedAdUnitID = "<ANDROID_ADMOB_REWARDED_AD_UNIT_ID>";
#elif UNITY_IOS
    string admobRewardedAdUnitID = "<IOS_ADMOB_REWARDED_AD_UNIT_ID>";
#endif
```

2\) 광고 로드에 사용되는 **AdRequest** 객체 생성 후, **RewardedAd** 클래스의 정적 메소드 '**Load**' 를 이용하여 광고를 로드 합니다.

{% hint style="info" %}
GDPR 관련 규정을 준수하는 경우, 사용자가 개인정보 활용 및 수집을 거부한 상태(2)일 때 **AdRequest**의 **Extras** 딕셔너리에 "**npa**" 키에 "1"를 추가합니다.
{% endhint %}

```csharp
using AdxUnityPlugin;
using GoogleMobileAds.Api;
...
private GoogleMobileAds.Api.RewardedAd admobRewardedAd;
...

void LoadAdmobRewardedAd()
{ 
    // Create our request used to load the ad.       
    AdRequest adRequest = new AdRequest();
    if (ADXGDPRManager.GetConsentState() == 2) {
        // Extra parameters to be sent in the ad request.
        adRequest.Extras["npa"] = "1";
    }

    // Load a rewarded ad
    GoogleMobileAds.Api.RewardedAd.Load(
        admobRewardedAdUnitID, 
        adRequest, (GoogleMobileAds.Api.RewardedAd ad, LoadAdError loadError) => {
            if (loadError != null){
                Debug.Log("Admob Rewarded ad failed to load with error: " 
                + loadError.GetMessage());
                return;
            } else if (ad == null){
                Debug.Log("Admob Rewarded ad failed to load.");
                return;
            }
            Debug.Log("Admob Rewarded ad loaded.");
            admobRewardedAd = ad;
    });
}
```

3\) 광고 로드에 성공하면, 광고 표시와 관련된 이벤트를 수신 받기 위해서 이벤트 핸들러를 등록합니다.

```csharp
...
private GoogleMobileAds.Api.RewardedAd admobRewardedAd;
...

void LoadAdmobRewardedAd()
{        
    ...
    // Load a rewarded ad
    GoogleMobileAds.Api.RewardedAd.Load(
        admobRewardedAdUnitId, 
        adRequest, (GoogleMobileAds.Api.RewardedAd ad, LoadAdError loadError) => {
            ...
            admobRewardedAd = ad;
            // Register to ad events to extend functionality.
            RegisterEventHandlers(ad);
    });
}

void RegisterEventHandlers(GoogleMobileAds.Api.RewardedAd ad)
{
    // Raised when the ad is estimated to have earned money.
    ad.OnAdPaid += (AdValue adValue) => {
        // a user reward is earned.
        Debug.Log(String.Format("Rewarded ad paid {0} {1}.",
            adValue.Value,
            adValue.CurrencyCode));
    };
    // Raised when an impression is recorded for an ad.
    ad.OnAdImpressionRecorded += () => {
        Debug.Log("Rewarded ad recorded an impression.");
    };
    // Raised when a click is recorded for an ad.
    ad.OnAdClicked += () => {
        Debug.Log("Rewarded ad was clicked.");
    };
    // Raised when the ad opened full screen content.
    ad.OnAdFullScreenContentOpened += () => {
        Debug.Log("Rewarded ad full screen content opened.");
    };
    // Raised when the ad closed full screen content.
    ad.OnAdFullScreenContentClosed += () => {
        Debug.Log("Rewarded ad full screen content closed.");
    };
    // Raised when the ad failed to open full screen content.
    ad.OnAdFullScreenContentFailed += (AdError error) => {
        Debug.LogError("Rewarded ad failed to open full screen content with error : "
            + error);
    };
}
```

{% hint style="info" %}
유저가 광고 보상을 획득하면, **OnAdPaid** 이벤트 핸들러가 호출됩니다. 이 핸들러에서 유저에게 제공할 보상과 관련된 코드를 추가합니다.\
\
OnAdPaid 이벤트가 수신되지 않으면, 애드몹 대쉬보드에 로그인 후, 아래 경로로 이동하여 "노출 수준 광고 수익" 이 활성화 되어 있는지 확인하십시오.\
\
**애드몹 대쉬보드 > 설정 > 계정 정보 > 노출 수준 광고 수익**
{% endhint %}

{% hint style="info" %}
이전 광고가 닫힌 직후에 다음 보상형 광고가 로드될 수 있도록 **OnAdFullScreenContentClosed** 핸들러에서 다른 보상형 광고를 로드하는 것이 좋습니다.
{% endhint %}

4\) **CanShowAd** 메소드로 광고를 표시할 수 있는 지 확인 후, **Show** 메소드로 광고를 표시합니다.

```csharp
void ShowAdmobRewardedAd()
{
    if (admobRewardedAd != null && admobRewardedAd.CanShowAd()){
        admobRewardedAd.Show((Reward reward) => {
            Debug.Log("Admob Rewarded ad granted a reward: " + reward.Amount);
        });
    } else{
        Debug.Log("Admob Rewarded ad cannot be shown.");
    }
}
```

## 3. 타겟팅

광고 요청 시 [<mark style="color:blue;">타겟팅</mark>](https://developers.google.com/admob/unity/targeting) 정보를 설정할 수 있습니다. 필요에 따라 구현해주세요.

1\) 아동 대상 설정 ([<mark style="color:blue;">아동 온라인 개인정보 보호법(COPPA)</mark>](https://www.ftc.gov/tips-advice/business-center/privacy-and-security/children's-privacy))

```csharp
RequestConfiguration requestConfiguration = new RequestConfiguration {
    TagForChildDirectedTreatment = TagForChildDirectedTreatment.True
};
MobileAds.SetRequestConfiguration(requestConfiguration);
```

2\) 광고 콘텐츠 필터링

```csharp
MobileAds.SetRequestConfiguration(requestConfiguration);
2) 광고 콘텐츠 필터링
RequestConfiguration requestConfiguration = new RequestConfiguration {
    MaxAdContentRating = MaxAdContentRating.G
};
MobileAds.SetRequestConfiguration(requestConfiguration);
```

## 4. 테스트 기기 등록

개발 중 상용 광고 키로 광고를 테스트하려는 경우 아래 단계에 따라 테스트 기기를 등록 후 사용해주시기 바랍니다.

{% hint style="danger" %}
테스트 기기 미등록 상태로 테스트할 경우 계정이 정지될 수 있습니다.
{% endhint %}

1\) ADXLibrary를 적용 후 광고를 로드하는 코드가 삽입된 상태로 실행해주시면 콘솔에서 해당 로그를 확인하실 수 있습니다.

{% tabs %}
{% tab title="Android" %}

```java
 I/Ads: Use RequestConfiguration.Builder
  .setTestDeviceIds(Arrays.asList("33BE2250B43518CCDA7DE426D04EE231"))
to get test ads on this device."
```

{% endtab %}

{% tab title="iOS" %}

```objectivec
<Google> To get test ads on this device, set: 
 GADMobileAds.sharedInstance.requestConfiguration
  .testDeviceIdentifiers = @[ @"aa20271272d6558e1bff61b329dd436c" ];
```

{% endtab %}
{% endtabs %}

2\) 출력된 Device ID를 복사하여 아래와 같이 `SetTestDeviceIds()` 를 호출하여 테스트 기기를 등록해주시면 됩니다.

{% hint style="info" %}
앱을 출시하기 전에 테스트 기기를 설정하는 코드를 반드시 삭제하세요.
{% endhint %}

```csharp
List<string> deviceIds = new List<string>();
deviceIds.Add("33BE2250B43518CCDA7DE426D04EE231");
deviceIds.Add("2077ef9a63d2b398840261c8221a0c9b");
RequestConfiguration requestConfiguration = new RequestConfiguration
    .Builder()
    .SetTestDeviceIds(deviceIds)
    .build();

MobileAds.SetRequestConfiguration(requestConfiguration);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://platform-business.gitbook.io/adx/unity/sdk-integration/ad-formats/rewarded-ad-hidden/admob.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
