Android Studio 加 Admob 步驟(2016/12/09)

官網文件連結
https://firebase.google.com/docs/admob/android/quick-start

1.在Firebase建立新project
https://firebase.google.com/docs/android/setup
1.1設定
此處的 app id 要和 Android Studio 裡的 package name 完全相同
否則會錯
例:
1.2下載 google-services.json
1.3修改 專案層級 的 build.gradle
buildscript {
dependencies {
// Add this line
classpath ‘com.google.gms:google-services:3.0.0’
}
}
1.4修改 app 層級的 build.gradle

//Add to the bottom of the file
dependencies {
//    compile ‘com.google.firebase:firebase-ads:9.8.0’    //Admob
compile ‘com.google.firebase:firebase-ads:9.2.1’    //Admob
}

// Add to the bottom of the file
apply plugin: ‘com.google.gms.google-services’

1.5點 Android Studio 裡 gradle 的 Sync Now

2.修改 strings.xml
加這列
<string name=”banner_ad_unit_id”>ca-app-pub-1234581776212345/1234512345</string>

3.修改 layout/xxxActivity.xml
加 namespace
xmlns:ads=”http://schemas.android.com/apk/res-auto”
加 adView element
<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>

4.修改 MainActivity.java
import com.google.android.gms.ads.AdRequest;//Admob
import com.google.android.gms.ads.AdView;//Admob
import com.google.android.gms.ads.MobileAds;//Admob

protected void onCreate(Bundle savedInstanceState) {

//Add the following lines
//————————————
// Admob
//————————————
MobileAds.initialize(getApplicationContext(), getString(R.string.banner_ad_unit_id));//Admob
AdView mAdView = (AdView) findViewById(R.id.adView);
com.google.android.gms.ads.AdRequest.Builder builder = new com.google.android.gms.ads.AdRequest.Builder();
//        builder.addTestDevice(“12345123451234512345123451234512″);
//        AdRequest adRequest = new AdRequest.Builder().build();
com.google.android.gms.ads.AdRequest adRequest = builder.build();
mAdView.loadAd(adRequest);
}

5.修改 AndroidManifest.xml

<uses-permission android:name=”android.permission.INTERNET” /><!–<ff>for Admob</ff>–>

6.修改 layout/xxx.xml

<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>

This entry was posted in Android development. Bookmark the permalink.

Leave a Reply

Your email address will not be published.