Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Admob Interstitial Memory leak

I'm trying to show interstitials at the end of some Activities. The problem is the interstitials seem to prevent the Activities from being garbage collected causing an out-of-memory exception. How do i resolve 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();
    }
}

And i used it like:

public class ActivityA extends AdActivity{ //...
} 
like image 243
user3785187 Avatar asked Dec 30 '25 16:12

user3785187


1 Answers

Ok i seem to have fixed it by changing

interstitial = new InterstitialAd(this);

to

interstitial = new InterstitialAd(getApplicationContext());

I don't completely understand memory management in java/android but I think whats going on is because the Activity references interstitial and interstitial has a reference to Activity so neither gets garbage-collected. Passing in the application context rather than the Activity context prevents this cycle dependency and solves the problems. Hope this helps someone :D.

like image 59
user3785187 Avatar answered Jan 01 '26 04:01

user3785187



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!