Reputation: 1023
I want to show an Admob ad whenever the user tries for the first time to exit the app, problem is that when the user does that Admob ad might not be completely loaded, so when it loads it could display when the user is already using some other thing, which doesn't offer a good user experience and it's maybe even against the conditions google sets for using Admob ads.
I've tried to do the previous with the following code, hoping that in the free times the app may have between checking that it's loading and letting the app to sleep for a little time it would keep on loading the add.
while (interstitialAds.isLoading())
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
But it just keeps on using the whole CPU for the while loop.
Any idea on how to be able to code that if the ad is still loading it must wait until it's loaded?
Upvotes: 0
Views: 3456
Reputation: 1401
Interstitial ads must not be shown on app exit according to Admob policies, avoid it. https://support.google.com/admob/answer/6201362?hl=en
Upvotes: 3
Reputation: 6033
Load your ad in the onCreate method as documented in the docs:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
// ...
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private InterstitialAd mInterstitialAd;;;
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
You could also use an AdListener:
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
Log.i("Ads", "onAdLoaded");
}
});
Upvotes: 0