Android Admob Interstitial Memory leak

南笙酒味 提交于 2019-12-10 20:56:43

问题


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{ //...
} 

回答1:


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.




回答2:


One thing that helped me is to invoke the interstitial.show() on the uithread (since i guess its UI-stuff u have to do it on the ui-thread)




回答3:


Just use application global context:

interstitial = new InterstitialAd(getApplication());

Don't use getApplicationContext(), because returned value will be your current activity.



来源:https://stackoverflow.com/questions/24463440/android-admob-interstitial-memory-leak

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!