본문 바로가기

Android 하나하나 집어보기

FaceBookAudience 를 쉽게 붙여보자!!!

.

FaceBook Audience


개인앱을 만드는 사람이라면 누구나 광고를 앱에 붙여 수익을 내보고 싶으실 겁니다. 앱에서 광고를 내보내는 방법은 여러방법이 있습니다. 배너광고, 보상형광고 (게임에서 많이 사용) ,네이티브 광고 등이 있습니다. 우리는 이중에서 네이티브 광고를 해보겠습니다. 네이티브는 각자 개인앱에 최적화되서 레이아웃을 커스텀할 수 있고 광고도 멋지게 내보낼 수 있는 최근 각광 받는 광고 시스템입니다. 네이티브 광고는 구글 admob 과 Facebook Audience 가 있는데 애드몹은 현재 베타인 관계로 페이스북 오디언스를 해보도록 하겠습니다.


우리가 작업할 내용은 페이스북 오디언스를 페이스북 광고 체계와 비슷하게 SNS 와 같은 리스트뷰 형식에서 스크롤시 광고가 중간 중간 들어가는 형태로 아래와 같이 만들어볼 예정입니다.



Gradle Setting

아래와 같이 그래들에 라이브러리를 추가해줍니다


allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

dependencies {
    compile 'com.facebook.android:audience-network-sdk:4.+'
    compile 'com.github.EdgeJH:AudienceHelperAdapter:1.0.0'
}

하나는 페이스북 오디언스 라이브러리이고 두번째 라이브러리는 페이스북 오디언스를 리사이클러뷰에 최대한 쉽게 붙일 수 있도록  제가만든 라이브러리 입니다.

AudienceHelperAdapter < 링크 클릭


일단 처음에 가볍게 리사이클러뷰를 만들어줍니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.edge.audiencehelperadapter.MainActivity">

<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler" />

</LinearLayout>

그 다음으로 가볍게 자신의 리사이클러뷰 아이템레이아웃을 만들어줍니다. 전그냥 텍스트뷰 하나만 만들어 보겠습니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp"
android:orientation="horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/text"
android:layout_margin="20dp"
android:textSize="17dp"/>

</LinearLayout>

그 다음으로 페이스북 광고 커스텀 레이아웃을 만들어줍니다.

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

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="10dp">

<ImageView
android:id="@+id/native_ad_icon"
android:layout_width="50dp"
android:layout_height="50dp" />

<LinearLayout
android:layout_width="match_parent"
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:lines="1"
android:textColor="@android:color/black"
android:textSize="18sp" />

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

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

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

<TextView
android:id="@+id/native_ad_social_context"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:ellipsize="end"
android:lines="2"
android:paddingRight="5dp"
android:textColor="@android:color/black"
android:textSize="15sp" />

<Button
android:id="@+id/native_ad_call_to_action"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="@android:color/holo_blue_light"
android:gravity="center"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>

페이스북 광고레이아웃을 만들땐 꼭 페이스북 광고 레이아웃 지침을 확인해보세요

페이스북 오디언스 레이아웃 지침< 링크 클릭


페이스북 광고레이아웃을 만들기 귀찮고 인스타처럼 하시고 싶으신분은 레이아웃 따로 만드실 필요없습니다. 라이브러리에 인스타처럼 미리 제공해놨습니다. 아래와 같은 레이아웃입니당

윽 카카오 택시 광고 ㅋㅋㅋㅋ 저에겐 이게 뜨는군요 ㅋㅋㅋ 이모티콘이 갖고 싶었습니다.

레이아웃을 다작성하셨다면 메인액티비티에 페이스북광고 세팅부터 시작하겠습니다.


메인액티비티에 다음과 같은 메소드를 작성해줍니다.

private void setManager(){
manager = new FBAdManager.Builder("YOUR_PLACEMENT_ID",getApplicationContext())
.setAdLoadCount(20)
.setListener(this)
.isCaching(true)
.build();
}


