Android FaceBook原生广告接入教程(精简版)

公司项目主要做海外市场,并且是资讯类的产品,所以接入一些广告公司的广告是一项不错的创收,昨天下午产品告诉我要马上接入Facebook的原生广告需求,于是下午就开始阅读Facebook广告接入的官方开发文档进行接入测试了,当然,接入的过程并没有那么顺利,遇到了好多坑,还好有一个有接入经验的大哥帮助加上自己坚持不懈的努力,最终成功的接入了。
FaceBook的原生广告的文档写的很详细,从创建项目到接入Facebook的广告sdk,再到自定义广告布局,调用广告api展示广告介绍的都非常详细,只不过新手第一次做的话,只做这些还不够,接下来跟你细细分析我的爬坑之路。

先把正确的接入流程写出来:
1、注册Facebook账号(这个就不多说)
2、找到原生广告集成文档(提示:先看https://developers.facebook.com/docs/audience-network/android 紧接着 再看这个 https://developers.facebook.com/docs/audience-network/android-native
3、配置相关信息:

使用 Facebook SDK 之前,需要先进行初始化。将调用添加到 Application 类中 onCreate 的 FacebookSdk.sdkInitialize: 

public class MyApplication extends Application { 
// Updated your class body: 
        @Override 
    public void onCreate() { 
        super.onCreate(); 
        // Initialize the SDK before executing any other operations, 
        FacebookSdk.sdkInitialize(getApplicationContext()); 
        AppEventsLogger.activateApp(this); 
        //FaceBook Ads广告,这个addTestDevice("")中的字符串是设备的编号,第一次运行实      从log日志里面观察可以看到,复制进来即可,不写这里会导致不出来广告的异常
        AdSettings.addTestDevice("1b0a5f0c-877d-4fe8-99df-a0322cde3a8e")
    } 
} 

AndroidMainfest.xml中要配置Facebook的应用id

<application
        android:name=".MyApplication"
        android:icon="@mipmap/icon"
        android:label="@string/app_name"
        android:roundIcon="@drawable/icon_logo"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
<!--  Facebook的应用id -->
<meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />
 <!--  如果需要接入Facebook统计的话需要集成这个 -->
<activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />

</application>

注意不要忘记在AndroidMainfest.xml文件中写入MyApplication

4 、添加依赖
在app级别下的build.gradle下添加如下依赖,这个也是Facebook官方文档最推荐的方式

dependencies {
  ...
  compile 'com.facebook.android:audience-network-sdk:4.28.1'  
  ...
}

5、写主要逻辑代码和自定义广告布局部分,这里会分步骤详解:
第一步:先创建一个native_ad_layout.xml文件写自己的自定义广告布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/native_ad_unit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical"
    android:paddingLeft="10dp"
    android:paddingRight="10dp">

    <LinearLayout
        android:id="@+id/ll_header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingBottom="10dp"
        android:paddingTop="10dp">

        <ImageView
            android:id="@+id/native_ad_icon"
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_gravity="center_vertical"/>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="5dp">

            <TextView
                android:id="@+id/native_ad_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:maxLines="2"
                android:textColor="@android:color/black"
                android:textSize="15sp"/>

            <TextView
                android:id="@+id/sponsored_label"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:lines="1"
                android:text="Sponsored"
                android:textColor="@android:color/darker_gray"
                android:textSize="10sp"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/ad_choices_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:orientation="horizontal"/>
    </LinearLayout>

    <com.facebook.ads.MediaView
        android:id="@+id/native_ad_media"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:gravity="center"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:orientation="vertical"
            android:paddingRight="10dp">

            <TextView
                android:id="@+id/native_ad_social_context"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:gravity="center_vertical"
                android:lines="2"
                android:paddingRight="5dp"
                android:textColor="@android:color/darker_gray"
                android:textSize="10sp"/>

            <TextView
                android:id="@+id/native_ad_body"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ellipsize="end"
                android:gravity="center_vertical"
                android:lines="2"
                android:textColor="@android:color/black"
                android:textSize="10sp"/>
        </LinearLayout>

        <Button
            android:id="@+id/native_ad_call_to_action"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:background="#4286F4"
            android:gravity="center"
            android:paddingLeft="3dp"
            android:paddingRight="3dp"
            android:textColor="@android:color/white"
            android:textSize="11sp"/>
    </LinearLayout>
</LinearLayout>

第二步:在你要显示这个广告的布局里面创建一个容器,来动态添加这个广告的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"    
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:paddingTop="50dp">
    ...
    <!--自定义Facebook ads布局容器-->
    <LinearLayout
        android:id="@+id/native_ad_container"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"/>
    ...
</RelativeLayout>

第三步:写加载广告的函数

    //声明三个变量
    private var nativeAd: NativeAd? = null
    private var nativeAdContainer: LinearLayout? = null
    private var adView: LinearLayout? = null

private fun showNativeAd() {
//        nativeAd = NativeAd(this@ArtActivity, "YOUR_PLACEMENT_ID") //加入你的广告版位号 测试的话直接用这个"YOUR_PLACEMENT_ID"就可以,不用改写
        nativeAd = NativeAd(this@ArtActivity, "1445302316225142_1445305302891510") // 正式的广告版位号
        //  手机上必须安装并且登陆谷歌play和Facebook app,然后Facebook账号必须在账号中心管理者后台添加开发者和测试者

        nativeAd!!.setAdListener(object : AdListener {
            override fun onAdClicked(p0: Ad?) {
                Log.d(TAG, "onAdClicked")
            }

            override fun onError(p0: Ad?, p1: AdError?) {
                Log.d(TAG, "onError")
                toast("Ad onError")
            }

            override fun onAdLoaded(p0: Ad?) {
                Log.d(TAG, "onAdLoaded")

                if (nativeAd != null) {
                    nativeAd!!.unregisterView()
                }

                // Add the Ad view into the ad container.
                nativeAdContainer = native_ad_container
                var inflater: LayoutInflater = LayoutInflater.from(this@ArtActivity)
                // Inflate the Ad view.  The layout referenced should be the one you created in the last step.
                adView = inflater.inflate(R.layout.native_ad_layout, nativeAdContainer, false) as LinearLayout
                nativeAdContainer?.addView(adView)


                // Create native UI using the ad metadata.
                val nativeAdIcon = adView!!.native_ad_icon as ImageView
                val nativeAdTitle = adView!!.native_ad_title as TextView
                val nativeAdMedia = adView!!.native_ad_media as MediaView
                val nativeAdSocialContext = adView!!.native_ad_social_context as TextView
                val nativeAdBody = adView!!.native_ad_body as TextView
                val nativeAdCallToAction = adView!!.native_ad_call_to_action as Button

                // Set the Text.
                nativeAdTitle.setText(nativeAd!!.getAdTitle())
                nativeAdSocialContext.setText(nativeAd!!.getAdSocialContext())
                nativeAdBody.setText(nativeAd!!.getAdBody())
                nativeAdCallToAction.setText(nativeAd!!.getAdCallToAction())

                // Download and display the ad icon.
                var adIcon: NativeAd.Image = nativeAd!!.getAdIcon()
                NativeAd.downloadAndDisplayImage(adIcon, nativeAdIcon)

                // Download and display the cover image.
                nativeAdMedia.setNativeAd(nativeAd)
                    toast("成功了")
                // Add the AdChoices icon
                var adChoicesContainer: LinearLayout = adView!!.ad_choices_container
                var adChoicesView: AdChoicesView = AdChoicesView(this@ArtActivity, nativeAd, true)
                adChoicesContainer.addView(adChoicesView)

                // Register the Title and CTA button to listen for clicks.
                var clickableViews = mutableListOf<View>()
                clickableViews.add(nativeAdTitle)
                clickableViews.add(nativeAdCallToAction)
                nativeAd!!.registerViewForInteraction(nativeAdContainer, clickableViews)

            }

            override fun onLoggingImpression(p0: Ad?) {
                Log.d(TAG, "onLoggingImpression")
                toast("")
            }

        })
        // Request an ad
        nativeAd!!.loadAd()
    }

第四步:在你的activity中onCreate方法里面调用这个showNativeAd()的函数就行

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         showNativeAd()
    }

