Skip to content

Instantly share code, notes, and snippets.

@iNuman
Created May 24, 2022 17:47
Show Gist options
  • Select an option

  • Save iNuman/522012e7d6a009a821760f1ebe72fb40 to your computer and use it in GitHub Desktop.

Select an option

Save iNuman/522012e7d6a009a821760f1ebe72fb40 to your computer and use it in GitHub Desktop.
BaseActivity Ads Integration
package com.numan.whatsstatussaverapp.ui.activity
import android.content.Context
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.Display
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustAdRevenue
import com.adjust.sdk.AdjustConfig
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdViewAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxAdView
import com.applovin.mediation.nativeAds.MaxNativeAdListener
import com.applovin.mediation.nativeAds.MaxNativeAdLoader
import com.applovin.mediation.nativeAds.MaxNativeAdView
import com.applovin.mediation.nativeAds.MaxNativeAdViewBinder
import com.google.android.gms.ads.*
import com.numan.whatsstatussaverapp.R
import com.numan.whatsstatussaverapp.ad_utils.NativeAdsManager
import com.numan.whatsstatussaverapp.ad_utils.app_lovin.AppLovinBanner.loadAndShowAppLovinBanner
import com.numan.whatsstatussaverapp.ad_utils.app_lovin.AppLovinInterstitials
import com.numan.whatsstatussaverapp.api.remote_config.HelperUtilsRemoteConfig.Companion.bannerAdId
import com.numan.whatsstatussaverapp.api.remote_config.HelperUtilsRemoteConfig.Companion.isPurchased
import com.numan.whatsstatussaverapp.api.remote_config.HelperUtilsRemoteConfig.Companion.startBannerInStatusesActivity
import com.numan.whatsstatussaverapp.api.remote_config.HelperUtilsRemoteConfig.Companion.startBannerInStickersActivity
import com.numan.whatsstatussaverapp.api.remote_config.HelperUtilsRemoteConfig.Companion.startNativeInDashboardScreen
import com.numan.whatsstatussaverapp.extensions.Extensions.gone
import com.numan.whatsstatussaverapp.extensions.Extensions.invisible
import com.numan.whatsstatussaverapp.extensions.Extensions.log
import com.numan.whatsstatussaverapp.extensions.Extensions.visible
import com.numan.whatsstatussaverapp.utils.isLollipopPlus
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
open class BaseActivityAds : AppCompatActivity() {
// private val nativeAdContainerView: ViewGroup? = null
var nativeAdLoader: MaxNativeAdLoader? = null
var loadedNativeAd: MaxAd? = null
var retryAttempt = 0
var nativeAdSmallMain: MaxAd? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
changeStatusBarColor()
}
private fun changeStatusBarColor() {
if (isLollipopPlus()) {
window.statusBarColor = ContextCompat.getColor(
this@BaseActivityAds,
R.color.colorPrimary
)
}
}
fun dashboardNativeAd() {
lifecycleScope.launchWhenCreated {
if (!isPurchased) {
loadAppLovinNative(findViewById<FrameLayout>(R.id.native_frame))
when (startNativeInDashboardScreen) {
2 -> {
showAppLovinNative()
}
1 -> {
// Admob
log("Admob Native here")
NativeAdsManager.starNatives(
this@BaseActivityAds,
findViewById<FrameLayout>(R.id.native_frame)
)
}
0 -> {
// Nothing
findViewById<ConstraintLayout>(R.id.top).gone()
log("Nothing will show here")
}
}
} else {
findViewById<ConstraintLayout>(R.id.top).gone()
}
}
}
fun setupStickersActivityBanner() {
if (!isPurchased) {
when (startBannerInStickersActivity) {
2 -> {
loadAndShowAppLovinBanner(this, findViewById(R.id.banner_container))
}
1 -> {
loadBanner(this, findViewById(R.id.banner_container))
}
0 -> {
findViewById<FrameLayout>(R.id.banner_container_).gone()
}
}
}
}
fun setupStatusesActivityBanner() {
if (!isPurchased) {
when (startBannerInStatusesActivity) {
2 -> {
loadAndShowAppLovinBanner(this, findViewById(R.id.banner_container))
}
1 -> {
loadBanner(this, findViewById(R.id.banner_container))
}
0 -> {
findViewById<FrameLayout>(R.id.banner_container_).gone()
}
}
}
}
fun loadAndShowAppLovinBanner(context: AppCompatActivity, view: FrameLayout) {
val adView = MaxAdView(context.getString(R.string.app_lovin_banner_id), context)
adView.setListener(object : MaxAdViewAdListener {
override fun onAdLoaded(ad: MaxAd?) {
log("Loaded max banner")
findViewById<TextView>(R.id.ad_is_loading_tv).invisible()
findViewById<FrameLayout>(R.id.banner_container).visible()
}
override fun onAdDisplayed(ad: MaxAd?) {
}
override fun onAdHidden(ad: MaxAd?) {
}
override fun onAdClicked(ad: MaxAd?) {
}
override fun onAdLoadFailed(adUnitId: String?, error: MaxError?) {
log("Failed Max onAdLoadFailed banner ${error?.message}")
}
override fun onAdDisplayFailed(ad: MaxAd?, error: MaxError?) {
log("Failed Display Max onAdDisplayFailed banner ${error?.message}")
}
override fun onAdExpanded(ad: MaxAd?) {
}
override fun onAdCollapsed(ad: MaxAd?) {
}
})
adView.setRevenueListener { ad ->
val adjustAdRevenue = AdjustAdRevenue(AdjustConfig.AD_REVENUE_APPLOVIN_MAX)
adjustAdRevenue.setRevenue(ad?.revenue, "USD")
adjustAdRevenue.setAdRevenueNetwork(ad?.networkName)
adjustAdRevenue.setAdRevenueUnit(ad?.adUnitId)
adjustAdRevenue.setAdRevenuePlacement(ad?.placement)
Adjust.trackAdRevenue(adjustAdRevenue)
}
view.addView(adView)
adView.loadAd()
}
fun loadBanner(context: Context, frameLayout: FrameLayout?) {
try {
var adView: AdView? = null
val adRequest = AdRequest.Builder().build()
adView = AdView(context)
adView.adUnitId = bannerAdId
if (frameLayout != null) {
frameLayout.removeAllViews()
frameLayout.addView(adView)
}
val adSize = getAdSize(context)
// Step 4 - Set the adaptive ad size on the ad view.
adView.adSize = adSize
// Step 5 - Start loading the ad in the background.
adView.loadAd(adRequest)
adView.adListener = object : AdListener() {
override fun onAdLoaded() {
// Code to be executed when an ad finishes loading.
findViewById<TextView>(R.id.ad_is_loading_tv).invisible()
findViewById<FrameLayout>(R.id.banner_container).visible()
}
override fun onAdFailedToLoad(adError: LoadAdError) {}
override fun onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
override fun onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
override fun onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
}
} catch (e: Exception) {
log("Exception : ${e.printStackTrace()}")
}
}
private fun getAdSize(activity: Context): AdSize? {
val manager: WindowManager =
activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display: Display = manager.defaultDisplay
val outMetrics = DisplayMetrics()
display.getMetrics(outMetrics)
val widthPixels = outMetrics.widthPixels.toFloat()
val density = outMetrics.density
val adWidth = (widthPixels / density).toInt()
// Step 3 - Get adaptive ad size and return for setting on the ad view.
return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(activity, adWidth)
}
fun loadAppLovinNative(nativeAdContainerView: FrameLayout) {
nativeAdLoader = MaxNativeAdLoader(getString(R.string.native_app_lovin_id), this)
nativeAdLoader?.setRevenueListener { }
nativeAdLoader?.setNativeAdListener(object : MaxNativeAdListener() {
override fun onNativeAdLoaded(nativeAdView: MaxNativeAdView?, nativeAd: MaxAd?) {
super.onNativeAdLoaded(nativeAdView, nativeAd)
// Clean up any pre-existing native ad to prevent memory leaks.
try {
findViewById<FrameLayout>(R.id.native_frame).visible()
findViewById<MaxAdView>(R.id.applovin_ad_view).invisible()
findViewById<FrameLayout>(R.id.loading_ad).invisible()
} catch (e: Exception) {
}
nativeAdLoader?.destroy(loadedNativeAd)
log("onNativeAdLoaded dual space: ${nativeAd.toString()}")
retryAttempt = 0
loadedNativeAd = nativeAd
nativeAdContainerView.removeAllViews()
nativeAdContainerView.addView(nativeAdView)
}
override fun onNativeAdLoadFailed(p0: String?, p1: MaxError?) {
super.onNativeAdLoadFailed(p0, p1)
log("onNativeAdLoadFailed: ${p1?.code.toString()}")
}
override fun onNativeAdClicked(p0: MaxAd?) {
super.onNativeAdClicked(p0)
}
})
}
fun showAppLovinNative() {
nativeAdLoader?.loadAd(createNativeAdView())
}
private fun createNativeAdView(): MaxNativeAdView {
val binder: MaxNativeAdViewBinder =
MaxNativeAdViewBinder.Builder(R.layout.app_lovin_native)
.setTitleTextViewId(R.id.title_text_view)
.setBodyTextViewId(R.id.body_text_view)
.setAdvertiserTextViewId(R.id.advertiser_textView)
.setIconImageViewId(R.id.icon_image_view)
.setMediaContentViewGroupId(R.id.media_view_container)
.setOptionsContentViewGroupId(R.id.options_view)
.setCallToActionButtonId(R.id.cta_button)
.build()
return MaxNativeAdView(binder, this)
}
override fun onDestroy() {
if (nativeAdSmallMain != null) {
nativeAdLoader?.destroy(nativeAdSmallMain)
}
if (loadedNativeAd != null) {
nativeAdLoader?.destroy(loadedNativeAd)
}
super.onDestroy()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment