Skip to content

Instantly share code, notes, and snippets.

@johncodeos johncodeos/AdFragment.kt
Last active Sep 24, 2019

Embed
What would you like to do?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
android:orientation="vertical"
tools:context=".BannerAds.BannerAdActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<!-- Content of your Activity/Fragment -->
<com.mopub.mobileads.MoPubView
android:id="@+id/banner_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="center_horizontal"
app:moPubAdSize="match_view" />
</RelativeLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="@color/colorPrimary"
tools:context=".NativeVideoAds.nativeVideoAd.NativeVideoAdSingleView">
<!-- Content of our Activity/Fragment -->
<FrameLayout
android:id="@+id/native_ad_frame"
android:layout_width="match_parent"
android:layout_centerInParent="true"
android:layout_height="wrap_content" />
<!-- Content of our Activity/Fragment -->
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:gravity="center"
android:background="@color/colorPrimary"
tools:context=".NativeVideoAds.nativeVideoAd.NativeVideoAdSingleView">
<!-- Content of our Activity/Fragment -->
<FrameLayout
android:id="@+id/native_video_ad_frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- Content of our Activity/Fragment -->
</RelativeLayout>
class AdFragment: Fragment() {
lateinit var mAdPlacer: MoPubStreamAdPlacer
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val position = arguments!!.getInt(ARG_AD_POSITION)
mAdPlacer.placeAdsInRange(position - 5, position + 5)
return mAdPlacer.getAdView(position, null, container)
}
companion object {
private val ARG_AD_POSITION = "ad_position"
fun newInstance(adPosition:Int, mStreamAdPlacer: MoPubStreamAdPlacer):AdFragment {
val fragment = AdFragment()
fragment.mAdPlacer = mStreamAdPlacer
val bundle = Bundle()
bundle.putInt(ARG_AD_POSITION, adPosition)
fragment.arguments = bundle
return fragment
}
}
}
<!-- MoPub's consent dialog -->
<activity android:name="com.mopub.common.privacy.ConsentDialogActivity" android:configChanges="keyboardHidden|orientation|screenSize"/>
<!-- All ad formats -->
<activity android:name="com.mopub.common.MoPubBrowser" android:configChanges="keyboardHidden|orientation|screenSize"/>
<!-- Interstitials -->
<activity android:name="com.mopub.mobileads.MoPubActivity" android:configChanges="keyboardHidden|orientation|screenSize"/>
<activity android:name="com.mopub.mobileads.MraidActivity" android:configChanges="keyboardHidden|orientation|screenSize"/>
<!-- Rewarded Video and Rewarded Playables -->
<activity android:name="com.mopub.mobileads.RewardedMraidActivity" android:configChanges="keyboardHidden|orientation|screenSize"/>
<activity android:name="com.mopub.mobileads.MraidVideoPlayerActivity" android:configChanges="keyboardHidden|orientation|screenSize"/>
// ... mopub activies
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
// ... main activity
<manifest>
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...>
</application>
</manifest>
<!-- Required permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Optional permissions. Will pass Lat/Lon values when available. Choose either Coarse or Fine -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- Optional permissions. Used for MRAID 2.0 storePicture ads -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
class BannerAdActivity : AppCompatActivity() {
private lateinit var moPubBanner: MoPubView
private lateinit var moPubViewBannerAdListener: MoPubView.BannerAdListener
private var isMediumRectangleAd = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_banner_ad)
MyMoPub().init(this, "AD_UNIT_ID")
Handler().postDelayed({
initAds()
}, 200)
}
private fun initAds() {
moPubBanner = findViewById(R.id.banner_view)
moPubBanner.adUnitId = "AD_UNIT_ID"
moPubBanner.loadAd()
Log.d("MoPub","Banner ad is loading.")
moPubViewBannerAdListener = object : MoPubView.BannerAdListener {
override fun onBannerExpanded(banner: MoPubView?) {
Log.d("MoPub","Banner ad has expanded.")
}
override fun onBannerLoaded(banner: MoPubView?) {
Log.d("MoPub","Banner ad has loaded.")
}
override fun onBannerCollapsed(banner: MoPubView?) {
Log.d("MoPub","Banner ad has collapsed.")
}
override fun onBannerFailed(banner: MoPubView?, errorCode: MoPubErrorCode?) {
Log.d("MoPub","Banner ad failed to load with error:$errorCode")
}
override fun onBannerClicked(banner: MoPubView?) {
Log.d("Banner ad was clicked.")
}
}
moPubBanner.bannerAdListener = moPubViewBannerAdListener
}
override fun onDestroy() {
// You must call this or the banner view may cause a memory leak.
moPubBanner.destroy()
super.onDestroy()
}
}
android {
// ... other configurations,compileSdkVersion,buildToolsVersion e.t.c
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
// ... other dependencies
implementation 'com.google.android.gms:play-services-base:17.1.0'
}
dependencies {
// ... other dependencies
implementation('com.mopub:mopub-sdk:5.9.0@aar') {
transitive = true
}
}
allprojects {
repositories {
// ... other project repositories
google()
jcenter()
maven { url "https://s3.amazonaws.com/moat-sdk-builds" }
}
}
dependencies {
// ... other project dependencies
// For banners
implementation('com.mopub:mopub-sdk-banner:+@aar') {
transitive = true
}
// For interstitials
implementation('com.mopub:mopub-sdk-interstitial:+@aar') {
transitive = true
}
// For rewarded videos. This will automatically also include interstitials
implementation('com.mopub:mopub-sdk-rewardedvideo:+@aar') {
transitive = true
}
// For native static (images).
implementation('com.mopub:mopub-sdk-native-static:+@aar') {
transitive = true
}
// For native video. This will automatically also include native static
implementation('com.mopub:mopub-sdk-native-video:+@aar') {
transitive = true
}
}
class ContentFragment: Fragment() {
companion object {
private val ARG_SECTION_NUMBER = "section_number"
fun newInstance(sectionNumber: Int): ContentFragment {
val fragment = ContentFragment()
val args = Bundle()
args.putInt(ARG_SECTION_NUMBER, sectionNumber)
fragment.arguments = args
return fragment
}
}
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_native_ad_view_pager_content, container, false)
val contentNumber = arguments!!.getInt(ARG_SECTION_NUMBER)
rootView.native_ad_view_pager_content_text.text = "Item $contentNumber"
return rootView
}
}
class CustomPagerAdapter(fm: FragmentManager,streamAdPlacer: MoPubStreamAdPlacer): FragmentStatePagerAdapter(fm) {
private val mStreamAdPlacer: MoPubStreamAdPlacer = streamAdPlacer
private val ITEM_COUNT = 30
init{
streamAdPlacer.setItemCount(ITEM_COUNT)
}
override fun getItemPosition(`object`:Any):Int {
// This forces all items to be recreated when invalidate() is called on the ViewPager.
return POSITION_NONE
}
override fun getCount(): Int {
return mStreamAdPlacer.getAdjustedCount(ITEM_COUNT)
}
override fun getItem(position: Int): Fragment {
mStreamAdPlacer.placeAdsInRange(position - 5, position + 5)
if (mStreamAdPlacer.isAd(position)) {
return AdFragment.newInstance(position, mStreamAdPlacer)
} else {
return ContentFragment.newInstance(mStreamAdPlacer.getOriginalPosition(position))
}
}
override fun getPageTitle(position:Int):CharSequence {
if (mStreamAdPlacer.isAd(position)){
return "Advertisement"
}else{
return "Content Item " + mStreamAdPlacer.getOriginalPosition(position)
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="native_main_image_height">200dp</dimen>
<dimen name="button_text_size">15sp</dimen>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="native_main_image_height">300dp</dimen>
<dimen name="button_text_size">17sp</dimen>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="native_main_image_height">400dp</dimen>
<dimen name="button_text_size">17sp</dimen>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="button_text_size">13sp</dimen>
<dimen name="native_main_image_height">200dp</dimen>
<dimen name="button_height">36dp</dimen>
</resources>
class InterstitialAdActivity : AppCompatActivity() {
private lateinit var moPubInterstitial: MoPubInterstitial
private lateinit var moPubInterstitialInterstitialAdListener: MoPubInterstitial.InterstitialAdListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_interstitial_ad)
MyMoPub().init(this, "AD_UNIT_ID")
Handler().postDelayed({
initAds()
}, 200)
}
private fun initAds() {
moPubInterstitial = MoPubInterstitial(this, "AD_UNIT_ID")
Log.d("MoPub", "Interstitial ad is loading.")
moPubInterstitial.load()
moPubInterstitialInterstitialAdListener =
object : MoPubInterstitial.InterstitialAdListener {
override fun onInterstitialLoaded(interstitial: MoPubInterstitial?) {
//Do something when insterstitial is loaded
Log.d("MoPub", "Interstitial ad is loaded.")
//Show the Ad if the Interstitial is loaded
yourAppsShowInterstitialMethod()
}
override fun onInterstitialShown(interstitial: MoPubInterstitial?) {
//Do something when insterstitial is shown
Log.d("MoPub", "Interstitial ad has show.")
}
override fun onInterstitialFailed(interstitial: MoPubInterstitial?,errorCode: MoPubErrorCode?) {
//Do something when insterstitial is failed
Log.d("MoPub", "Interstitial ad failed to load with error: $errorCode")
}
override fun onInterstitialDismissed(interstitial: MoPubInterstitial?) {
//Do something when insterstitial is dismissed
Log.d("MoPub", "Interstitial ad has dismissed.")
}
override fun onInterstitialClicked(interstitial: MoPubInterstitial?) {
//Do something when insterstitial is clicked
Log.d("MoPub", "Interstitial ad clicked.")
}
}
moPubInterstitial.interstitialAdListener = moPubInterstitialInterstitialAdListener
}
private fun yourAppsShowInterstitialMethod() {
if (moPubInterstitial.isReady) {
moPubInterstitial.show()
} else {
// Caching is likely already in progress if `isReady()` is false.
// Avoid calling `load()` here and instead rely on the callbacks on moPubInterstitialInterstitialAdListener
}
}
override fun onDestroy() {
// You must call this or the interstital view may cause a memory leak.
moPubInterstitial.destroy()
super.onDestroy()
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
android:background="@color/colorPrimary"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mopub_native_ad_layout">
<ImageView
android:id="@+id/mopub_native_ad_privacy"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="-5dp"
android:layout_marginEnd="-5dp"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:tint="@android:color/white"
android:contentDescription="Privacy Information Icon image"
android:padding="10dp"
android:layout_marginRight="-5dp"
android:layout_alignParentRight="true" />
<ImageView
android:id="@+id/mopub_native_ad_icon"
android:background="@null"
android:scaleType="centerInside"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginStart="10dp"
android:layout_alignParentStart="true"
android:layout_marginLeft="10dp"
android:layout_alignParentLeft="true" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/mopub_native_ad_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="@id/mopub_native_ad_icon"
android:layout_marginStart="10dp"
android:layout_toStartOf="@id/mopub_native_ad_privacy"
android:textColor="@android:color/white"
android:textStyle="bold"
android:textSize="16sp"
android:text="Lorem ipsum dolor sit amet, consectetur"
android:layout_marginEnd="10dp"
android:layout_alignTop="@id/mopub_native_ad_icon"
android:layout_toRightOf="@id/mopub_native_ad_icon"
android:layout_toLeftOf="@id/mopub_native_ad_privacy" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/mopub_native_ad_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/mopub_native_ad_title"
android:layout_marginStart="12dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="3dp"
android:layout_marginBottom="2dp"
android:layout_toStartOf="@+id/mopub_native_ad_privacy"
android:layout_toEndOf="@id/mopub_native_ad_icon"
android:lines="2"
android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
android:textColor="@android:color/white"
android:textSize="14sp"
android:layout_marginLeft="12dp"
android:layout_marginRight="3dp"
android:layout_toLeftOf="@+id/mopub_native_ad_privacy"
android:layout_toRightOf="@id/mopub_native_ad_icon" />
<ImageView
android:id="@+id/mopub_native_ad_main_imageview"
android:layout_below="@id/mopub_native_ad_text"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="@dimen/native_main_image_height" />
<Button
android:id="@+id/mopub_native_ad_cta"
android:layout_width="match_parent"
android:layout_height="@dimen/button_height"
android:layout_marginLeft="10dp"
android:layout_below="@id/mopub_native_ad_main_imageview"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:textAllCaps="false"
android:focusable="true"
android:background="@color/colorPrimaryDark"
android:text="Free to play"
android:textSize="@dimen/button_text_size"
android:minWidth="0dp"
android:minHeight="0dp"
android:textColor="@android:color/white"
android:textStyle="bold" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
android:background="@color/colorPrimary"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mopub_native_video_ad_layout">
<ImageView
android:id="@+id/mopub_native_video_ad_privacy"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginTop="-5dp"
android:layout_marginEnd="-5dp"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:tint="@android:color/white"
android:contentDescription="Privacy Information Icon image"
android:padding="10dp"
android:layout_marginRight="-5dp"
android:layout_alignParentRight="true" />
<ImageView
android:id="@+id/mopub_native_video_ad_icon"
android:background="@null"
android:scaleType="centerInside"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginStart="10dp"
android:layout_alignParentStart="true"
android:layout_marginLeft="10dp"
android:layout_alignParentLeft="true" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/mopub_native_video_ad_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="@id/mopub_native_video_ad_icon"
android:layout_marginStart="10dp"
android:layout_toStartOf="@id/mopub_native_video_ad_privacy"
android:textColor="@android:color/white"
android:textStyle="bold"
android:textSize="16sp"
android:text="Lorem ipsum dolor sit amet, consectetur"
android:layout_marginEnd="10dp"
android:layout_alignTop="@id/mopub_native_video_ad_icon"
android:layout_toRightOf="@id/mopub_native_video_ad_icon"
android:layout_toLeftOf="@id/mopub_native_video_ad_privacy" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/mopub_native_video_ad_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/mopub_native_video_ad_title"
android:layout_marginStart="12dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="3dp"
android:layout_marginBottom="2dp"
android:layout_toStartOf="@+id/mopub_native_video_ad_privacy"
android:layout_toEndOf="@id/mopub_native_video_ad_icon"
android:lines="2"
android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"
android:textColor="@android:color/white"
android:textSize="14sp"
android:layout_marginLeft="12dp"
android:layout_marginRight="3dp"
android:layout_toLeftOf="@+id/mopub_native_video_ad_privacy"
android:layout_toRightOf="@id/mopub_native_video_ad_icon" />
<com.mopub.nativeads.MediaLayout
android:id="@+id/mopub_native_video_ad_media_layout"
android:layout_below="@id/mopub_native_video_ad_text"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
class MyMoPub {
private lateinit var mPersonalInfoManager: PersonalInfoManager
private lateinit var mContext: Context
fun init(context: Context, adunit: String) {
mContext = context
val sdkConfiguration = SdkConfiguration.Builder(adunit)
.withLogLevel(MoPubLog.LogLevel.DEBUG)
.withLegitimateInterestAllowed(false)
.build()
MoPub.initializeSdk(mContext, sdkConfiguration, initSdkListener())
}
private fun initSdkListener(): SdkInitializationListener {
return SdkInitializationListener {
/* MoPub SDK initialized.
Check if you should show the consent dialog here, and make your ad requests. */
Log.d("MoPub", "MoPub SDK Initilized")
GDPRConsent()
}
}
private fun GDPRConsent() {
mPersonalInfoManager = MoPub.getPersonalInformationManager()!!
Log.d("MoPub", "This country covered by GDPR? ${mPersonalInfoManager.gdprApplies()}")
if (mPersonalInfoManager.shouldShowConsentDialog()) {
mPersonalInfoManager.loadConsentDialog(initDialogLoadListener())
}
}
private fun initDialogLoadListener(): ConsentDialogListener {
return object : ConsentDialogListener {
override fun onConsentDialogLoaded() {
mPersonalInfoManager.showConsentDialog()
}
override fun onConsentDialogLoadFailed(@NonNull moPubErrorCode: MoPubErrorCode) {
Log.d("MoPub", "Consent dialog failed to load.")
}
}
}
}
class NativeAdRecyclerView : AppCompatActivity() {
private lateinit var itemsCells: ArrayList<String?>
private lateinit var adapter: NativeAd_RVAdapter
private lateinit var moPubAdapter: MoPubRecyclerAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_native_ad_recycler_view)
//Initialize MoPub SDK
MyMoPub().init(this, "AD_UNIT_ID")
//** Set the data for our ArrayList
setItemsData()
//** Set the adapter of the RecyclerView
setAdapter()
//** Set the Layout Manager of the RecyclerView
setRVLayoutManager()
}
private fun setItemsData() {
itemsCells = ArrayList()
for (i in 0..40) {
itemsCells.add("Item $i")
}
}
private fun setAdapter() {
adapter =
NativeAd_RVAdapter(itemsCells)
native_ad_rv.adapter = adapter
Handler().postDelayed({
initNativeAds()
}, 200)
adapter.notifyDataSetChanged()
}
private fun setRVLayoutManager() {
val mLayoutManager = LinearLayoutManager(native_ad_rv.context)
native_ad_rv.layoutManager = mLayoutManager
native_ad_rv.setHasFixedSize(true)
}
private fun initNativeAds() {
moPubAdapter = MoPubRecyclerAdapter(this, adapter)
val myViewBinder = ViewBinder.Builder(R.layout.mopub_native_ad_view)
.titleId(R.id.mopub_native_ad_title)
.textId(R.id.mopub_native_ad_text)
.mainImageId(R.id.mopub_native_ad_main_imageview)
.iconImageId(R.id.mopub_native_ad_icon)
.callToActionId(R.id.mopub_native_ad_cta)
.privacyInformationIconImageId(R.id.mopub_native_ad_privacy)
.build()
val myRenderer = MoPubStaticNativeAdRenderer(myViewBinder)
moPubAdapter.registerAdRenderer(myRenderer)
native_ad_rv.adapter = moPubAdapter
moPubAdapter.loadAds("AD_UNIT_ID")
}
override fun onDestroy() {
// You must call this or the ad adapter may cause a memory leak.
moPubAdapter.destroy()
super.onDestroy()
}
}
class NativeAdSingleView : AppCompatActivity() {
private lateinit var moPubNativeNetworkListener: MoPubNative.MoPubNativeNetworkListener
private lateinit var moPubNativeEventListener: NativeAd.MoPubNativeEventListener
private lateinit var moPubNative: MoPubNative
private lateinit var adapterHelper: AdapterHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_native_ad_single_view)
MyMoPub().init(this, "AD_UNIT_ID")
Handler().postDelayed({
initAds()
}, 200)
}
private fun initAds() {
moPubNativeEventListener = object : NativeAd.MoPubNativeEventListener{
override fun onClick(view: View?) {
// Click tracking.
Log.d("MoPub", "Native ad recorded a click.")
}
override fun onImpression(view: View?) {
// Impress is recorded - do what is needed AFTER the ad is visibly shown here.
Log.d("MoPub", "Native ad recorded an impression.")
}
}
moPubNativeNetworkListener = object : MoPubNative.MoPubNativeNetworkListener {
override fun onNativeLoad(nativeAd: NativeAd?) {
adapterHelper = AdapterHelper(this@NativeAdSingleView, 0, 3)
val v = adapterHelper.getAdView(null, native_ad_frame,nativeAd,ViewBinder.Builder(0).build())
nativeAd!!.setMoPubNativeEventListener(moPubNativeEventListener)
native_ad_frame.addView(v)
Log.d("MoPub", "Native ad has loaded.")
}
override fun onNativeFail(errorCode: NativeErrorCode) {
Log.d("MoPub", "Native ad failed to load with error: $errorCode")
}
}
moPubNative = MoPubNative(this, "AD_UNIT_ID", moPubNativeNetworkListener)
val viewBinder = ViewBinder.Builder(R.layout.mopub_native_ad_view)
.titleId(R.id.mopub_native_ad_title)
.textId(R.id.mopub_native_ad_text)
.mainImageId(R.id.mopub_native_ad_main_imageview)
.iconImageId(R.id.mopub_native_ad_icon)
.callToActionId(R.id.mopub_native_ad_cta)
.privacyInformationIconImageId(R.id.mopub_native_ad_privacy)
.build()
val adRenderer = MoPubStaticNativeAdRenderer(viewBinder)
moPubNative.registerAdRenderer(adRenderer)
moPubNative.makeRequest()
Log.d("MoPub", "Native ad is loading.")
}
override fun onDestroy() {
// You must call this or the native view may cause a memory leak.
moPubNative.destroy()
super.onDestroy()
}
}
class NativeAdViewPager : AppCompatActivity() {
lateinit var mPagerAdapter: CustomPagerAdapter
lateinit var moPubNativeAdLoadedListener: MoPubNativeAdLoadedListener
lateinit var adPlacer: MoPubStreamAdPlacer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_native_ad_view_pager)
MyMoPub().init(this, "AD_UNIT_ID")
initAds()
//** Set the adapter of the ViewPager
setAdapter()
}
private fun initAds() {
moPubNativeAdLoadedListener = object : MoPubNativeAdLoadedListener {
override fun onAdRemoved(position: Int) {
native_ad_pager.invalidate()
mPagerAdapter.notifyDataSetChanged()
Log.d("MoPub","Native ad has been removed")
}
override fun onAdLoaded(position: Int) {
native_ad_pager.invalidate()
mPagerAdapter.notifyDataSetChanged()
Log.d("MoPub","Native ad has been loaded")
}
}
// Set up a renderer for a static native ad.
val moPubStaticNativeAdRenderer = MoPubStaticNativeAdRenderer(ViewBinder.Builder(R.layout.mopub_native_ad_view)
.titleId(R.id.mopub_native_ad_title)
.textId(R.id.mopub_native_ad_text)
.mainImageId(R.id.mopub_native_ad_main_imageview)
.iconImageId(R.id.mopub_native_ad_icon)
.callToActionId(R.id.mopub_native_ad_cta)
.privacyInformationIconImageId(R.id.mopub_native_ad_privacy)
.build()
)
// This ad placer is used to automatically insert ads into the ViewPager.
adPlacer = MoPubStreamAdPlacer(this)
// The first renderer that can handle a particular native ad gets used.
adPlacer.registerAdRenderer(moPubStaticNativeAdRenderer)
adPlacer.setAdLoadedListener(moPubNativeAdLoadedListener)
}
private fun setAdapter() {
mPagerAdapter = CustomPagerAdapter(supportFragmentManager, adPlacer)
native_ad_pager.adapter = mPagerAdapter
Handler().postDelayed({
adPlacer.loadAds("AD_UNIT_ID")
Log.d("MoPub","Native ad is loading.")
},200)
}
override fun onDestroy() {
// You must call this or the ad adapter may cause a memory leak.
adPlacer.destroy()
super.onDestroy()
}
override fun onResume() {
// MoPub recommends to reload ads when the user returns to a view.
adPlacer.loadAds("AD_UNIT_ID")
super.onResume()
}
}
class NativeVideoAdRecyclerView : AppCompatActivity() {
lateinit var itemsCells: ArrayList<String?>
lateinit var adapter: NativeVideoAd_RVAdapter
private lateinit var moPubAdapter: MoPubRecyclerAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_native_video_ad_recycler_view)
MyMoPub().init(this, "AD_UNIT_ID")
//** Set the data for our ArrayList
setItemsData()
//** Set the adapter of the RecyclerView
setAdapter()
//** Set the Layout Manager of the RecyclerView
setRVLayoutManager()
}
private fun setItemsData() {
itemsCells = ArrayList()
for (i in 0..40) {
itemsCells.add("Item $i")
}
}
private fun setAdapter() {
adapter =
NativeVideoAd_RVAdapter(itemsCells)
native_video_ad_rv.adapter = adapter
initAds()
adapter.notifyDataSetChanged()
}
private fun setRVLayoutManager() {
val mLayoutManager = LinearLayoutManager(native_video_ad_rv.context)
native_video_ad_rv.layoutManager = mLayoutManager
native_video_ad_rv.setHasFixedSize(true)
}
private fun initAds() {
moPubAdapter = MoPubRecyclerAdapter(this, adapter)
val mediaViewBinder = MediaViewBinder.Builder(R.layout.mopub_native_video_ad_view)
.mediaLayoutId(R.id.mopub_native_video_ad_media_layout)
.iconImageId(R.id.mopub_native_video_ad_icon)
.titleId(R.id.mopub_native_video_ad_title)
.textId(R.id.mopub_native_video_ad_text)
.privacyInformationIconImageId(R.id.mopub_native_video_ad_privacy)
.build()
val moPubVideoNativeAdRenderer = MoPubVideoNativeAdRenderer(mediaViewBinder)
// You should still register a renderer for static native ads as well.
val staticViewBinder = ViewBinder.Builder(R.layout.mopub_native_ad_view)
.titleId(R.id.mopub_native_ad_title)
.textId(R.id.mopub_native_ad_text)
.mainImageId(R.id.mopub_native_ad_main_imageview)
.iconImageId(R.id.mopub_native_ad_icon)
.callToActionId(R.id.mopub_native_ad_cta)
.privacyInformationIconImageId(R.id.mopub_native_ad_privacy)
.build()
val moPubStaticNativeAdRenderer = MoPubStaticNativeAdRenderer(staticViewBinder)
moPubAdapter.registerAdRenderer(moPubStaticNativeAdRenderer)
moPubAdapter.registerAdRenderer(moPubVideoNativeAdRenderer)
native_video_ad_rv.adapter = moPubAdapter
moPubAdapter.loadAds("AD_UNIT_ID")
}
override fun onDestroy() {
// You must call this or the ad adapter may cause a memory leak.
moPubAdapter.destroy()
super.onDestroy()
}
}
class NativeVideoAdSingleView : AppCompatActivity() {
private lateinit var moPubNativeVideoNetworkListener: MoPubNative.MoPubNativeNetworkListener
private lateinit var moPubNativeVideoEventListener: NativeAd.MoPubNativeEventListener
private lateinit var moPubNativeVideo: MoPubNative
private lateinit var adapterHelper: AdapterHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_native_video_ad_single_view)
MyMoPub().init(this, "AD_UNIT_ID")
Handler().postDelayed({
initAds()
}, 200)
}
private fun initAds() {
moPubNativeVideoEventListener = object : NativeAd.MoPubNativeEventListener{
override fun onClick(view: View?) {
// Click tracking.
native_video_ad_status.text = "Native video ad recorded a click."
}
override fun onImpression(view: View?) {
// Impress is recorded - do what is needed AFTER the ad is visibly shown here.
native_video_ad_status.text = "Native video ad recorded an impression."
}
}
moPubNativeVideoNetworkListener = object : MoPubNative.MoPubNativeNetworkListener {
override fun onNativeLoad(nativeAd: NativeAd?) {
adapterHelper = AdapterHelper(this@NativeVideoAdSingleView, 0, 3)
val v = adapterHelper.getAdView(null, native_video_ad_frame,nativeAd,ViewBinder.Builder(0).build())
nativeAd!!.setMoPubNativeEventListener(moPubNativeVideoEventListener)
native_video_ad_frame.addView(v)
native_video_ad_status.text = "Native video ad has loaded."
}
override fun onNativeFail(errorCode: NativeErrorCode) {
native_video_ad_status.text = "Native video ad failed to load with error: $errorCode"
}
}
moPubNativeVideo = MoPubNative(this, "AD_UNIT_ID", moPubNativeVideoNetworkListener)
val mediaViewBinder = MediaViewBinder.Builder(R.layout.mopub_native_video_ad_view)
.mediaLayoutId(R.id.mopub_native_video_ad_media_layout)
.iconImageId(R.id.mopub_native_video_ad_icon)
.titleId(R.id.mopub_native_video_ad_title)
.textId(R.id.mopub_native_video_ad_text)
.privacyInformationIconImageId(R.id.mopub_native_video_ad_privacy)
.build()
val moPubVideoNativeAdRenderer = MoPubVideoNativeAdRenderer(mediaViewBinder)
moPubNativeVideo.registerAdRenderer(moPubVideoNativeAdRenderer)
moPubNativeVideo.makeRequest()
native_video_ad_status.text = "Native video ad is loading."
}
override fun onDestroy() {
// You must call this or the native video view may cause a memory leak.
moPubNativeVideo.destroy()
super.onDestroy()
}
}
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system"/>
</trust-anchors>
</base-config>
</network-security-config>
class RewardedVideoAdActivity : AppCompatActivity() {
private lateinit var moPubRewardedVideoListener : MoPubRewardedVideoListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rewarded_video_ad)
MyMoPub().init(this, "AD_UNIT_ID")
moPubRewardedVideoListener = object : MoPubRewardedVideoListener {
override fun onRewardedVideoClosed(adUnitId: String) {
Log.d("MoPub","Rewarded ad has closed")
}
override fun onRewardedVideoCompleted(adUnitIds: MutableSet<String>, reward: MoPubReward) {
//When the video ends, it triggers this callback in the background(before you press the close button)
Log.d("MoPub","Rewarded ad completed and the reward is: ${reward.amount}")
}
override fun onRewardedVideoPlaybackError(adUnitId: String, errorCode: MoPubErrorCode) {
Log.d("MoPub","Rewarded ad video playback error: $errorCode")
}
override fun onRewardedVideoLoadFailure(adUnitId: String, errorCode: MoPubErrorCode) {
Log.d("MoPub","Rewarded ad load failed: $errorCode")
}
override fun onRewardedVideoClicked(adUnitId: String) {
Log.d("MoPub","Rewarded ad clicked")
}
override fun onRewardedVideoStarted(adUnitId: String) {
Log.d("MoPub","Rewarded ad has started")
}
override fun onRewardedVideoLoadSuccess(adUnitId: String) {
Log.d("MoPub","Rewarded ad has loaded")
}
}
MoPubRewardedVideos.setRewardedVideoListener(moPubRewardedVideoListener)
load_rewarded_btn.setOnClickListener {
//Start loading the Rewarded Ad
MoPubRewardedVideos.loadRewardedVideo("AD_UNIT_ID")
Log.d("MoPub","Rewarded ad is loading")
}
check_rewarded_btn.setOnClickListener {
//Check if the Rewarded Ad is loaded
val isAvailable = MoPubRewardedVideos.hasRewardedVideo("AD_UNIT_ID")
Log.d("MoPub","Rewarded ad is available? $isAvailable")
}
show_rewarded_btn.setOnClickListener {
//Show the Rewarded Ad
MoPubRewardedVideos.showRewardedVideo("AD_UNIT_ID")
}
}
override fun onDestroy() {
MoPubRewardedVideos.setRewardedVideoListener(null)
super.onDestroy()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.