그리고 나서 아래와같이 변수를 선언해주고 FBLoadListener를  implements 해줍니다.

public class MainActivity extends AppCompatActivity implements FBLoadListener{
FBAdManager manager;
RecyclerView recyclerView;
AdAdapter adapter;
ArrayList<String> arrayList= new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setArrayList();
initView();
setManager();
}
}

위 내용을 잠시 설명드리자면 FBAdManager는 리사이클러뷰의 광고 몇개를 로테이션돌릴지 갯수 설정과, 광고가 로딩이 되었는지 FBLoadListener 를 통해 받아올 수 있습니다. FBAdManager에는 페이스북에서 오디언스 가입하고 받아보실 수 있습니다.

페이스북 오디언스 가입< 링크 클릭


다음으로 Adapter 를 만들어보도록 하겠습니다. 여기서 두가지 버전으로 나뉩니다. 앞서 말씀드린 레이아웃 짜기 귀찮으신분용 어댑터와 커스텀으로 광고 레이아웃을 만드실 분의 레이아웃을 나뉩니다. 먼저 레이아웃 따로 작성하지 않는 어댑터입니다.


public class AdAdapter extends FBAdapter<AdAdapter.CustomHolder> {
Context context;
ArrayList<String> arrayList=new ArrayList<>();

public AdAdapter(Context context, ArrayList arrayList, FBAdapterSetting setting) {
super(context, arrayList, setting);
this.context = context;
this.arrayList = arrayList;
}

@Override
public RecyclerView.ViewHolder onFBCreateViewHolder(ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.example_item,parent,false);
return new CustomHolder(view);
}

@Override
public void onFBBindViewHolder(CustomHolder holder, int position) {
holder.textView.setText(arrayList.get(position));
}


class CustomHolder extends RecyclerView.ViewHolder {
TextView textView;
public CustomHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text);
}
}
}

구조는 기존 리사이클러 어댑터와 유사하게 만들었습니다. 뷰홀더를 구현하고 온크리에이트 뷰홀더와 온바인드 뷰홀더만 세팅해주시면 됩니다. 아이템 카운트는 알아서 세팅이되도록 만들었습니다. 다음으로 커스텀레이아웃을 만드시는 분 어댑터입니다.

public class AdCustomAdapter extends FBCustomAdapter<AdCustomAdapter.MyHolder,AdCustomAdapter.AdHolder> {
Context context;
ArrayList<String> arrayList;
public AdCustomAdapter(Context context, ArrayList arrayList, FBAdapterSetting setting) {
super(context, arrayList, setting);
this.context = context;
this.arrayList =arrayList;
}

@Override
public RecyclerView.ViewHolder onCreateAllViewHolder(ViewGroup parent, int viewType) {
switch (viewType){
case FBCustomAdapter.AD_TYPE :
View adView = LayoutInflater.from(context).inflate(R.layout.custom_layout,parent,false);
return new AdHolder(adView);
case FBCustomAdapter.POST_TYPE :
View myView = LayoutInflater.from(context).inflate(R.layout.example_item,parent,false);
return new MyHolder(myView);
default:
return null;
}
}

@Override
public void onBindMyViewHolder(MyHolder holder, int position) {
holder.textView.setText(arrayList.get(position));
}

@Override
public void onBindFBViewHolder(AdHolder holder, int position, NativeAd nativeAd) {
holder.bindView(nativeAd);
}

class MyHolder extends RecyclerView.ViewHolder {
TextView textView;
public MyHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text);
}
}

