Android Google AdMob 广告接入示例(要demo联系我呦~)

开发工具:android studio

首先进入admob官网注册登录(需翻墙),登陆后创建一个应用,添加一个横幅广告(最好用google给出的测试的广告单元id:ca-app-pub-3940256099942544/6300978111,一开始测试不用自己添加,自己添加长时间使用有可能会被封号)。

用android studio新建一个工程项目,更改验证应用级build.gradle(出错误的话,点击file->Project Structure->Ads->点上对号->ok)
... dependencies { compile fileTree(dir:
'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:xx.x.x' compile 'com.google.firebase:firebase-ads:10.0.1'//需添加
 } ... apply plugin: 'com.google.gms.google-services'//需添加

点击同步,打开您应用的字符串资源文件 

strings.xml

 
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Demo</string>

<string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>
</resources>
注意:上述广告单元 ID 仅供测试使用。 这样一来,您便可以检索示例横幅广告,并确保您的实现正确无误。 开发和测试您的应用时,应始终使用测试广告。 点击您自己的实际广告是违反 AdMob 政策的行为。在开发和测试期间,请仅使用测试广告。如果您确实需要在发布前呈现实际广告,请避免点击它们。如果您点击了实际广告,您的 AdMob 帐号可能会被暂停。

activity_main.xml 文件:
<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:layout_height="match_parent"
        android:layout_width="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="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>


MainActivity.java(节选)

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

        MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544~3347511713");

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

    ...

}
运行就可以看到一个横幅广告诞生!!!
原文地址:https://www.cnblogs.com/lhj1017/p/7376037.html