Java – Android Admob Interstitial memory leak

Android Admob Interstitial memory leak… here is a solution to the problem.

Android Admob Interstitial memory leak

I’m trying to display interstitial ads at the end of certain activities. The problem is that interstitial ads seem to prevent activities from being garbage collected, resulting in out-of-memory exceptions. How do I fix this? Thanks in advance.

public class AdActivity extends FragmentActivity{

//...

protected InterstitialAd interstitial;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

//...

 Create the interstitial.
    interstitial = new InterstitialAd(this);
    interstitial.setAdUnitId(INTERSTITIAL_UNIT_ID);

 Create ad request.
    AdRequest adRequest2 = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .addTestDevice(deviceId)
            .build();

 Begin loading interstitial.
    interstitial.loadAd(adRequest2);
}

@Override
public void onPause() {
    super.onPause();
    displayInterstitial();
}

public void displayInterstitial() {
    if (interstitial.isLoaded() && System.currentTimeMillis() >= lastInterstitial + timeLag * 1000) {
        lastInterstitial = System.currentTimeMillis();
        interstitial.show();
    }
}

I use it this way:

public class ActivityA extends AdActivity{ //...
} 

Solution

Well, I seem to have fixed it with changes

interstitial = new InterstitialAd(this);

to

interstitial = new InterstitialAd(getApplicationContext());

I

don’t fully understand memory management in java/android, but I think it’s because Activity references interstitial and interstitial refers to Activity, so neither is garbage collected. Passing in the application context instead of the activity context prevents this circular dependency and solves the problem. Hope this helps someone :D.

Related Problems and Solutions