Tuesday, August 4, 2015

Integrating New Google Admob with Banner and Interstitial ads in Android Studio

This guide will show you how to integrate the Google Mobile Ads SDK into a brand new app and use it to display a simple banner ad. It should take about thirty minutes to complete and will give you a good sense of how the SDK functions within an app. If you're new to Google Mobile Ads, this is a great place to start before moving on to more advanced examples.
The ad unit and samples that we provide return test ads. Test ads are always available, even if your account is suspended or disabled. For more information, review the AdMob policies and learn more about invalid activity.
Using live ads during development is against AdMob policy; if you test on live ads, your AdMob account may be suspended.
No two developers have the same level of experience, so we've added occasional notes like this one for those who are new to Android and Android Studio. If you're an expert, feel free to skip them.

Prerequisites

  • Running Android Studio 1.0 or higher
  • Developing for Android level 9 or higher
In order to complete the Get Started guide, you'll need to have Android Studio installed on your development machine. If you don't already have it, see the Android Studio site for instructions on how to download everything you need to get up and running.
If you haven't used Android Studio before, consider running through the First App Tutorial for Android Studio before starting this one.

Creating a new project

In this step, we'll create a brand new project in Android Studio to use for our example. If you don't already have Studio running, go ahead and open it now.

Start the new project wizard

If you see the above welcome screen, select New Project. Otherwise, select File > New Project from the menu. This will bring up the new project wizard:

Name your project

Enter "BannerExample" as the app name, and whatever company domain you use for your apps. Android Studio will automatically determine a good project location, but feel free to change it if you'd like.

Set the required SDK version

On the next screen, select Phone and Tablet for the form factor and a minimum platform SDK version of 9. That's the minimum version supported by the Google Mobile Ads SDK.

Add your main activity

We're keeping it simple for this example, so on this screen select Blank Activity.

Name your activity

On this screen you have the option of choosing names for the app's activity and its related resources. We'll use the default names for this example, so just click the Finish button.

Compile your new project

After clicking Finish, you'll have a working project with a single activity. Try compiling and running it (select Run 'app' from the Run menu). You should see a "Hello world!" message on an otherwise empty gray screen. Don't worry, we'll add some more content in the next steps.
If you're new to developing Android apps, take a look at the tutorials for USB Debugging and Using Virtual Devices. You'll need to do one of those two things in order to run your new app and see what it looks like.

Download the Google Repository



The Google Repository contains gradle artifacts for the Google Mobile Ads SDK, which your app can use to request and display ads. Make sure that you have the latest version by opening up your SDK Manager. You can do this by selecting Tools > Android > SDK Manager.

The SDK Manager

In the Android SDK Manager window, select Google Repository under the Extras folder, then press Install Packages and accept the licenses to download. If the Install Packages button is disabled, don't worry. That just means you already have the latest version, so there's nothing else you need to do in the SDK Manager.

Configuring gradle



Now that the Google Repository is installed, you need to update your app to reference the Google Play Services SDK inside it. You can do this by adding a line to the dependencies in your app-level build.gradle file. Look for it in the BannerExample/app/ folder and open it.

build.gradle

...
dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:22.2.0'
        compile 'com.google.android.gms:play-services-ads:7.5.0'
    }
...
Update the dependencies section to include the latest Google Play services SDK.
You may see a warning message across the top of the Android Studio window indicating that gradle needs to perform a gradle sync. If that's the case, click Sync Now to do so. Gradle will refresh your project's libraries to include the dependency you just added.
Try rebuilding your project (Run 'app' in the Run menu) to make sure everything compiles correctly. You won't see any changes, but including Google Play services is the first step toward getting ads into your app.

Modify the manifest file

Every Android app uses a file called a manifest to inform the Android system about itself. The information typically found in these files includes things like the permissions required by the app, the activities it contains, and so on. For more details on manifests and how they work, check out the App Manifest Intro.
Now that you have a working app that includes Google Play services, it's time to modify the app manifest file to include the permissions, version number, and activity definition that the Mobile Ads SDK requires. OpenBannerExample/app/src/main/AndroidManifest.xml for editing.

