I'm switching to the new Admob 2021 interstitials. New InterstitialAd My main event has 10 episodes and no matter which one I switch to, an interstitial ad will appear. However, when I got back to the event, I noticed that it wasn't showing again. What I want to do is reload after closing the interstitial ad.
public class MainActivity extends Activity {
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
mInterstitialAd = null;
}
});
}
}
If you can use hilt this is so simple just copy-paste this code its code work great in my production app
AdmobUtil.kt
#Singleton
class AdmobUtil #Inject constructor(#ApplicationContext private val context: Context) {
companion object {
private const val TEST_INTERSTITIAL_AD_UNIT_ID = "ca-app-pub-3940256099942544/1033173712"
private const val INTERSTITIAL_AD_UNIT_ID = ""
}
private lateinit var interstitialAd: InterstitialAd
init {
MobileAds.initialize(context) {
loadAdmobInterstitialAd()
}
}
private val interstitialAdUnitId = when {
(BuildConfig.DEBUG) -> TEST_INTERSTITIAL_AD_UNIT_ID
else -> INTERSTITIAL_AD_UNIT_ID
}
private fun loadAdmobInterstitialAd() {
interstitialAd = InterstitialAd(context)
interstitialAd.adUnitId = interstitialAdUnitId
interstitialAd.loadAd(AdRequest.Builder().build())
interstitialAd.adListener = object : AdListener() {
override fun onAdClosed() {
super.onAdClosed()
reloadInterstitialAd()
}
override fun onAdFailedToLoad(error: LoadAdError?) {
super.onAdFailedToLoad(error)
}
}
}
fun reloadInterstitialAd() {
if (::interstitialAd.isInitialized) interstitialAd.loadAd(AdRequest.Builder().build())
}
fun showInterstitialAd() {
if (::interstitialAd.isInitialized && interstitialAd.isLoaded) interstitialAd.show()
}
}
MainApplication.kt
#HiltAndroidApp
class MainApplication : Application() {
#Inject
lateinit var admobUtil: AdmobUtil
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
admobUtil.reloadInterstitialAd()
}
}
MainAcitivty.kt
#AndroidEntryPoint
class MainActivity : AppCompatActivity(R.layout.main_activity) {
#Inject
lateinit var admobUtil: AdmobUtil
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
admobUtil.showInterstitialAd()
}
}
Related
I'm using the newest ads play services (21.4.0) and see following behaviour (testing with test app id and test ad ids):
The onAdDismissedFullScreenContent function of FullScreenContentCallback is never called.
Problem
When I click the close button inside the interstitial ad no callback function is called... All other functions inside (at least the non error functions) are called successfully. Why? Am I missing something? I need to react to the event that the ad is being dismissed...
Code
load the ad
InterstitialAd.load(
context,
adId,
AdRequest.Builder().build(),
createInterstitialAdListener()
)
wait for the ad to be loaded inside the listener
private fun createInterstitialAdListener(): InterstitialAdLoadCallback {
return object : InterstitialAdLoadCallback() {
override fun onAdLoaded(ad: InterstitialAd) {
super.onAdLoaded(ad)
L.d { "Interstitial ad loaded..." }
ad.fullScreenContentCallback = createFullScreenContentCallback("Interstitial")
interstitialAd = ad
this#AdsViewManager.onAdLoaded()
}
override fun onAdFailedToLoad(error: LoadAdError) {
super.onAdFailedToLoad(error)
onAdLoadingError(error.message)
}
}
}
private fun createFullScreenContentCallback(type: String): FullScreenContentCallback {
return object : FullScreenContentCallback() {
override fun onAdClicked() {
// works!
L.d { "[$type] FullScreen ad clicked" }
}
override fun onAdDismissedFullScreenContent() {
// never gets called!
L.d { "[$type] FullScreen ad dismissed" }
interstitialAd = null
rewardedAd = null
}
override fun onAdFailedToShowFullScreenContent(error: AdError) {
onAdLoadingError(error.message)
interstitialAd = null
rewardedAd = null
}
override fun onAdImpression() {
// works!
L.d { "[$type] FullScreen ad - IMPRESSION" }
}
override fun onAdShowedFullScreenContent() {
// works!
L.d { "[$type] FullScreen ad showed..." }
}
}
}
show the ad when it is ready
fun show() {
if (interstitialAd == null) {
L.e { "Interstitial ad not ready" }
} else {
interstitialAd?.show(activity)
L.d { "Showing interstitial ad..." }
}
}
Logs from code above
Interstitial ad loaded...
Showing interstitial ad...
[Interstitial] FullScreen ad showed...
[Interstitial] FullScreen ad - IMPRESSION
// missing the close log... it never appears...
Try in this manner, in your Activity
private var interstitialAd: InterstitialAd? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
createInterstitialAdListener()
}
Your loadAd function
private fun createInterstitialAdListener(): InterstitialAdLoadCallback {
return object : InterstitialAdLoadCallback() {
override fun onAdLoaded(ad: InterstitialAd) {
super.onAdLoaded(ad)
L.d { "Interstitial ad loaded..." }
interstitialAd = ad
this#AdsViewManager.onAdLoaded()
}
override fun onAdFailedToLoad(error: LoadAdError) {
super.onAdFailedToLoad(error)
onAdLoadingError(error.message)
}
}
}
While showing Ad, copy/paste following...
fun show() {
if (interstitialAd == null) {
L.e { "Interstitial ad not ready" }
} else {
interstitialAd?.fullScreenContentCallback = fullScreenContentCallback
interstitialAd?.show(activity)
L.d { "Showing interstitial ad..." }
}
}
private val fullScreenContentCallback = object : FullScreenContentCallback() {
override fun onAdClicked() {
// works!
L.d { "[$type] FullScreen ad clicked" }
}
override fun onAdDismissedFullScreenContent() {
// never gets called!
L.d { "[$type] FullScreen ad dismissed" }
interstitialAd = null
rewardedAd = null
}
override fun onAdFailedToShowFullScreenContent(error: AdError) {
onAdLoadingError(error.message)
interstitialAd = null
rewardedAd = null
}
override fun onAdImpression() {
// works!
L.d { "[$type] FullScreen ad - IMPRESSION" }
}
override fun onAdShowedFullScreenContent() {
// works!
L.d { "[$type] FullScreen ad showed..." }
}
}
}
It will work as expected. Let me know, if it didn't work
After updating com.google.android.gms:play-services-ads to 19.7.0
it says InterstitialAd & RewardedVideoAd & UnifiedNativeAdView deprecated.
can anyone help ?
after a quick search, I found that we need to use
public abstract class InterstitialAd extends Object
instead of
public final class InterstitialAd extends Object
so you need to use:
com.google.android.gms.ads.interstitial.InterstitialAd
instead of:
come.google.android.gms.ads
and this is how we interact with the new package:
public class AdManager
{
private var interstitialAd: InterstitialAd? = null
private var mRewardedVideoAd: RewardedAd? = null
private var currentNativeAd: NativeAd? = null
private var builder: AdLoader.Builder? = null
init {
RequestConfiguration.Builder().setTestDeviceIds(
listOf(
AdRequest.DEVICE_ID_EMULATOR,
"CE88B9A1CB213EEEA19A2F7E54993908"
)
)
}
// Create a full screen content callback.
val fullScreenContentCallback = object : FullScreenContentCallback() {
override fun onAdFailedToShowFullScreenContent(p0: AdError) {
super.onAdFailedToShowFullScreenContent(p0)
}
override fun onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent()
}
override fun onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent()
interstitialAd = null
mRewardedVideoAd = null
}
}
fun createInterstitialAd(context: Context) {
InterstitialAd.load(
context,
BuildConfig.ADMOB_AD_INTERSTITIAL_UNIT_ID,
request.build(),
object : InterstitialAdLoadCallback() {
override fun onAdLoaded(ad: InterstitialAd) {
interstitialAd = ad
interstitialAd?.fullScreenContentCallback = fullScreenContentCallback
}
})
}
}
fun getFullScreenAd(): InterstitialAd? {
return interstitialAd
}
fun getVideoAd(): RewardedAd? {
return mRewardedVideoAd
}
fun loadRewardedVideoAd(context: Context) {
if (!userManager.getCurrentUser().isPremium) {
val request = AdRequest.Builder()
RewardedAd.load(
context,
BuildConfig.ADMOB_AD_VIDEO_UNIT_ID,
AdRequest.Builder().build(),
object : RewardedAdLoadCallback() {
override fun onAdLoaded(ad: RewardedAd) {
super.onAdLoaded(ad)
mRewardedVideoAd = ad;
mRewardedVideoAd?.fullScreenContentCallback = fullScreenContentCallback;
}
override fun onAdFailedToLoad(p0: LoadAdError) {
super.onAdFailedToLoad(p0)
}
})
}
fun loadNativeAd(context: Activity,adFrame:FrameLayout) {
builder = AdLoader.Builder(context, BuildConfig.ADMOB_AD_UNIT_ID_DIALOG_NATIVE)
builder?.forNativeAd { unifiedNativeAd: NativeAd ->
val adView: View =
context.layoutInflater.inflate(R.layout.ad_unified, null)
val ad = adView as NativeAdView
populateUnifiedNativeAdView(unifiedNativeAd, ad)
adFrame.removeAllViews()
adFrame.addView(ad)
}
val adLoader = builder?.withAdListener(object : AdListener() {
override fun onAdFailedToLoad(i: LoadAdError) {
super.onAdFailedToLoad(i)
Log.e("NativeAdFailed", i.toString() + "")
}
})?.build()
val builder = AdManagerAdRequest.Builder()
adLoader?.loadAd(builder.build())
}
}
private fun populateUnifiedNativeAdView(
nativeAd: NativeAd,
adView: NativeAdView
) {
// You must call destroy on old ads when you are done with them,
// otherwise you will have a memory leak.
if (currentNativeAd != null) currentNativeAd?.destroy()
currentNativeAd = nativeAd
// Set the media view.
adView.mediaView = adView.findViewById<View>(R.id.ad_media) as com.google.android.gms.ads.nativead.MediaView
// Set other ad assets.
adView.headlineView = adView.findViewById(R.id.ad_headline)
adView.bodyView = adView.findViewById(R.id.ad_body)
adView.callToActionView = adView.findViewById(R.id.ad_call_to_action)
adView.iconView = adView.findViewById(R.id.ad_app_icon)
adView.priceView = adView.findViewById(R.id.ad_price)
adView.starRatingView = adView.findViewById(R.id.ad_stars)
adView.storeView = adView.findViewById(R.id.ad_store)
adView.advertiserView = adView.findViewById(R.id.ad_advertiser)
// The headline and media content are guaranteed to be in every UnifiedNativeAd.
(adView.headlineView as TextView).text = nativeAd.headline
nativeAd.mediaContent?.let {
adView.mediaView?.setMediaContent(it)
}
// These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
// check before trying to display them.
if (nativeAd.body == null) {
adView.bodyView?.visibility = View.INVISIBLE
} else {
adView.bodyView?.visibility = View.VISIBLE
(adView.bodyView as TextView).text = nativeAd.body
}
if (nativeAd.callToAction == null) {
adView.callToActionView?.visibility = View.INVISIBLE
} else {
adView.callToActionView?.visibility = View.VISIBLE
(adView.callToActionView as TextView).text = nativeAd.callToAction
}
if (nativeAd.icon == null) {
adView.iconView?.visibility = View.GONE
} else {
(adView.iconView as ImageView).setImageDrawable(
nativeAd.icon?.drawable
)
adView.iconView?.visibility = View.VISIBLE
}
if (nativeAd.price == null) {
adView.priceView?.visibility = View.INVISIBLE
} else {
adView.priceView?.visibility = View.VISIBLE
(adView.priceView as TextView).text = nativeAd.price
}
if (nativeAd.store == null) {
adView.storeView?.visibility = View.INVISIBLE
} else {
adView.storeView?.visibility = View.VISIBLE
(adView.storeView as TextView).text = nativeAd.store
}
if (nativeAd.starRating == null) {
adView.starRatingView?.visibility = View.INVISIBLE
} else {
nativeAd.starRating?.toDouble()?.let {
(adView.starRatingView as RatingBar).rating = it.toFloat()
adView.starRatingView?.visibility = View.VISIBLE
}
}
if (nativeAd.advertiser == null) {
adView.advertiserView?.visibility = View.INVISIBLE
} else {
(adView.advertiserView as TextView).text = nativeAd.advertiser
adView.advertiserView?.visibility = View.VISIBLE
}
// This method tells the Google Mobile Ads SDK that you have finished populating your
// native ad view with this native ad.
adView.setNativeAd(nativeAd)
}
}
There are many breaking changes coming in version 20.0.0. Version
19.7.0 introduced many new APIs, and deprecated or renamed many classes in preparation for version 20.0.0.
This code explains how to integrate interstitial ads in v 19.7.0
class Web : AppCompatActivity() {
private var mInterstitialAd: InterstitialAd? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_web)
// load ad
loadAd();
toNextLevel()
}
// load ad
private fun loadAd() {
InterstitialAd.load(
this#Web,
"ca-app-pub-3940256099942544/1033173712",
AdRequest.Builder().build(),
object : InterstitialAdLoadCallback() {
override fun onAdLoaded(interstitialAd: InterstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd
mInterstitialAd?.fullScreenContentCallback =
object : FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent()
mInterstitialAd = null
//// perform your code that you wants to do after ad dismissed or closed
}
override fun onAdFailedToShowFullScreenContent(adError: AdError) {
super.onAdFailedToShowFullScreenContent(adError)
mInterstitialAd = null
/// perform your action here when ad will not load
}
override fun onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent()
this#Web.mInterstitialAd = null
}
}
}
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
// Handle the error
mInterstitialAd = null
}
})
}
private fun toNextLevel() {
// Show the interstitial if it is ready. Otherwise, proceed to the next level
// without ever showing it
if (mInterstitialAd != null) {
mInterstitialAd?.show(this#Web)
} else {
nextLevel()
// in case you want to load a new ad
requestNewInterstitial()
}
}
private fun nextLevel() {
TODO("Not yet implemented")
}
private fun requestNewInterstitial() {
if (mInterstitialAd == null) {
loadAd()
}
}
}
use com.google.android.gms.ads.interstitial.InterstitialAd
instead of
come.google.android.gms.ads
when you upgrade the admob sdk to
implementation 'com.google.firebase:firebase-ads:19.7.0'
you will found the old sdk method deprecated like InterstitialAD
Its Simple here just follow my way to load your interstitial and remove deprecation here its my sample code for better ad request load your add in the On start in your activity if you have any query kindly let me know below in comments copy paste the below code:
public static AdRequest adRequest;
public static InterstitialAd mInterstitialAd;
public void InterstitialAdmob() {
InterstitialAd.load(MainActivity.this,getString(R.string.Interstitial), adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
mInterstitialAd=null;
//// perform your code that you wants todo after ad dismissed or closed
}
#Override
public void onAdFailedToShowFullScreenContent(com.google.android.gms.ads.AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
mInterstitialAd = null;
/// perform your action here when ad will not load
}
#Override
public void onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent();
mInterstitialAd = null;
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
mInterstitialAd = null;
}
});
}
#Override
protected void onStart() {
super.onStart();
measyrating.onStart();
adRequest = new AdRequest.Builder().build();
InterstitialAdmob();
}
Now show your ads simply on backpressed or button click
#Override
public void onBackPressed() {
if (mInterstitialAd!=null){
mInterstitialAd.show(MainActivity.this);
}
else{
if (doubleBackToExitPressedOnce) {
if (mBottomNavigationView.getSelectedItemId() == R.id.navigation_doc)
{
super.onBackPressed();
}
else
{
mBottomNavigationView.setSelectedItemId(R.id.navigation_doc);
}
return;
}
this.doubleBackToExitPressedOnce = true;
if (this.drawer.isDrawerOpen(GravityCompat.START)) {
this.drawer.closeDrawer(GravityCompat.START);
}
if (itempositionselected==0){
loadFragment(new DocxFileFragment());
}
else {
}
if (!searchView.isIconified()) {
searchView.setIconified(true);
}
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
Google Mobile Ads SDK version 20.0.0 is planned for early 2021 and comes with a few major changes, as well as several straightforward API renames and removal of deprecated APIs.
You can check more details on this link.
Use NativeAdView instead of UnifiedNativeAdView and so on.
Following page has example and details for newer version of interstitial ad
https://developers.google.com/admob/android/interstitial
Below is a full working example based on above i am using with current versioncom.google.android.gms:play-services-ads:20.2.0:
public class BriefDisplayActivity extends AppCompatActivity {
InterstitialAd briefInterstitialAd;
AdRequest adRequest_I = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest_I,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
BriefDisplayActivity.this.briefInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
briefInterstitialAd.show(BriefDisplayActivity.this);
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
BriefDisplayActivity.this.briefInterstitialAd = null;
}
});
}
I want to insert parameter during runtime by using Dagger-Hilt. I knew that it could be achieved using annotation that hilt is providing i.e #AssistedFactory. I m implementing it the same way, but still it throws an error lateinit property isn't initialized. I couldn't find where I go wrong if some can help me in this regard. Following is what I have done so far.
Timer.kt
#AssistedFactory
interface TimerFactory {
fun create(
#Assisted("millis")
millisInFuture: Long,
#Assisted("interval")
countDownInterval: Long
): Timer
}
var isRunning = true
class Timer #AssistedInject constructor(
#Assisted("millis") val millisInFuture: Long,
#Assisted("interval") val countDownInterval: Long
) :
CountDownTimer(millisInFuture, countDownInterval) {
var otpView: TextView? = null
companion object {
var remainMilli: Long = 0
}
override fun onTick(millisInFuture: Long) {
remainMilli = millisInFuture
otpView?.text = (millisInFuture / 1000).toString() + "seconds"
}
override fun onFinish() {
isRunning = false
remainMilli = 0
}
fun setTimerView(view: View) {
otpView = view as TextView
}
}
Fragment.kt
#Inject
lateinit var timerFactory: TimerFactory
private lateinit var timer: Timer
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setTimer()
timer.setTimerView(binding.pvOtp)
}
private fun setTimer() {
if (!isRunning) {
timer.cancel()
isRunning = true
} else {
if (remainMilli == 0L) {
timer = timerFactory.create(30000, 1000)// lateinit property timerFactory has not been initialized
timer.start()
isRunning = false
} else {
timer = timerFactory.create(remainMilli, 1000)
timer.start()
isRunning = false
}
}
}
MainActivity & ApplicationAcitivty
#AndroidEntryPoint
class MainAcitivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
}
#HiltAndroidApp
class Sample: Application() {
override fun onCreate() {
super.onCreate()
}
}
Menifest.xml
<application
android:name=".Sample"
...</application>
GeneratedFile OTPFragment_MembersInjector.kt
#DaggerGenerated
#SuppressWarnings({
"unchecked",
"rawtypes"
})
public final class OTPFragment_MembersInjector implements MembersInjector<OTPFragment> {
private final Provider<TimerFactory> timerFactoryProvider;
public OTPFragment_MembersInjector(Provider<TimerFactory> timerFactoryProvider) {
this.timerFactoryProvider = timerFactoryProvider;
}
public static MembersInjector<OTPFragment> create(Provider<TimerFactory> timerFactoryProvider) {
return new OTPFragment_MembersInjector(timerFactoryProvider);
}
#Override
public void injectMembers(OTPFragment instance) {
injectTimerFactory(instance, timerFactoryProvider.get());
}
#InjectedFieldSignature("com.jsglobal.ui.fragment.auth_fragment.OTPFragment.timerFactory")
public static void injectTimerFactory(OTPFragment instance, TimerFactory timerFactory) {
instance.timerFactory = timerFactory;
}
}
Any Help would be really appreciated. Thanks
After updating com.google.android.gms:play-services-ads to 19.7.0
it says InterstitialAd & RewardedVideoAd & UnifiedNativeAdView deprecated.
can anyone help ?
after a quick search, I found that we need to use
public abstract class InterstitialAd extends Object
instead of
public final class InterstitialAd extends Object
so you need to use:
com.google.android.gms.ads.interstitial.InterstitialAd
instead of:
come.google.android.gms.ads
and this is how we interact with the new package:
public class AdManager
{
private var interstitialAd: InterstitialAd? = null
private var mRewardedVideoAd: RewardedAd? = null
private var currentNativeAd: NativeAd? = null
private var builder: AdLoader.Builder? = null
init {
RequestConfiguration.Builder().setTestDeviceIds(
listOf(
AdRequest.DEVICE_ID_EMULATOR,
"CE88B9A1CB213EEEA19A2F7E54993908"
)
)
}
// Create a full screen content callback.
val fullScreenContentCallback = object : FullScreenContentCallback() {
override fun onAdFailedToShowFullScreenContent(p0: AdError) {
super.onAdFailedToShowFullScreenContent(p0)
}
override fun onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent()
}
override fun onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent()
interstitialAd = null
mRewardedVideoAd = null
}
}
fun createInterstitialAd(context: Context) {
InterstitialAd.load(
context,
BuildConfig.ADMOB_AD_INTERSTITIAL_UNIT_ID,
request.build(),
object : InterstitialAdLoadCallback() {
override fun onAdLoaded(ad: InterstitialAd) {
interstitialAd = ad
interstitialAd?.fullScreenContentCallback = fullScreenContentCallback
}
})
}
}
fun getFullScreenAd(): InterstitialAd? {
return interstitialAd
}
fun getVideoAd(): RewardedAd? {
return mRewardedVideoAd
}
fun loadRewardedVideoAd(context: Context) {
if (!userManager.getCurrentUser().isPremium) {
val request = AdRequest.Builder()
RewardedAd.load(
context,
BuildConfig.ADMOB_AD_VIDEO_UNIT_ID,
AdRequest.Builder().build(),
object : RewardedAdLoadCallback() {
override fun onAdLoaded(ad: RewardedAd) {
super.onAdLoaded(ad)
mRewardedVideoAd = ad;
mRewardedVideoAd?.fullScreenContentCallback = fullScreenContentCallback;
}
override fun onAdFailedToLoad(p0: LoadAdError) {
super.onAdFailedToLoad(p0)
}
})
}
fun loadNativeAd(context: Activity,adFrame:FrameLayout) {
builder = AdLoader.Builder(context, BuildConfig.ADMOB_AD_UNIT_ID_DIALOG_NATIVE)
builder?.forNativeAd { unifiedNativeAd: NativeAd ->
val adView: View =
context.layoutInflater.inflate(R.layout.ad_unified, null)
val ad = adView as NativeAdView
populateUnifiedNativeAdView(unifiedNativeAd, ad)
adFrame.removeAllViews()
adFrame.addView(ad)
}
val adLoader = builder?.withAdListener(object : AdListener() {
override fun onAdFailedToLoad(i: LoadAdError) {
super.onAdFailedToLoad(i)
Log.e("NativeAdFailed", i.toString() + "")
}
})?.build()
val builder = AdManagerAdRequest.Builder()
adLoader?.loadAd(builder.build())
}
}
private fun populateUnifiedNativeAdView(
nativeAd: NativeAd,
adView: NativeAdView
) {
// You must call destroy on old ads when you are done with them,
// otherwise you will have a memory leak.
if (currentNativeAd != null) currentNativeAd?.destroy()
currentNativeAd = nativeAd
// Set the media view.
adView.mediaView = adView.findViewById<View>(R.id.ad_media) as com.google.android.gms.ads.nativead.MediaView
// Set other ad assets.
adView.headlineView = adView.findViewById(R.id.ad_headline)
adView.bodyView = adView.findViewById(R.id.ad_body)
adView.callToActionView = adView.findViewById(R.id.ad_call_to_action)
adView.iconView = adView.findViewById(R.id.ad_app_icon)
adView.priceView = adView.findViewById(R.id.ad_price)
adView.starRatingView = adView.findViewById(R.id.ad_stars)
adView.storeView = adView.findViewById(R.id.ad_store)
adView.advertiserView = adView.findViewById(R.id.ad_advertiser)
// The headline and media content are guaranteed to be in every UnifiedNativeAd.
(adView.headlineView as TextView).text = nativeAd.headline
nativeAd.mediaContent?.let {
adView.mediaView?.setMediaContent(it)
}
// These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
// check before trying to display them.
if (nativeAd.body == null) {
adView.bodyView?.visibility = View.INVISIBLE
} else {
adView.bodyView?.visibility = View.VISIBLE
(adView.bodyView as TextView).text = nativeAd.body
}
if (nativeAd.callToAction == null) {
adView.callToActionView?.visibility = View.INVISIBLE
} else {
adView.callToActionView?.visibility = View.VISIBLE
(adView.callToActionView as TextView).text = nativeAd.callToAction
}
if (nativeAd.icon == null) {
adView.iconView?.visibility = View.GONE
} else {
(adView.iconView as ImageView).setImageDrawable(
nativeAd.icon?.drawable
)
adView.iconView?.visibility = View.VISIBLE
}
if (nativeAd.price == null) {
adView.priceView?.visibility = View.INVISIBLE
} else {
adView.priceView?.visibility = View.VISIBLE
(adView.priceView as TextView).text = nativeAd.price
}
if (nativeAd.store == null) {
adView.storeView?.visibility = View.INVISIBLE
} else {
adView.storeView?.visibility = View.VISIBLE
(adView.storeView as TextView).text = nativeAd.store
}
if (nativeAd.starRating == null) {
adView.starRatingView?.visibility = View.INVISIBLE
} else {
nativeAd.starRating?.toDouble()?.let {
(adView.starRatingView as RatingBar).rating = it.toFloat()
adView.starRatingView?.visibility = View.VISIBLE
}
}
if (nativeAd.advertiser == null) {
adView.advertiserView?.visibility = View.INVISIBLE
} else {
(adView.advertiserView as TextView).text = nativeAd.advertiser
adView.advertiserView?.visibility = View.VISIBLE
}
// This method tells the Google Mobile Ads SDK that you have finished populating your
// native ad view with this native ad.
adView.setNativeAd(nativeAd)
}
}
There are many breaking changes coming in version 20.0.0. Version
19.7.0 introduced many new APIs, and deprecated or renamed many classes in preparation for version 20.0.0.
This code explains how to integrate interstitial ads in v 19.7.0
class Web : AppCompatActivity() {
private var mInterstitialAd: InterstitialAd? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_web)
// load ad
loadAd();
toNextLevel()
}
// load ad
private fun loadAd() {
InterstitialAd.load(
this#Web,
"ca-app-pub-3940256099942544/1033173712",
AdRequest.Builder().build(),
object : InterstitialAdLoadCallback() {
override fun onAdLoaded(interstitialAd: InterstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd
mInterstitialAd?.fullScreenContentCallback =
object : FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent()
mInterstitialAd = null
//// perform your code that you wants to do after ad dismissed or closed
}
override fun onAdFailedToShowFullScreenContent(adError: AdError) {
super.onAdFailedToShowFullScreenContent(adError)
mInterstitialAd = null
/// perform your action here when ad will not load
}
override fun onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent()
this#Web.mInterstitialAd = null
}
}
}
override fun onAdFailedToLoad(loadAdError: LoadAdError) {
// Handle the error
mInterstitialAd = null
}
})
}
private fun toNextLevel() {
// Show the interstitial if it is ready. Otherwise, proceed to the next level
// without ever showing it
if (mInterstitialAd != null) {
mInterstitialAd?.show(this#Web)
} else {
nextLevel()
// in case you want to load a new ad
requestNewInterstitial()
}
}
private fun nextLevel() {
TODO("Not yet implemented")
}
private fun requestNewInterstitial() {
if (mInterstitialAd == null) {
loadAd()
}
}
}
use com.google.android.gms.ads.interstitial.InterstitialAd
instead of
come.google.android.gms.ads
when you upgrade the admob sdk to
implementation 'com.google.firebase:firebase-ads:19.7.0'
you will found the old sdk method deprecated like InterstitialAD
Its Simple here just follow my way to load your interstitial and remove deprecation here its my sample code for better ad request load your add in the On start in your activity if you have any query kindly let me know below in comments copy paste the below code:
public static AdRequest adRequest;
public static InterstitialAd mInterstitialAd;
public void InterstitialAdmob() {
InterstitialAd.load(MainActivity.this,getString(R.string.Interstitial), adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
mInterstitialAd=null;
//// perform your code that you wants todo after ad dismissed or closed
}
#Override
public void onAdFailedToShowFullScreenContent(com.google.android.gms.ads.AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
mInterstitialAd = null;
/// perform your action here when ad will not load
}
#Override
public void onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent();
mInterstitialAd = null;
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
mInterstitialAd = null;
}
});
}
#Override
protected void onStart() {
super.onStart();
measyrating.onStart();
adRequest = new AdRequest.Builder().build();
InterstitialAdmob();
}
Now show your ads simply on backpressed or button click
#Override
public void onBackPressed() {
if (mInterstitialAd!=null){
mInterstitialAd.show(MainActivity.this);
}
else{
if (doubleBackToExitPressedOnce) {
if (mBottomNavigationView.getSelectedItemId() == R.id.navigation_doc)
{
super.onBackPressed();
}
else
{
mBottomNavigationView.setSelectedItemId(R.id.navigation_doc);
}
return;
}
this.doubleBackToExitPressedOnce = true;
if (this.drawer.isDrawerOpen(GravityCompat.START)) {
this.drawer.closeDrawer(GravityCompat.START);
}
if (itempositionselected==0){
loadFragment(new DocxFileFragment());
}
else {
}
if (!searchView.isIconified()) {
searchView.setIconified(true);
}
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
Google Mobile Ads SDK version 20.0.0 is planned for early 2021 and comes with a few major changes, as well as several straightforward API renames and removal of deprecated APIs.
You can check more details on this link.
Use NativeAdView instead of UnifiedNativeAdView and so on.
Following page has example and details for newer version of interstitial ad
https://developers.google.com/admob/android/interstitial
Below is a full working example based on above i am using with current versioncom.google.android.gms:play-services-ads:20.2.0:
public class BriefDisplayActivity extends AppCompatActivity {
InterstitialAd briefInterstitialAd;
AdRequest adRequest_I = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest_I,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
BriefDisplayActivity.this.briefInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
briefInterstitialAd.show(BriefDisplayActivity.this);
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
BriefDisplayActivity.this.briefInterstitialAd = null;
}
});
}
Using Firebase, I'm trying to get the SMS code by phone number, but it doesn’t work. Everything does not work in two cases:
Inside onVerificationCompleted() function with log message sms code is null.
After visiting startPhoneNumberVerification() function logs stop writing and I don't receive SMS code either.
I read the documentation, looked at different versions of the code on Github, but I don't understand why my code doesn't work.
VerificationFragment
class VerificationFragment : BaseFragment() {
private lateinit var phone: String
override val menuResId: Nothing? = null
override val contentResId = R.layout.fragment_verification
override val baseToolbar = R.id.toolbar
private var verificationId = ""
private val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onCodeSent(s: String, p1: PhoneAuthProvider.ForceResendingToken) {
super.onCodeSent(s, p1)
verificationId = s
}
override fun onVerificationCompleted(phoneAuthCredential: PhoneAuthCredential) {
val code = phoneAuthCredential.smsCode
if (code != null) {
Log.d("SmsCode", "onVerificationCompleted(): ща будем верифаить")
verifyCode(code)
} else {
Log.d("SmsCode", "onVerificationCompleted(): sms code is null")
}
}
override fun onVerificationFailed(e: FirebaseException) {
if (e is FirebaseAuthInvalidCredentialsException) {
Log.d("SmsCode", "onVerificationFailed(): Invalid request")
} else if (e is FirebaseTooManyRequestsException) {
Log.d("SmsCode", "onVerificationFailed(): The SMS quota for the project has been exceeded")
}
}
}
private fun startPhoneNumberVerification(phoneNumber: String) {
Log.d("SmsCode", "startPhoneNumberVerification() visited")
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phoneNumber,
60,
TimeUnit.SECONDS,
baseActivity,
callbacks
)
}
fun verifyCode(code: String) {
Log.d("SmsCode", "verificationId: $verificationId")
val credential = PhoneAuthProvider.getCredential(verificationId, code)
singInWithCredential(credential)
}
private fun singInWithCredential(credential: PhoneAuthCredential) {
val mAuth = FirebaseAuth.getInstance()
mAuth.signInWithCredential(credential)
.addOnCompleteListener(baseActivity) { task ->
if (task.isSuccessful) {
val fUser = task.result?.user
Log.d("SmsCode", "singInWithCredential(): fUser is $fUser")
} else {
Log.d("SmsCode", "singInWithCredential(): error")
}
}
}
override fun setViews() {
phone = VerificationFragmentArgs.fromBundle(requireArguments()).phone
setPhoneNumber()
startPhoneNumberVerification(phone)
}
private fun setPhoneNumber() {
verificationText.text = String.format(verificationText.text.toString(), phone)
}
}
BaseFragment
abstract class BaseFragment: Fragment() {
val baseActivity: MainActivity
get() = activity as MainActivity
private var currentView: View? = null
protected abstract val menuResId: Int?
protected abstract val contentResId: Int
protected abstract val baseToolbar: Int
protected inline fun <T> LiveData<T>.observe(crossinline codeBlock: (T) -> Unit) {
observe(this#BaseFragment, Observer { it -> it?.let { codeBlock(it) } })
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
if (currentView == null) {
currentView = inflater.inflate(contentResId, container, false)
}
return currentView!!
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setViews()
setToolbar(view)
setObservers()
setListeners()
setActions()
}
protected open fun setViews() {}
protected open fun setObservers() {}
protected open fun setListeners() {}
protected open fun setActions() {}
fun showBottomBar() = baseActivity.showBottomBar()
fun hideBottomBar() = baseActivity.hideBottomBar()
protected open fun setToolbar(view: View) {
menuResId?.let {
view.findViewById<MaterialToolbar>(baseToolbar).inflateMenu(it)
}
}
}
Adequate firebase messages do not appear in the logs. I have one test number, but I can’t get the SMS code to other numbers either.
I would be grateful for any answers.
You need firstly to enable phone authentication in firebase and then you can follow the code below :
public class VerifyPhoneNumActivity extends AppCompatActivity {
protected PinView editTextCode;
protected TextView resendCode;
DatabaseReference reference;
FirebaseUser firebaseUser;
String phone_number;
String code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_verify_phone_num);
initView();
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
Intent intent = getIntent();
phone_number = intent.getStringExtra("phone_number");
sendVerificationCode(phone_number);
resendCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendVerificationCode(phone_number);
}
});
}
private void sendVerificationCode(String mobile) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
"+20" + mobile,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallbacks);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks
= new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
//Getting the code sent by SMS
code = phoneAuthCredential.getSmsCode();
//sometime the code is not detected automatically
//in this case the code will be null
//so user has to manually enter the code
if (code != null) {
editTextCode.setText(code);
//verifying the code
verifyVerificationCode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
// public void onVerificationFailed(FirebaseException e) {
// Toast.makeText(VerifyPhoneNumActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
Toast.makeText(VerifyPhoneNumActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference.removeValue();
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
}
};
private void verifyVerificationCode(String otp) {
//signing the user
reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
HashMap<String, Object> map = new HashMap<>();
map.put("phone", phone_number);
reference.updateChildren(map);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(VerifyPhoneNumActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}, 5000);
}
private void initView() {
editTextCode = (PinView) findViewById(R.id.editTextCode);
resendCode = (TextView) findViewById(R.id.resend_code);
}
}
and the xml file :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".controller.Register_Login.VerifyPhoneNumActivity">
<LinearLayout
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints">
<com.chaos.view.PinView
android:id="#+id/editTextCode"
style="#style/PinWidget.PinView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:padding="10dp"
android:layout_marginTop="80dp"
android:textColor="#222222"
android:textSize="18sp"
android:cursorVisible="true"
app:cursorColor="#color/colorAccent"
app:cursorWidth="2dp"
app:itemCount="6"
app:itemHeight="48dp"
app:itemRadius="4dp"
app:itemSpacing="5dp"
app:itemWidth="36dp"
app:lineColor="#color/colorPrimary"
app:lineWidth="2dp"
app:viewType="rectangle" />
<TextView
android:id="#+id/resend_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#019b77"
android:textStyle="bold"
android:textAlignment="center"
android:text="#string/i_didn_t_get_a_code"
android:textSize="20sp"
android:layout_marginTop="20dp"/>
</LinearLayout>
I actually use phone number which I got from another but absolutely you can change this, hope it's helpful