Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Leak while using Admob interstitial ads

I have service which will show an activity at particular point of time, after that activity on every 13th time i am showing an admob interstitial ads. My application's RAM usage is increasing by 20MB when the interstitial ad is shown and after that it is not getting garbage collected. On the next 13th time when another interstitial ads is shown there is no increase in the service memory.

My code for showing ads :

public void loadAndShowInterstitialAd() {
        interstitial = new InterstitialAd(getApplicationContext());
        interstitial.setAdUnitId(AD_UNIT_ID);

        final AdRequest adRequest = new AdRequest.Builder()
                .build();

        Handler handler = new Handler(new Handler.Callback() {

            @Override
            public boolean handleMessage(Message msg) {
                interstitial.loadAd(adRequest);
                return true;
            }
        });

        if (handler != null) {
            handler.sendEmptyMessageDelayed(0, 200);
        }

        interstitial.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                displayInterstitial();
            }

        });
    }

    public void displayInterstitial() {
        if (interstitial.isLoaded()) {
            interstitial.show();
        }
    }

I have tried few solutions in the following stack overflow questions, but nothing worked for me.

Android Admob Interstitial Memory leak

Android AdMob causes memory leak?

like image 452
venkat Avatar asked Jul 23 '14 05:07

venkat


2 Answers

I ran to this issue today, finally I have a fix: In your activity, in onDestroy():

  • If there is an AdView, remove it from your layout, set the AdView to null.
  • Set the all the AdListeners to null.

     @Override 
      public void onDestroy(){
          super.onDestroy();
          mMainView.removeView(adView);
          adView = null;
          interstitial.setAdListener(null);
      }
    

    In your case, maybe set AdListener to null is enough.

P/S:

Because leaks happen in so many ways, just in case someone misses this: remember to initialize the Interstitial using Context.getApplicationContext() (like what OP did), not by your Activity - which absolutely creates a leak - because Interstitial now seems to hold a reference to your Activity, and it never leaves, so never let your Activity go ...

Interstitial interstitial = new Interstitial(getApplicationContext())
like image 175
DuDu Avatar answered Oct 02 '22 19:10

DuDu


I have managed to fix this issue by running the Ad activity in another process. I guess due to some reasons, android keep the activities in process memory for more time than it is needed. Hope it will help someone to fix this issue.

like image 36
venkat Avatar answered Oct 02 '22 19:10

venkat