AndroidManifest.xml

<?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"
        android:value="@integer/google_play_services_version" />
        <activity
            android:name=".MainActivity"
            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>
There are three changes you need to make:
  1. Add two <uses-permission> tags for INTERNET and ACCESS_NETWORK_STATE. The tag forINTERNET is required and used to access the Internet to make ad requests. ACCESS_NETWORK_STATE is optional, and used to check if an internet connection is available prior to making an ad request.
  2. Add a <meta-data> tag that references the Google Play services version. This lets Android know which version of the service your app expects to use.
  3. Add an <activity> element with configChanges and theme attributes. This activity is used by the SDK when banners are clicked or interstitials are presented, and like any other activity must be declared in the manifest before being presented.
Go ahead and rebuild the project to make sure everything has been done correctly. You should still see the same "Hello world!" message for now. By configuring the App Manifest correctly, though, you've given your app the ability to use Mobile Ads.

Give your app an Ad Unit ID

An Ad Unit ID is a unique identifier given to the places in your app where ads are displayed. If you had an app with two activities, for example, each displaying a banner, you'd have two ad units, each with its own ID. AdMob ad unit IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN
In order for your new app to display an ad, it needs to include an Ad Unit ID. Open your app's string resource file, which is found at BannerExample/app/src/main/res/values/strings.xml.

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>
Add a new <string> tag as shown. Note that the Ad Unit ID provided above is just for testing. It will allow you to retrieve a sample banner ad and make sure your implementation is correct. You should always use test ads when developing and testing your app--testing with live production ads is a violation of AdMob policy and could cause your account to be suspended. See the addTestDevice method documentation for information on how to get test ads with your own Ad Unit IDs.
While it's not a requirement, storing your Ad Unit ID values in a resource file is a good practice. As your app grows and your ad publishing needs mature, you will occasionally find that you want to change the ID values. If you make sure they're always in a resource file, you'll never have to search through your code looking for them.

Place an AdView in your main activity layout

Layout files contain XML definitions for the visual design of things like activities, fragments, and list items. In this step, we'll be modifying the layout file for the main activity so that it includes an AdView at the bottom. You can add things to an activity progammatically via Java code, but layout files offer better separation of presentation and behavior.
There are only two steps remaining before your app is ready to show an ad. First, you'll need to modify your main activity's layout to include an AdView. OpenBannerExample/app/src/main/res/layout/activity_main.xml in the editor.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <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>
Add these to the XML:
  1. An additional namespace used for ads:
    http://schemas.android.com/apk/res-auto
    
  2. A new element for your AdView. You'll be asked to provide layout_width and layout_height. You can set both to wrap_content. In the AdView tag, set the adSize to BANNER and the adUnitId to@string/banner_ad_unit_id.
If you look at the last parameter in the AdView tag, you'll see that it's called adUnitId. This is the Ad Unit ID that the AdView will use when requesting ads. In this case, we've given it a reference to the string resource you added in the last step, so the AdView will use that value.

Load the ad in the MainActivity class

The last change needed is for you to add to your app's main activity class some Java code that will load an ad into the AdView.
Open your MainActivity.java file. It will be in the BannerExample/app/src/main/java/ folder, though the exact subdirectory path will vary based on the domain you used when creating your project above. Once it's open in the editor, look for the onCreate method in the MainActivity class:

MainActivity.java (excerpt)

package ...
import ...
import ...
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
public class MainActivity extends ActionBarActivity {

    ...

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
    }

    ...
}
Make these two changes:
  1. Import the AdRequest and AdView classes.
  2. Add the code that will find your AdView in the layout, create an AdRequest, and then load an ad into theAdView with it.
Do not use the AdRequest line shown above if you are testing. Refer to our Targeting page to learn more about using test devices and test device IDs.
Once that's completed, you're finished. You now have a fully functional AdView in your app's main activity.

Enjoy a freshly loaded ad

Your app is now ready to display an ad using the Google Mobile Ads SDK. Run it again, and you should see a test banner displayed at the bottom of the device screen:
Congratulations! You've successfully integrated banner ads into an app.

No comments:

Post a Comment