# Android でのバナー広告の実装

> Android アプリケーションにバナー広告を実装します。バナービューオブジェクトを作成し、レイアウトに表示し、リスナーを使用して広告イベントを管理します。

> **Note:**
>
> バナー広告を表示する前に、Unity Ads を 初期化 する必要があります。

バナー広告には、特定のタイプのバナー専用 [広告ユニット](/grow/dashboard/ad-units.md) が必要です。

他のビューと同様に、バナービューオブジェクトはビュー階層に配置できます。これにより、各バナーインスタンスの位置をカスタマイズしたり、複数のバナーを表示したりできます。

> **Note:**
>
> app-ads.txt は、詐欺に対処し広告エコシステムに透明性をもたらす IAB イニシアチブです。記載されているとおりに app-ads.txt を実装してください。そうしないと、バナーの需要が大幅に減るおそれがあります。

## スクリプトの実装##script-implementation

以下のスクリプトサンプルは、画面に 2 つのバナー広告と、それらをテストするボタンを表示するための実装例です。

この例では、複数のバナービューオブジェクトに単一のリスナーを使用しています。バナービューオブジェクトごとに異なるリスナーを使用することもできます。

> **Note:**
>
> Unity Ads では現在実行中のアクティビティにアクセスする必要があるため、以下の例では `getApplicationContext()` を使用しています。
> これはすべての実装に適しているとは限らないため、(インテグレーションによっては) 一部カスタマイズが必要になる場合があります。

### MREC バナー形式の実装##implementing-the-mrec-banner-format

アプリでミディアムレクタングル (MREC) サイズの広告フォーマットを表示するには、300 x 250、300 x 300、450 x 450 など、適切なサイズを使用する必要があります。具体的には、300 x 250 の 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) します。
