Penerapan iklan Native AdMob sedikit lebih rumit dibandingkan penerapan jenis iklan AdMob lainnya. Misalnya iklan Banner yang dalam menerapkannya hanya membutuhkan beberapa baris kode XML / Java maka iklan siap untuk ditampilkan. Berbeda dengan Native Ads yang harus di kustominasi dan memiliki aturan yang cukup banyak.
Untuk menampilkan iklan Native, kita harus menyediakan layout / container, misalnya : CardView atau layout seperti LinearLayout, Relativelayout dan sebagainya. Kemudian juga kita harus menyediakan object-object view di dalam sebuah Layout Resource File seperti TextView untuk judul dari iklan, nama pengiklan, deskripsi iklan, lalu ImageView untuk icon perusahaan pengiklan dan sebuah listener untuk mengunjungi halaman website pengiklan (opsional).
Baik, mari kita mulai! Hal pertama adalah mengimport SDK Google Ads terlebih dahulu. Letakkan baris kode library berikut ini ke dalam dependencies pada file build.gradle(Module: app) kemudian sync gradle.
implementation 'com.google.android.gms:play-services-ads:19.5.0'
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.gwnbs.nativeads"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
//Library SDK Admob
implementation 'com.google.android.gms:play-services-ads:19.5.0'
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gwnbs.nativeads">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Meta data id aplikasi -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-3940256099942544~3347511713"/>
</application>
</manifest>
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
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=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textKontenApp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textColor="@color/adColorBodyText"
android:textSize="18sp"
android:fontFamily="serif"
android:text="Konten aplikasi"/>
<!-- layout container untuk iklan native-->
<LinearLayout
android:id="@+id/adContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="10dp" />
<TextView
android:id="@+id/textKontenApp2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textColor="@color/adColorBodyText"
android:textSize="18sp"
android:fontFamily="serif"
android:text="Konten aplikasi"/>
</LinearLayout>
</ScrollView>
Layout ini kita namakan native_ad_layout.xml. Berikut isi keseluruhan dari file ini.
native_ad_layout.xml :
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.ads.formats.UnifiedNativeAdView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@color/adColorBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/adAtribusi"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@color/adColorAtribusi"
android:layout_alignParentStart="true"
android:text="Ad"
android:gravity="center"
android:textSize="15sp"
android:textStyle="bold"/>
<TextView
android:id="@+id/btnRefreshAd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="?selectableItemBackground"
android:textColor="@color/adColorBodyText"
android:text="Refresh"
android:textSize="10sp"
android:layout_gravity="end"
android:gravity="center"
app:drawableTopCompat="@drawable/ic_refresh" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/adIcon"
android:layout_width="60dp"
android:layout_height="60dp"
android:contentDescription="@string/app_name"
android:adjustViewBounds="true"
android:padding="5dp"
android:scaleType="fitXY"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/adHeadlineText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="@color/adColorHeading"
android:text="Ad Headline"/>
<TextView
android:id="@+id/adAdvertiserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="@color/adColorBodyText"
android:text="Advertiser name"/>
<RatingBar
android:id="@+id/adRating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:stepSize="0.5"
style="?android:attr/ratingBarStyleSmall"
android:isIndicator="true"/>
</LinearLayout>
</LinearLayout>
<TextView
android:id="@+id/adBodyText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/adColorBodyText"
android:text="Ad body text"
android:textSize="18sp"/>
</LinearLayout>
<com.google.android.gms.ads.formats.MediaView
android:id="@+id/mediaView"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginTop="5dp"
android:layout_gravity="center_horizontal"/>
<Button
android:id="@+id/btnAction"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/adColorButtonText"
android:text="Install Now"/>
</LinearLayout>
</com.google.android.gms.ads.formats.UnifiedNativeAdView>
colors.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#F57C00</color>
<color name="colorPrimaryDark">#F57C00</color>
<color name="colorAccent">#0288D1</color>
<!-- Warna untuk object-object view iklan native -->
<color name="adColorAtribusi">#FBC02D</color>
<color name="adColorBackground">#F6EBEB</color>
<color name="adColorHeading">#512DA8</color>
<color name="adColorBodyText">#000000</color>
<color name="adColorButton">#C2185B</color>
<color name="adColorButtonText">#530B0B</color>
</resources>
strings.xml :
<resources>
<string name="app_name">Native Ads</string>
<string name="konten_app"><![CDATA[<h2>What is Lorem Ipsum?</h2><p><strong>Lorem Ipsum</strong> is simply dummy
text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the
1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not
only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised
in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum.</p><h2>Where does it come from?</h2><p>Contrary to
popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC,
making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one
of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in
classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33
of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise
on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum,
\"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.</p><p>The standard chunk of Lorem Ipsum used since
the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from \"de Finibus Bonorum et Malorum\"
by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by
H. Rackham.</p>]]></string>
<string name="konten_app2"><![CDATA[<h2>Why do we use it?</h2><p>It is a long established fact that a reader will be
distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a
more-or-less normal distribution of letters, as opposed to using \'Content here, content here\', making it look like
readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text,
and a search for \'lorem ipsum\' will uncover many web sites still in their infancy. Various versions have evolved over
the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p><h2>Where can I get some?
</h2><p>There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in
some form, by injected humour, or randomised words which don\'t look even slightly believable. If you are going to use a
passage of Lorem Ipsum, you need to be sure there isn\'t anything embarrassing hidden in the middle of text. All the
Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true
generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence
structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from
repetition, injected humour, or non-characteristic words etc.</p>]]></string>
</resources>
Selanjutnya di MainActivity.java. Pertama-tama membuat variabel global untuk objek UnifiedNativeAd, kemudian di dalam onCreate kita menginisialisasi dan menyetel nilai kedua TextView artikel nya dari HTML. Disini menggunakan HTML supaya teks dapat di kustominasi seperti terlihat pada file value strings.xml diatas.
MainActivity.java :
package com.gwnbs.nativeads;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdLoader;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.formats.MediaView;
import com.google.android.gms.ads.formats.UnifiedNativeAd;
import com.google.android.gms.ads.formats.UnifiedNativeAdView;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
public class MainActivity extends AppCompatActivity {
private UnifiedNativeAd nativeAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Inisialisasi dan menyetel nilai string TextView artikel
TextView textKontenApp = findViewById(R.id.textKontenApp);
TextView textKontenApp2 = findViewById(R.id.textKontenApp2);
textKontenApp.setText(Html.fromHtml(getString(R.string.konten_app)));
textKontenApp2.setText(Html.fromHtml(getString(R.string.konten_app2)));
//Inisialisasi SDK AdMob
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
showOrRefreshAd("Displaying ad...");
}
//Metode untuk menampilkan iklan
private void showOrRefreshAd(final String toastMessage) {
AdLoader.Builder builder = new AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110");
builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
@Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
Toast.makeText(getApplicationContext(), toastMessage, Toast.LENGTH_SHORT).show();
nativeAd = unifiedNativeAd;
LinearLayout adContainer = findViewById(R.id.adContainer);
@SuppressLint("InflateParams")
UnifiedNativeAdView adView = (UnifiedNativeAdView) getLayoutInflater().inflate(R.layout.native_ad_layout, null);
TextView btnRefreshAd = adView.findViewById(R.id.btnRefreshAd);
populateNativeAd(unifiedNativeAd, adView);
adContainer.removeAllViews();
adContainer.addView(adView);
//metode klik untuk tombol refresh iklan.
btnRefreshAd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showOrRefreshAd("Ad refreshed successfully.");
}
});
}
});
AdLoader adLoader = builder.withAdListener(new AdListener() {
@Override
public void onAdFailedToLoad (LoadAdError adError) {
Toast.makeText(getApplicationContext(), "Ad failed to load!", Toast.LENGTH_SHORT).show();
}
}).build();
adLoader.loadAd(new AdRequest.Builder().build());
}
//Mengkoneksikan seluruh atribut iklan dengan object-object view yang ada di native_ad_layout.xml
private void populateNativeAd (UnifiedNativeAd nativeAd, UnifiedNativeAdView adView) {
adView.setIconView(adView.findViewById(R.id.adIcon));
adView.setHeadlineView(adView.findViewById(R.id.adHeadlineText));
adView.setAdvertiserView(adView.findViewById(R.id.adAdvertiserName));
adView.setBodyView(adView.findViewById(R.id.adBodyText));
adView.setStarRatingView(adView.findViewById(R.id.adRating));
adView.setMediaView((MediaView) adView.findViewById(R.id.mediaView));
adView.setCallToActionView(adView.findViewById(R.id.btnAction));
adView.getMediaView().setMediaContent(nativeAd.getMediaContent());
((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
if (nativeAd.getBody() == null) {
adView.getBodyView().setVisibility(View.INVISIBLE);
} else {
((TextView) adView.getBodyView()).setText(nativeAd.getBody());
adView.getBodyView().setVisibility(View.VISIBLE);
}
if (nativeAd.getAdvertiser() == null) {
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
} else {
((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
adView.getAdvertiserView().setVisibility(View.VISIBLE);
}
if (nativeAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
((RatingBar) adView.getStarRatingView()).setRating(nativeAd.getStarRating().floatValue());
adView.getStarRatingView().setVisibility(View.VISIBLE);
}
if (nativeAd.getIcon() == null) {
adView.getIconView().setVisibility(View.GONE);
} else {
((ImageView) adView.getIconView()).setImageDrawable(nativeAd.getIcon().getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if (nativeAd.getCallToAction() == null) {
adView.getCallToActionView().setVisibility(View.INVISIBLE);
} else {
((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
}
adView.setNativeAd(nativeAd);
}
//Menonaktifkan iklan jika iklan masih aktif namun activity sudah tidak berjalan.
@Override
public void onDestroy() {
if (nativeAd !=null) {
nativeAd.destroy();
}
super.onDestroy();
}
}
Untuk argumen string yang ada di dalam metode showOrRefreshAd ditunjukkan untuk menampilkan pesan toast berbeda. Itu karena kita memanggil metode privat tersebut di 2 tempat sehingga kita perlu membuat argumen string tersebut untuk menampilkan pesan toast yang berbeda.
0 comments:
Post a Comment