1. 添加 sdk/extras/google/google_play_services/libproject/google-play-services_lib 到当前工程
2. 在项目属性中->Android中添加google-play-services_lib
3. 在 AndroidManifest.xml 中添加权限
<!-- 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
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<!-- 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 文件中添加
在layout最上层容器控件添加xmlns属性
xmlns:ads="http://schemas.android.com/apk/res-auto"
添加ads控件
<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() 中添加代码
AdView mAdView = (AdView) findViewById(R.id.adView); mAdView.setAdListener(new AdListener(){}); mAdView.loadAd(new AdRequest.Builder().build());
5.2 使用基于代码的AdView控件,在YourActivityt 文件中添加代码,
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());
6. 最重要的,申请 ads id,填入到字串资源 ad_unit_id,以下填入你自己的 ads id
<string name="ad_unit_id">a15273abf6a0db9</string>
另外,ads 需要符合一定规范来防止侵犯用户使用体验,具体可参考http://developer.android.com/distribute/googleplay/policies/ads.html