我有3个tab(片段)android应用。我添加了在点击“搜索”片段时打开的插页式广告,但是广告需要花费一些时间才能加载。如何减少广告加载时间?我想在用户点击“搜索”标签(片段)后立即弹出广告。
代码如下:
public class MainActivity extends AppCompatActivity {
public InterstitialAd mInterstitialAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadInterstitial();
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
bottomNav.setOnNavigationItemSelectedListener(navListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_favorites:
selectedFragment = new FavoritesFragment();
break;
case R.id.nav_search:
selectedFragment = new SearchFragment();
displayInterstitial();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
private void loadInterstitial() {
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
AdRequest adRequest1 = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequest1);
mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
private void displayInterstitial() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
}