其实这里如果正常的话会正常的出来广告,但是我这里没有出来,原因很简单:
手机上没有安装Facebook和谷歌play,
装上后一定要登陆上你的Facebook账号,
并且这个账号必须在你注册的应用账号中心管理者后台添加为开发者,
然后检查手机网络确认已经翻墙后,就可以正常的显示广告了。
以上这几点也是我遇到的最坑的几点,要不是一个接过广告的老手帮忙调试,我还不知道怎么能把广告显示出来估计
另外这里再介绍给大家一种新的调试Android应用的方法,因为Facebook是认签名的,发布版才能正常调用分享,广告等功能,跟微信一样,以前都是打包成发布版的apk包进行测试,这样的坏处是不能正常看log日志,不能正常跟踪异常信息,总是打包也不太方便,然后就发现了一种可以测试环境也可以直接用发布版签名的方法,很方便,这里做下记录:

在app级别的bulide.glide中的Android{}中添加或者修改为如下
 signingConfigs {
        release {
            keyAlias 'your keyAlias'
            keyPassword 'adminis'
            storeFile file('C:/Users/EASY/Desktop/key/mykey.jks')
            storePassword 'your storePassword '
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            signingConfig signingConfigs.release
        }
    }

然后这样就可以直接debug跑项目的时候也可以直接调试发布版才能调试的功能了,而且log,error信息随时掌握,非常方便,哈哈,感觉收获满满的今天!

猜你喜欢

转载自blog.csdn.net/wjj1996825/article/details/80179206