# Android에서 배너 광고 구현

> Android 앱에서 배너 광고를 구현합니다. 배너 뷰 오브젝트를 생성하고 레이아웃에 표시하고 리스너를 사용하여 광고 이벤트를 관리합니다.

> **Note:**
>
> Unity Ads를 초기화한 후 배너 광고를 표시해야 합니다.

배너 광고를 사용하려면 특정 유형의 배너 전용 [광고 단위](/grow/dashboard/ad-units.md)가 필요합니다.

다른 뷰와 마찬가지로 배너 뷰 오브젝트를 뷰 계층 구조에 배치할 수 있습니다. 그러면 각 배너 인스턴스의 위치를 커스터마이즈하거나 여러 배너를 표시할 수 있습니다.

> **Note:**
>
> app-ads.txt는 광고 생태계의 부정 행위를 근절하고 투명성을 구축하기 위한 IAB 이니셔티브입니다. 설명된 대로 app-ads.txt를 구현해야 합니다. 그렇지 않으면 배너 수요가 크게 줄어듭니다.

## 스크립트 구현##script-implementation

다음 스크립트 샘플은 화면에 두 개의 배너 광고와 이를 테스트하기 위한 버튼을 표시하는 구현 예제입니다.

이 예제에서는 여러 배너 뷰 오브젝트에 단일 리스너를 사용합니다. 배너 뷰 오브젝트별로 다른 리스너를 사용할 수도 있습니다.

> **Note:**
>
> Unity Ads는 현재 실행 중인 작업에 대한 액세스 권한이 필요하므로 다음 예에서는 `getApplicationContext()`를 사용합니다.
> 이는 모든 구현에 적합하지 않을 수 있으므로 일부 커스터마이징이 필요할 수 있습니다(연동에 따라 다름).

### MREC 배너 포맷 구현##implementing-the-mrec-banner-format

앱에 MREC(중간 직사각형) 크기의 광고 포맷을 표시하려면 300x250, 300x300, 450x450과 같이 적절한 크기를 사용해야 합니다. 특히 300x250 MREC 배너 광고의 경우 다음 예제 코드에서 아래 값을 변경합니다.

```java
new UnityBannerSize(320, 50)
```

조정된 크기는 다음과 같습니다.

```java
new UnityBannerSize(300, 250)
```

#### 배너 광고 예시##banner-ad-example

