Set a delay of some seconds before reloading an interstitial ad - java

I want to set/add a delay when reloading an ad when it has failed to load. I think it could be done with Looper.getMainLooper() but I don´t know how to do this. You can see I have implemented that if the ad fails to load,it will be reloaded up to 5 times, so I think that adding a delay before reloading the ad could be a good option.
Here is my code:
#Override
protected void onResume() {
super.onResume();
requestNewInterstitial(5);
}
private void requestNewInterstitial(int maxRetry) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
if (maxRetry>0){
/*HERE IS WHERE THE AD IS RELOADED, SO THE DELAY COULD BE SET HERE BEFORE
CALLING THE REQUEST NEW INTERSTITIAL FUNCTION*/
mInterstitialAd = null;
requestNewInterstitial(maxRetry-1);
}
});
}
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});

I tried to do this.
if (maxRetry>0){
//add a delay before retrying
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestNewInterstitial(maxRetry-1);
}
}, 1000);
}
Hope this fixes your problem.

You can use a simple Handler to delay a function like this:
(Kotlin version, but you get the idea)
private fun reloadInterstitialAd() {
if (maxRetry > 0) {
val delayTime = 5000L // 5 seconds.
val looper = mainLooper // Use `Looper.getMainLooper()` if you do not have access to an Activity context.
mInterstitialAd = null
Handler(looper).postDelayed({
maxRetry--
requestNewInterstitial(maxRetry)
}, delayTime)
} else {
Log.d(TAG, "Max reload reached")
}
}
Use this function like reloadInterstitialAd() in the onAdFailedToLoad callback.

You can use this
Thread.sleep(delay_time_in_milliseconds);

Related

Activity is stuck on process dialog and wont go to the next page

So i recently updated my code with the latest admob SDK and dependencies.
it is supposed to show an interstitial ad before going to the next page.
upon running it the StartActivity is stuck on process dialog and wont go to the next page.
here is the code
//Start Here
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(StartActivity.this,StartActivity.this.getString(R.string.main_inter), adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
pd.dismiss();
mInterstitialAd = interstitialAd;
mInterstitialAd.show(StartActivity.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
pd.dismiss();
mInterstitialAd = null;
startActivity(new Intent(StartActivity.this, MainActivity.class));
StartActivity.this.finish();
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
mInterstitialAd = null;
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
mInterstitialAd = null;
}
});
}
});
}
}
You are not dismissing your progress dialog upon onAdDismissedFullScreenContent
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
pd.dismiss()
mInterstitialAd = null;
StartActivity.this.finish();
}
Always remember to handle dialog states, or it can cause window leaks.
Start Activity before finish() is called
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
pd.dismiss()
mInterstitialAd = null;
startActivity(new Intent(StartActivity.this, NextActivity.class));
StartActivity.this.finish();
}
You should dismiss the dialog if the interstitial fails to load or show.
private void openNextPage(ProgressDialog pd){
pd.dismiss();
mInterstitialAd = null;
startActivity(new Intent(StartActivity.this, MainActivity.class));
StartActivity.this.finish();
}
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(StartActivity.this,
StartActivity.this.getString(R.string.main_inter),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
// Don't dismiss dialog here as we are going to show interstitials now
mInterstitialAd = interstitialAd;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
openNextPage(pd);
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
openNextPage(pd);
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
}
});
mInterstitialAd.show(StartActivity.this);
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
openNextPage(pd);
}
});

Is it a good practice to use recursion to reload an ad using Admob if it fails when it is loaded?

I'm using this code to load and show an interstitial ad. It works fine but as you can see if the ad fails to load onAdFailedToLoad, the interstitial ad is recursively requested. Maybe this could be a really bad practice as if the ad is not loaded, the function could be called a huge number of times. But, I have thought that as I'm requesting the ad after the device is connected to the internet, the probability that the ad is loaded should be almost 100%, but I was just wondering if it is a bad practice to do this. The interstitial ad is shown in the 2 activities, as you can see in one of them, it is shown when a button is clicked and after it is clicked there is an intent to move to another activity. The other activity that the interstitial is shown is almost the same, in this second activity it is shown when the game is paused and also when the level is finished. I don´t know if it is important but all the levels are in the same activity, so the interstitial as I have said is only shown in 2 different activities.
#Override
protected void onResume() {
super.onResume();
CallNewInertial();
}
private void CallNewInertial() {
ConnectionDetector cd = new ConnectionDetector(Activityone.this);
if (cd.isConnectingToInternet()) {
requestNewInterstitial();
}
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
requestNewInterstitial();
}
});
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});
fixed code to make it perfect:
#Override
protected void onResume() {
super.onResume();
requestNewInterstitial(5);
}
private void requestNewInterstitial(int maxRetry) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
if (maxRetry>0){
mInterstitialAd = null;
requestNewInterstitial(maxRetry-1);
}
}
});
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});
(using delay),updated code to make it even more perfect:
#Override
protected void onResume() {
super.onResume();
requestNewInterstitial(5);
}
private void requestNewInterstitial(int maxRetry) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
if (maxRetry>0){
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
mInterstitialAd = null;
requestNewInterstitial(maxRetry-1);
}
//delay of 10 seconds
}, 10000);
}
});
}
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});

Do I need to check if the device is connected to the internet to request new interstitial?

I have integrated Admob ads in my app and the I working fine, but I don´t know if I can omit the step of checking if the device is connected to the internet to request an interstitial ad.
This is my code:
//connectiondetec.java:
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
//noinspection deprecation
NetworkInfo[] info = connectivity.getAllNetworkInfo();
for (NetworkInfo anInfo : info)
if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
//Activityone.java:
#Override
protected void onResume() {
super.onResume();
CallNewInertial();
}
private void CallNewInertial() {
ConnectionDetector cd = new ConnectionDetector(Activityone.this);
if (cd.isConnectingToInternet()) {
requestNewInterstitial();
}
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
mInterstitialAd = null;
requestNewInterstitial();
}
});
}
So, could I delete the connection detector class so that now the CallNewInertial is changed to the following code?
private void CallNewInertial() {
requestNewInterstitial();
}
updated code to make it work perfect:
#Override
protected void onResume() {
super.onResume();
requestNewInterstitial(5);
}
private void requestNewInterstitial(int maxRetry) {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(Activityone.this, getString(R.string.interid),
adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
if (maxRetry>0){
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
mInterstitialAd = null;
requestNewInterstitial(maxRetry-1);
}
}, 10000);
}
});
}
}
btnPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd != null) {
mInterstitialAd.show(Activityone.this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
}
});
It's not a common practice to check the internet connection before loading ad. It's also not very common to reload ad when it failed to load, because usually you start loading a new Interstitial anyway when entering next screen / loading next game level.
However, if your app does not have "natural" points when you request a new ad, then it's fine to reload it in onAdFailedToLoad, but limit the attempts to let's say 3 times and optionally add some delay before next attempt.

Google Admob Ad crashes app while loading interstitial ad

my app crashes while loading Google Admob ad. It worked fine for a long time but now I get following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.ads.interstitial.InterstitialAd.setFullScreenContentCallback(com.google.android.gms.ads.FullScreenContentCallback)' on a null object reference
I've changed nothing in code, my app is in Play Store and I have the App on my Galaxy S10 & it worked all the time but now if the Ad has to be loaded I get this error. Can somebody help?
Thanks
Edit: Here's my code
#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-93706071examplenumber/4141725063", adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
Log.i("TAG", "onAdLoaded");
mInterstitialAd = null;
}
});
private void showInterstitial(){
if (callbackActive == false){
setCallback();
}
if (mInterstitialAd != null ) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
}
private void setCallback(){
callbackActive = true;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdDismissedFullScreenContent() {
Log.d("TAG", "The ad was dismissed.");
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
Log.d("TAG", "The ad failed to show.");
}
#Override
public void onAdShowedFullScreenContent() {
mInterstitialAd = null;
Log.d("TAG", "The ad was shown.");
}
});
}
Put setFullScreenContentCallback in onAdLoaded
here is a code snippet (see code below) and check the full code from AdMob official sample on GitHub
public void loadAd() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(
this,
AD_UNIT_ID,
adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
MyActivity.this.interstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
Toast.makeText(MyActivity.this, "onAdLoaded()", Toast.LENGTH_SHORT).show();
interstitialAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Make sure to set your reference to null so you don't
// show it a second time.
MyActivity.this.interstitialAd = null;
Log.d("TAG", "The ad was dismissed.");
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Make sure to set your reference to null so you don't
// show it a second time.
MyActivity.this.interstitialAd = null;
Log.d("TAG", "The ad failed to show.");
}
#Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d("TAG", "The ad was shown.");
}
});
}

Prevent ads from showing in background (Android Studio)

so iv'e set my ad to show after every 5 minutes but the problem is that my app shows Ad even after my app is in background and i am using another app or just like keep the app at background.
I want my app Ads to stop showing after i put the app on background (My Ads don't show after i close app which is fine, but in background it still does)
public class MainActivity extends AppCompatActivity {
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
MobileAds.initialize(this,
"ca-app-pub-3940256099942544~3347551713");
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940255099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
prepareAD();
ScheduledExecutorService ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
ScheduledExecutorService.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "Ad not loaded");
}
prepareAD();
}
});
}
}, 5, 5, TimeUnit.MINUTES);
}else{
Toast.makeText(getApplicationContext(), "No Internet Connection, please try again later...", Toast.LENGTH_LONG).show();
}
}
public void prepareAD() {
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173212");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
}
I will suggest to showing the app in the main thread instead of some background thread. If you pass anything to check if the activity is alive inside the background thread then it has chances of memory leak.
Even if it's in the background then it will check for the activity state and will fail.
getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)
using the life cycle component, do this.
ScheduledExecutorService.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
boolean stateAlive = getLifecycle().getCurrentState().isAtLeast(Lifecycle.State.RESUMED)
if (stateAlive && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "Ad not loaded");
}
prepareAD();
}
});
}
}, 5, 5, TimeUnit.MINUTES);

Categories

Resources