2015-12-24

【Android Studio】置入 AdMob 播廣告 - 插頁式廣告(InterstitialAd)篇

參考資料 ----
插頁式廣告
不允許的插頁式廣告導入方式

若您在 app 層級的 build.gradle 所相依的 AdMob 套件版本在 20(含) 以上,請參考


本篇筆記的重點在 app 一啟動即顯示插頁式廣告
===== 2023.04.03 =====
但這種做法違反 AdMob 政策!所以參考程式碼就好 😒

先以 Android Studio 精靈建立新專案

進行修改

修改後的 activity_main.xml
  1.  
  2. <RelativeLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. tools:context="com.test.adtest.MainActivity">
  8.  
  9. <!-- view for AdMob Interstitial Ad -->
  10. <TextView
  11. android:id="@+id/app_title"
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:layout_centerHorizontal="true"
  15. android:layout_marginTop="50dp"
  16. android:text="@string/interstitial_ad_sample"
  17. android:textAppearance="?android:attr/textAppearanceLarge"/>
  18. </RelativeLayout>
  19.  

修改後的 MainActivity.java
  1.  
  2. package com.test.adtest;
  3.  
  4. import com.google.android.gms.ads.AdListener;
  5. import com.google.android.gms.ads.AdRequest;
  6. import com.google.android.gms.ads.InterstitialAd;
  7.  
  8. import android.os.Bundle;
  9. import android.support.v7.app.AppCompatActivity;
  10.  
  11. public class MainActivity extends AppCompatActivity
  12. {
  13. private InterstitialAd mInterstitialAd;
  14.  
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState)
  17. {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_main);
  20.  
  21. mInterstitialAd = new InterstitialAd(this);
  22. mInterstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
  23. requestNewInterstitial();
  24.  
  25. mInterstitialAd.setAdListener(new AdListener()
  26. {
  27. @Override
  28. public void onAdLoaded()
  29. {
  30. mInterstitialAd.show();
  31. }
  32. });
  33. }
  34.  
  35. private void requestNewInterstitial()
  36. {
  37. AdRequest adRequest = new AdRequest.Builder()
  38. .build();
  39. mInterstitialAd.loadAd(adRequest);
  40. }
  41. }
  42.  

string.xml 內容
 
<resources>
    <string name="app_name">Adtest</string>

    <string name="interstitial_ad_sample">Interstitial Ad Sample</string>
    <!-- -
        This is an ad unit ID for an interstitial test ad. Replace with your own interstitial ad unit id.
        For more information, see https://support.google.com/admob/answer/3052638
    <!- -->
    <string name="interstitial_ad_unit_id">ca-app-pub-3940256099942544/1033173712</string>
</resources>
 


第一次啟動時,廣告會比較慢出現,之後就不會了;不過還是可以看得到 MainActivity,再找時間研究如何真正 app 的第一個畫面就是廣告。


 相關筆記 ----
【Android Studio】置入 AdMob 播廣告 - 橫幅廣告(banner)篇
【Android】app 置入 Admob 廣告賺錢