Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 應用如何接入 Google 廣告(AdMob)

編輯:關於 Android 程式設計

為應用接入廣告是變現的常見手段。本文以 Google Play Services 中的 AdMob 為例,介紹從工程配置到代碼接入的完整步驟。

一、引入 Google Play Services 庫

  1. 將 sdk/extras/google/google_play_services/libproject/google-play-services_lib 添加到當前工程。
  2. 在項目屬性 → Android 中,把 google-play-services_lib 添加為依賴庫。

二、添加權限

在 AndroidManifest.xml 中加入網絡相關權限:

<!-- 用於請求 banner 與插屏廣告 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 用於在無網絡時避免發送廣告請求 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

三、聲明 AdActivity

在 AndroidManifest.xml 的 <application> 中添加 AdActivity:

<!-- 展示廣告覆蓋層所需的 Activity -->
<activity
    android:name="com.google.android.gms.ads.AdActivity"
    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

若應用的 target SDK 版本過低,screenSize | smallestScreenSize 這兩個參數可能無效。此時不要為通過編譯而刪除它們,否則運行時廣告區域會顯示警告:missing AdActivity with android:configChanges in androidManifest.xml。正確做法是在項目屬性 → Android 中選擇更高版本的 Project Build Target(如 Android 4.3 及以上)。

四、添加 AdView 控件

先在 Activity 中引入命名空間:

import com.google.android.gms.ads.*;

方式一:基於 XML 布局

在對應的布局文件中添加 AdView:

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    ads:adSize="BANNER"
    ads:adUnitId="@string/ad_unit_id"/>

注意需保證根布局帶有 xmlns:ads="https://schemas.android.com/apk/res-auto" 命名空間聲明。接著在 onCreate 中加載廣告:

AdView mAdView = (AdView) findViewById(R.id.adView);
mAdView.setAdListener(new AdListener() {});
mAdView.loadAd(new AdRequest.Builder().build());

方式二:純代碼創建

如果不使用 XML 布局,也可以在代碼中動態創建 AdView 並添加到容器:

setContentView(R.layout.your_layout);
ViewGroup contentView = (ViewGroup) findViewById(R.id.yourlayout_id); // 獲得布局容器
AdView mAdView = new AdView(this);
mAdView.setAdUnitId(getString(R.string.ad_unit_id));
mAdView.setAdSize(AdSize.BANNER);
mAdView.setAdListener(new AdListener() {});
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
contentView.addView(mAdView, params);
mAdView.loadAd(new AdRequest.Builder().build());

五、申請廣告位 ID

最重要的一步,是申請屬於自己的 ads id,並填入字符串資源 ad_unit_id:

<string name="ad_unit_id">a15273abf6a0db9</string>

把上面的示例值換成你在 AdMob 後台申請到的真實廣告位 ID 即可。完成以上步驟後,重新編譯運行,就能在應用中看到廣告展示。實際接入時,還需注意遵守平台政策、合理選擇廣告形式與展示時機,以免影響用戶體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved