We previously discussed how to show a custom image using the Google AdMob SDK when an ad request can’t be filled. In the second and final part of this series, we’ll explain how to resume showing AdMob ads if, for example, internet connectivity is restored.

In part 1, we demonstrated how to hide the ad and display a custom image when the first ad request fails. However, the AdMob SDK doesn't make another ad request until it successfully receives an ad, so you must schedule your own refresh. Here’s how to do it:

private final Handler refreshHandler = new Handler();
private final Runnable refreshRunnable = new RefreshRunnable();
private boolean firstAdReceived = false;

@Override
public void onFailedToReceiveAd(Ad ad, ErrorCode code) {
  if (!firstAdReceived) {
    // Keep code from part 1.
    ...
    // Schedule an ad refresh.
    refreshHandler.removeCallbacks(refreshRunnable);
    refreshHandler.postDelayed(
        refreshRunnable, REFRESH_RATE_IN_SECONDS * 1000);
  }
}

private class RefreshRunnable implements Runnable {
  @Override
  public void run() {
    // Load an ad with an ad request.
    adView.loadAd(new AdRequest());
  }
}

A Handler is used to schedule an ad refresh at your desired refresh rate. Before making the postDelayed call, the handler removes any pending posts that may be queued.

With these changes, your application will request an AdMob ad at a regular interval. Once a request is successful, the existing code in onReceiveAd swaps out your custom image with an AdMob ad, and AdMob starts refreshing automatically.

If the user either leaves your app or clicks on your custom ad, you want to pause your refresh handler when your app is not visible to the user. This is an Android best practice that will help preserve battery life. You can override Android’s onStop and onStart callbacks to stop and start ad refreshes, as shown below:

@Override
public void onStop() {
  super.onStop();
  // Remove any pending ad refreshes.
  refreshHandler.removeCallbacks(refreshRunnable);
}

@Override
public void onStart() {
  super.onStart();
  if (!firstAdReceived) {
    // Request a new ad immediately.
    refreshHandler.post(refreshRunnable);
  }
}

This code prevents your app from making ad requests when the user exits your app but immediately requests an ad when the user returns to your app.

That’s it! You’ve successfully integrated a placeholder image into your application to stand in when an ad request can’t be filled. Check out the full example if you have trouble setting up the code.

As always, let us know on the forum if you have any questions about the Google AdMob SDK, or join us during office hours.