After updating Google Ads SDK to 19.7.0 gives a deprecated warning message for InterstitialAd, while I searched this link for resolving the issue but not succeed.
how can I resolve it?
Here my code
public void InterstitialAdmob() {
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(Util.ADMOBINTER);
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
}
protected void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder().addTestDevice(ADMOBDEV).build();
mInterstitialAd.loadAd(adRequest);
}
// for showing ads
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
and developer site or suggestion
Check the new API examples here:
https://developers.google.com/admob/android/interstitial-fullscreen
Warning: There are many breaking changes coming in version 20.0.0. Version 19.7.0 introduces many new APIs, and deprecates or renames many classes in preparation for version 20.0.0. Please read the migration guide for more details on the changes.
https://developers.google.com/admob/android/migration
This is what I did on my fragment, with just 4 steps.
1.Replace the deprecated import:
import com.google.android.gms.ads.InterstitialAd
with the new one:
import com.google.android.gms.ads.interstitial.InterstitialAd
2.Replace the old initialization:
interstitialAd = InterstitialAd(requireContext())
interstitialAd.adUnitId = "ca-app-pub-00000000/11111111"
interstitialAd.loadAd(AdRequest.Builder().build())
with the new one:
val adRequest = AdRequest.Builder().build()
InterstitialAd.load(requireContext(),
"ca-app-pub-00000000/11111111",
adRequest,
object : InterstitialAdLoadCallback() {
override fun onAdLoaded(myAd: InterstitialAd) {
Timber.d("Ad Loaded")
interstitialAd = myAd
}
override fun onAdFailedToLoad(adError: LoadAdError) {
Timber.d("Failed to load ad: ${adError.message}")
interstitialAd = null
}
})
3.Replace the old way of showing it:
if (interstitialAd.isLoaded) {
interstitialAd.show()
} else {
Timber.d("Ad wasn't loaded yet!")
}
with the new one:
if (interstitialAd != null){
interstitialAd?.show(requireActivity())
}else {
Timber.d("Interstitial Ad not ready yet")
}
4.There is no step 4, enjoy😁
Source
public static com.google.android.gms.ads.interstitial.InterstitialAd googleFullscreen;
public static void mLoadGoogleFullScreenAds(final Activity activity) {
FullScreenContentCallback fullScreenContentCallback = new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
googleFullscreen = null;
// Proceed to the next level.
}
#Override
public void onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent();
}
#Override
public void onAdFailedToShowFullScreenContent(com.google.android.gms.ads.AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
Log.d(TAG, "onAdFailedToShowFullScreenContent: " + adError.toString());
}
};
googleFullscreen.load(
activity,
activity.getResources().getString(R.string.google_fullscreen),
new AdRequest.Builder().build(),
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd ad) {
googleFullscreen = ad;googleFullscreen.setFullScreenContentCallback(fullScreenContentCallback);
googleFullscreen.show(activity);
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError adError) {
googleFullscreen = null;
Log.d(TAG, "onAdFailedToLoad: " + adError.toString());
// Code to be executed when an ad request fails.
}
});
}
i think this code solve your problem
Related
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'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()
}
}
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 include in-app billing in my Android app.
When reading the documentation it says to:
"specify a listener which implements the SkuDetailsResponseListener interface. You can then override onSkuDetailsResponse() which notifies the listener when the query finishes"
public class MainActivity extends AppCompatActivity implements SkuDetailsResponseListener {
Which gives:
#Override
public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) {
}
However, this is a problem because it doesn't include the listener specified in the documentation, ie.
billingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(BillingResult billingResult,
List<SkuDetails> skuDetailsList) {
// Process the result.
}
});
When including the BillingClient line and the listener there is obviously a resolve symbol error as it is outside any method, so how do you work around this?
Additionally, would you then place this block inside onCreate()?
List<String> skuList = new ArrayList<> ();
skuList.add("coins5");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(SkuType.INAPP);
As documented in Billing API documentation, you also need to implement the BillingClientStateListener as well as PurchaseUpdateListener. https://developer.android.com/google/play/billing/integrate
The following code is a working example in Billing API 3.0 with Android Version Targeted SDK 28. The code is defined in a Singleton class so it can be used from multiple activities with one instance of BillingClient.
public class ApplicationBillingClient
{
static ApplicationBillingClient applicationBillingClient= null;
private static BillingClient billingClient;
private ApplicationBillingClient() {}
private static boolean isInitialized()
{
return applicationBillingClient != null && billingClient != null;
}
private static void initialize(Context applicationContext)
{
try
{
if(applicationContext != null)
{
applicationBillingClient = new ApplicationBillingClient();
BillingClient.Builder builder= BillingClient.newBuilder(applicationContext);
builder.setListener(new PurchaseActivityListener());
builder.enablePendingPurchases();
billingClient = builder.build();
}
LogUtil.info("Initializing the Billing Client");
}
catch (Exception ex)
{
LogUtil.error("Error while initializing billing client", ex);
}
}
public static ApplicationBillingClient getInstance(Context applicationContext)
{
if(isInitialized() == false)
{
initialize(applicationContext);
}
return applicationBillingClient;
}
public void startConnection()
{
billingClient.startConnection(new StateListener());
}
public boolean isReady()
{
return billingClient.isReady();
}
public void getMonthlySubscription()
{
try
{
if(billingClient.isReady())
{
SkuDetailsParams.Builder skuBuilder = SkuDetailsParams.newBuilder();
skuBuilder.setType(BillingClient.SkuType.SUBS);
skuBuilder.setSkusList(Arrays.asList(new String[]{MONTHLY_BILLING_SUBSCRIPTION_SKU}));
SkuDetailsParams params = skuBuilder.build();
billingClient.querySkuDetailsAsync(params, new SkuDetailsListener());
}
}
catch (Exception ex)
{
LogUtil.error("Error while querying async SKU for Monthly Subscription", ex);
}
}
}
//In your activity
ApplicationBillingClient appBillingClient =
ApplicationBillingClient.getInstance(applicationContext);
if (appBillingClient.isReady() == false)
{
appBillingClient.startConnection();
}
else
{
appBillingClient.getMonthlySubscription();
}
Welcome to stackoverflow !
Two solutions :
Use the the listener specified in the documentation and don't implements it on the class declaration.
Or keep the implements and instead billingClient.querySkuDetailsAsync(params.build(), new SkuDetailsResponseListener() { ....
just use : billingClient.querySkuDetailsAsync(params.build(), this);
I am doing some simple app with two buttons... first button is sending request for Awarded (test) ad and then second shows the ad.
Here is my code:
using GoogleMobileAds.Api;
using UnityEngine;
using System;
public class adManager : MonoBehaviour
{
RewardBasedVideoAd rewardedAd;
public void Start()
{
rewardedAd = RewardBasedVideoAd.Instance;
requestVideo();
}
public void requestVideo()
{
Debug.Log("Video Requested!");
string adID = "My ad ID";
AdRequest request = new AdRequest.Builder()
.AddTestDevice(AdRequest.TestDeviceSimulator) // Simulator.
.AddTestDevice("BD6E7C35B6F8FA70") // My test device.
.Build();
rewardedAd.LoadAd(request, adID);
}
public void showBannerAd()
{
if (rewardedAd.IsLoaded())
{
Debug.Log("AdAvailible!");
rewardedAd.OnAdRewarded += HandleOnAdRewarded;
rewardedAd.Show();
}
else
{
Debug.Log("AdNotAvailible!");
}
}
public void HandleOnAdRewarded(object sender, EventArgs args)
{
Debug.Log("You are rewarded!");
}
public event EventHandler<Reward> OnAdRewarded;
}
Is something wrong with my code or something else?
I tried interstitial and banner ad and they WORKED.
Thanks for help.