1. 添加 sdk/extras/google/google_play_services/libproject/google-play-services_lib 到當前工程
2. 在項目屬性中->Android中添加google-play-services_lib
3. 在 AndroidManifest.xml 中添加權限
[cpp]
<!-- Used to request banner and interstitial ads. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Used to avoid sending an ad request if there is no connectivity. -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
4. 在 AndroidManifest.xml 的 <Application> 中添加AdActivity
[cpp]
<!-- Activity required to show ad overlays. -->
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
如果你的應用基於的 SDK版本過低,則 android:configChanges 中 screenSize | smallestScreenSize 參數無效,不能刪除這兩個屬性來通過編譯,否則會發現廣告顯示區顯示的是警告信息:missing AdActivity with android:configChanges in androidManifest.xml 只能考慮在 項目屬性中->Android標簽中選擇高版本Project Build Target,比如 Android 4.3
5. 添加AdView控件
在YourActivity文件中添加 import com.google.android.gms.ads.*;
5.1 使用基於 xml layout文件的AdView控件,在相應 yourLayout 文件中添加
[cpp]
<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"/>
在相應 YourActivity 的onCreate() 中添加代碼
[cpp]
<pre name="code" class="cpp"><pre name="code" class="cpp"> AdView mAdView = (AdView) findViewById(R.id.adView);
mAdView.setAdListener(new AdListener(){});
mAdView.loadAd(new AdRequest.Builder().build());</pre></pre>
5.2 使用基於代碼的AdView控件,在YourActivityt 文件中添加代碼,
[cpp]
<pre name="code" class="cpp"><pre name="code" class="cpp"><pre name="code" class="cpp"> setContentView(R.layout.your_layout);
ViewGroup contentView = (ViewGroup)findViewById(R.id.yourlayout_id); // 獲得layout中的布局控件
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());</pre></pre></pre>
6. 最重要的,申請 ads id,填入到字串資源 ad_unit_id,以下填入你自己的 ads id
[cpp]
<string name="ad_unit_id">a15273abf6a0db9</string>