AdMob causes delay in displaying fragments

2019-08-10 11:35发布

问题:

My app is using navigation drawer. Upon clicking on the item in the drawer, it will display a fragment. And I put the AdMob code inside the fragment, as displayed below:

public class MenuIncome extends Fragment {

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.menu_income, container, false);
        AdView mAdView = (AdView) rootView.findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
        mAdView.destroy();

        return rootView;
    }
}

Before I put the AdMob code, my fragment would be displayed instantaneously upon clicking an item on the navigation drawer. But after I put the AdMob code, when I click an item on the drawer, sometimes my app would be liked freezed for up to 1 second, then only the fragment (with the ad) would be displayed.

Why do this happen? I thought AdView have already load its ad asynchronously.

回答1:

The first call of loadAd(..) takes some time for the initialization of admob and this freezes your fragment when loading. You can delay the initialization until your fragment has been loaded and is visible:

             mAdView.postDelayed(
                     new Runnable() {
                         @Override
                         public void run() {
                             mAdView.loadAd(adRequest);
                         }
                     }, 500
             );


回答2:

Have you tried instead to place the AdView in your parent Activity which is hosting the Fragment?

The below setup is how I use ads in my application, which also uses a navigation drawer and multiple fragments. There is no delay at all in loading the fragments. In fact, at times the fragment will load well before the ad, depending on the case.

MainActivity.java:

public class MainActivity extends ActionBarActivity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AdView mAdView = (AdView) findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
    }

}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    ...>

    ...

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id">
    </com.google.android.gms.ads.AdView>

</RelativeLayout>


标签: android admob