1. **Java**

   ```java
    import androidx.appcompat.app.AppCompatActivity;
    import android.os.Bundle;

    import com.unity3d.ads.IUnityAdsInitializationListener;
    import com.unity3d.ads.UnityAds;
    import com.unity3d.services.banners.BannerErrorInfo;
    import com.unity3d.services.banners.BannerView;
    import com.unity3d.services.banners.UnityBannerSize;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.RelativeLayout;

    public class ShowBanners extends AppCompatActivity implements IUnityAdsInitializationListener {

      String unityGameID = "1234567";
      Boolean testMode = true;
      String topAdUnitId = "topBanner";
      String bottomAdUnitId = "bottomBanner";

      // Listener for banner events:
      private BannerView.IListener bannerListener = new BannerView.IListener() {
        @Override
        public void onBannerLoaded(BannerView bannerAdView) {
          // Called when the banner is loaded.
          Log.v("UnityAdsExample", "onBannerLoaded: " + bannerAdView.getPlacementId());
          // Enable the correct button to hide the ad
          (bannerAdView.getPlacementId().equals("topBanner") ? hideTopBannerButton : hideBottomBannerButton).setEnabled(true);
        }

        @Override
        public void onBannerFailedToLoad(BannerView bannerAdView, BannerErrorInfo errorInfo) {
          Log.e("UnityAdsExample", "Unity Ads failed to load banner for " + bannerAdView.getPlacementId() + " with error: [" + errorInfo.errorCode + "] " + errorInfo.errorMessage);
          // Note that the BannerErrorInfo object can indicate a no fill (refer to the API documentation).
        }

        @Override
        public void onBannerClick(BannerView bannerAdView) {
          // Called when a banner is clicked.
          Log.v("UnityAdsExample", "onBannerClick: " + bannerAdView.getPlacementId());
        }

        @Override
        public void onBannerLeftApplication(BannerView bannerAdView) {
          // Called when the banner links out of the application.
          Log.v("UnityAdsExample", "onBannerLeftApplication: " + bannerAdView.getPlacementId());
        }
      };

      // This banner view object will be placed at the top of the screen:
      BannerView topBanner;
      // This banner view object will be placed at the bottom of the screen:
      BannerView bottomBanner;
      // View objects to display banners:
      RelativeLayout topBannerView;
      RelativeLayout bottomBannerView;
      // Buttons to show the banners:
      Button showTopBannerButton;
      Button showBottomBannerButton;
      // Buttons to destroy the banners:
      Button hideTopBannerButton;
      Button hideBottomBannerButton;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Initialize Unity Ads:
        UnityAds.initialize(getApplicationContext(), unityGameID, testMode, this);

        // Set up a button to load the top banner when clicked:
        showTopBannerButton = findViewById(R.id.loadTopBanner);
        // Set up a button to load the bottom banner when clicked:
        showBottomBannerButton = findViewById(R.id.loadBottomBanner);
        // Set up a button to destroy the top banner when clicked:
        hideTopBannerButton = findViewById(R.id.hideTopBanner);
        // Set up a button to destroy the bottom banner when clicked:
        hideBottomBannerButton = findViewById(R.id.hideBottomBanner);

        showTopBannerButton.setEnabled(false);
        showBottomBannerButton.setEnabled(false);
        hideTopBannerButton.setEnabled(false);
        hideBottomBannerButton.setEnabled(false);

        showTopBannerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          showTopBannerButton.setEnabled(false);
          // Create the top banner view object:
          topBanner = new BannerView(view.getContext(), topAdUnitId, new UnityBannerSize(320, 50));
          // Set the listener for banner lifecycle events:
          topBanner.setListener(bannerListener);
          topBannerView = findViewById(R.id.topBanner);
          LoadBannerAd(topBanner, topBannerView);
      }
    });

    showBottomBannerButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
            showBottomBannerButton.setEnabled(false);
            // Create the bottom banner view object:
            bottomBanner = new BannerView(view.getContext(), bottomAdUnitId, new UnityBannerSize(320, 50));
            // Set the listener for banner lifecycle events:
            bottomBanner.setListener(bannerListener);
            bottomBannerView = findViewById(R.id.bottomBanner);
            LoadBannerAd(bottomBanner, bottomBannerView);
      }
    });

    hideTopBannerButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
            // Remove content from the banner view:
            topBannerView.removeAllViews();
            // Remove the banner variables:
            topBannerView = null;
            topBanner = null;
            showTopBannerButton.setEnabled(true);
      }
    });

    hideBottomBannerButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
            // Remove content from the banner view:
            bottomBannerView.removeAllViews();
            // Remove the banner variables:
            bottomBannerView = null;
            bottomBanner = null;
            showBottomBannerButton.setEnabled(true);
        }
      });
    }

      public void LoadBannerAd(BannerView bannerView, RelativeLayout bannerLayout) {
        // Request a banner ad:
        bannerView.load();
        // Associate the banner view object with the banner view:
        bannerLayout.addView(bannerView);
      }

      @Override
      public void onInitializationComplete() {
        // Enable the show ad buttons because ads can now be loaded
        showTopBannerButton.setEnabled(true);
        showBottomBannerButton.setEnabled(true);
      }

      @Override
      public void onInitializationFailed(UnityAds.UnityAdsInitializationError error, String message) {
      }
    }
   ```

**다음 단계**: [수익화 전략](/grow/ads/monetization-strategy.md) 가이드를 검토하고 [구현 내용을 테스트](/grow/ads/optimization/test-ads-integration.md)하십시오.
