Android使用Google Mob廣告教學
1.
在build.gradle內的dependencies加入
...
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:xx.x.x'
compile 'com.google.android.gms:play-services-ads:10.2.4'
}
...
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:xx.x.x'
compile 'com.google.android.gms:play-services-ads:10.2.4'
}
...
2.
在strings.xml內加入您的廣告單元編號
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">My Application</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string> </resources>
3.
在逾放廣告的最外層Layout加入
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
...
<TextView android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
...
<TextView android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</RelativeLayout>
4. Activity onCreate初始化您的廣告
MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544~3347511713");//改成您的應用程式編號
AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest);
沒有留言:
張貼留言