This Blog is in continuation with our previous blog “Beginner’s Guide to AdMob – a Portmanteau for “Advertising on Mobile” where we talked all about AdMob and how to monetize your App with Ads. Here we will go a step forward and talk about how to actually write code for the App to create AdMob in it.
Below we will be discussing the code: AdMob
Create a Sample Application for Two Types of AdMob about Banner Ad and Interstitial Ad. First we will talk about Banner Ad.
Banner Ad App:
- First of all add the code for Google Ad services in build.gradle file In dependencies:
1 |
compile 'com.google.android.gms:play-services:7.0.0' |
2. In the manifest file i.e AndroidManifest.xml add below code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.google.android.gms.example.bannerexample" > <!-- Include required permissions for Google Mobile Ads to run--> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <!--This meta-data tag is required to use Google Play Services.--> <meta-data android:name="com.google.android.gms.version"/> <activity android:name=".MyActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--Include the AdActivity configChanges and theme. --> <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" /> </application> </manifest> |
3. Add your banner Ad unit ID to string.xml file:
1 2 |
<!-- This is an ad unit ID for a test ad. Replace with your own banner ad unit id. --> <string name="banner_ad_uncait_id">-app-pub-3940256099942544/6300978111</string> |
Note: This banner ID key is for my Ad. Since you have already learn how to generate banner ID key, create a new Ad ID for your app.
4. Add below code to MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
package com.google.android.gms.example.bannerexample; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; public class MyActivity extends AppCompatActivity { private AdView mAdView; private WebView webview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); mAdView = (AdView) findViewById(R.id.ad_view); AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .build(); mAdView.loadAd(adRequest); webview = (WebView) findViewById(R.id.webView); webview.getSettings().setJavaScriptEnabled(true); webview.loadUrl(" https://acadgild.com/blog/category/android/"); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.my, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onPause() { if (mAdView != null) { mAdView.pause(); } super.onPause(); } @Override public void onResume() { super.onResume(); if (mAdView != null) { mAdView.resume(); } } @Override public void onDestroy() { if (mAdView != null) { mAdView.destroy(); } super.onDestroy(); } } |
5. Add this code to design your ad in “activity_main.xml” file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<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" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="@dimen/activity_vertical_margin" tools:context=".MyActivity" tools:ignore="MergeRootFrame"> <com.google.android.gms.ads.AdView android:id="@+id/ad_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" ads:adSize="BANNER" ads:adUnitId="@string/banner_ad_unit_id" /> <WebView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/webView" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_above="@+id/ad_view" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> </RelativeLayout> |
Run the code and you will see the output as shown in figure below:
With this we have successfully learnt how to create and display Ad at the bottom of the page. Now we will see how to create an Interstitial Ad in the App.
Interstitial Ad App
1. First of all add the code for Google Ad services in build.gradle file In dependencies
1 |
compile 'com.google.android.gms:play-services:7.0.0' |
2. In the manifest file i.e AndroidManifest.xml add below code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.google.android.gms.example.interstitialexample" > <!-- Include required permissions for Google Mobile Ads to run. --> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <!--This meta-data tag is required to use Google Play Services. --> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/> <activity android:name=".MyActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--Include the AdActivity configChanges and theme. --> <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" /> </application> </manifest> |
3. Add this code to design your ad in “activity_main.xml” file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MyActivity" tools:ignore="MergeRootFrame"> <TextView android:id="@+id/game_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="@string/impossible_game" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/timer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/game_title" android:layout_centerHorizontal="true" android:textAppearance="?android:attr/textAppearanceLarge" /> <Button android:id="@+id/retry_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="Retry" /> </RelativeLayout> |
4. Add below code to MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
package com.google.android.gms.example.interstitialexample; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.InterstitialAd; public class MyActivity extends ActionBarActivity { private static final long GAME_LENGTH_MILLISECONDS = 3000; private InterstitialAd mInterstitialAd; private CountDownTimer mCountDownTimer; private Button mRetryButton; private boolean mGameIsInProgress; private long mTimerMilliseconds; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); // Create the InterstitialAd and set the adUnitId. mInterstitialAd = new InterstitialAd(this); // Defined in res/values/strings.xml mInterstitialAd.setAdUnitId(getString(R.string.ad_unit_id)); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { startGame(); } }); mRetryButton = ((Button) findViewById(R.id.retry_button)); mRetryButton.setVisibility(View.INVISIBLE); mRetryButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showInterstitial(); } }); startGame(); } private void createTimer(final long milliseconds) { if (mCountDownTimer != null) { mCountDownTimer.cancel(); } final TextView textView = ((TextView) findViewById(R.id.timer)); mCountDownTimer = new CountDownTimer(milliseconds, 50) { @Override public void onTick(long millisUnitFinished) { mTimerMilliseconds = millisUnitFinished; textView.setText("seconds remaining: " + ((millisUnitFinished / 1000) + 1)); } @Override public void onFinish() { mGameIsInProgress = false; textView.setText("done!"); mRetryButton.setVisibility(View.VISIBLE); } }; } @Override public void onResume() { // Start or resume the game. super.onResume(); if (mGameIsInProgress) { resumeGame(mTimerMilliseconds); } } @Override public void onPause() { // Cancel the timer if the game is paused mCountDownTimer.cancel(); super.onPause(); } private void showInterstitial() { // Show the ad if it's ready. Otherwise toast and restart the game. if (mInterstitialAd != null && mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } else { Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show(); startGame(); } } private void startGame() { if (!mInterstitialAd.isLoaded() && !mInterstitialAd.isLoaded()) { AdRequest adRequest = new AdRequest.Builder().build(); mInterstitialAd.loadAd(adRequest); } mRetryButton.setVisibility(View.INVISIBLE); resumeGame(GAME_LENGTH_MILLISECONDS); } private void resumeGame(long milliseconds) { mGameIsInProgress = true; mTimerMilliseconds = milliseconds; createTimer(milliseconds); mCountDownTimer.start(); } } |
Run this code and you will get an output as shown in figure below:
Hope with these two blogs you now have a clear idea on how to create Ad in your App using AdMob.
Can i get a examle of web view app with admob