class AdHolder extends RecyclerView.ViewHolder {
private MediaView mAdMedia;
private ImageView mAdIcon;
private TextView mAdTitle;
private TextView mAdBody;
private TextView mAdSocialContext;
private Button mAdCallToAction;

public AdHolder(View view) {
super(view);

mAdMedia = (MediaView) view.findViewById(R.id.native_ad_media);
mAdTitle = (TextView) view.findViewById(R.id.native_ad_title);
mAdBody = (TextView) view.findViewById(R.id.native_ad_body);
mAdSocialContext = (TextView) view.findViewById(R.id.native_ad_social_context);
mAdCallToAction = (Button)view.findViewById(R.id.native_ad_call_to_action);
mAdIcon = (ImageView)view.findViewById(R.id.native_ad_icon);

}

public void bindView(NativeAd ad) {
if (ad == null) {
mAdTitle.setText("No Ad");
mAdBody.setText("Ad is not loaded.");
}
else {
mAdTitle.setText(ad.getAdTitle());
mAdBody.setText(ad.getAdBody());
mAdSocialContext.setText(ad.getAdSocialContext());
mAdCallToAction.setText(ad.getAdCallToAction());
mAdMedia.setNativeAd(ad);
NativeAd.Image adIcon = ad.getAdIcon();
NativeAd.downloadAndDisplayImage(adIcon, mAdIcon);
}
}
}
}

내용이 많아보이지만 사실 뷰홀더 내용 빼고보면 별코드없습니다. 각각의 뷰를 온크리에이트에서 두가지로 나눠서 작성해주시고 온바인드는 따로 나누어서 세팅되도록 만들었습니다.


다작성하셨다면 다시 메인액티비티도 이동해보겠습니다. 메인액티비티에서 아래와같이 작성해줍니다.

private void setAdapter(NativeAdsManager nativeAdsManager){
FBAdapterSetting setting = new FBAdapterSetting.Builder()
.setAdInterval(10)
.setAdsManager(nativeAdsManager)
.build();
adapter = new AdAdapter(getApplicationContext(),arrayList,setting);
setRecyclerView();
}

private void setRecyclerView(){
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
}


@Override
public void onLoadSuccess(NativeAdsManager adsManager) {
setAdapter(adsManager);
}



@Override
public void onLoadFail(AdError error) {
setAdapter(null);
}

위 내용을 살펴보면 onLoadSuccess와 onLoadFail 은 위의 FBAdManager의 리스너입니다. 페이스북 광고가 로드가 되면 어댑터를 세팅하고 어댑터 세팅이 끝이나면 리사이클러뷰를 세팅하는 방식입니다. 리사이클러 뷰의 세팅은 기존과 같고 어댑터 세팅하는 부분을 보면 FBAdapterSetting 이 있습니다.  이클래스는 페이스북 어댑터 세팅을위한 클래스입니다. 빌더 인자를 살펴보면 광고가 리사이클러뷰에서 몇번당 한번씩 나올것인지와 페이스북광고매니저를 가지고 어댑터에 붙여주시기만 하면됩니다.  그리고 지금 위의 코드는 AdAdatper로 인스타버전 어댑터인데 커스텀버전은 아래와같이 setAdapter 메소드안에 어댑터부분만 바꿔주시면 됩니다.

adapter = new AdCustomAdapter(getApplicationContext(),arrayList,setting);


자이제 페이스북 광고를 붙여보는것이 모두 끝이났습니다. 원래 페이스북 광고를 붙이는게 여간 까다로운일이 아닙니다. 리사이클러뷰 아이템갱신과 이것저것 세팅값들 로딩 타이밍잡기 등등 생각보다 처음접하신 분들은 좀 애를 먹습니다. 하지만 저의 AudienceHelperAdapter 와 함께라면 금방 작성하실 수 있습니다.


위의 풀코드는  여기여기여기 <클릭 하셔서 들어가셔서 보실 수 있습니다. 사용해보시고 좋으시면 깃헙에 스타하나 부탁드립니다. 감사합니다.


이상 포스팅을 마치겠습니당. 끝!


ps.


비전공자 안드로이드 질문방을 운영중입니다. 

톡방링크 (링크) 를 통해 들어오시면 못다 설명드린내용들 자세히 설명드릴게요!!! 

이깟 블로그보다 직접만나서 배워보고 싶으시면 말리지 않습니다. 어서오세요 (링크)

마지막으로....제가 만든 앱 (링크) 입니다. 리뷰... 하나가 생명을 살립니다. 감사합니다.