Grumpy Cat
Grumpy Cat

Reputation: 1249

How hide and show admob banner adview runtime

Hello guys I am using admob banner to show ads. So I left some space at bottom so admob mob banner load. So if user turn off internet then I want to use that banner space to show content of my activity. while if user turn on his internet again then I shrink my activity content and show admob banner again, So in short I want to grow or shrink layout space.

This is code I try. This code removes banner space if internet is off. but I dont know how to add banner again if user turn on internet.



    public class MainActivity extends AppCompatActivity {

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



            MobileAds.initialize(getApplicationContext(), "ca-app-pub-3940256099942544~3347511713");

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

            mAdView.setAdListener(new AdListener() {
                @Override
                public void onAdFailedToLoad(int i) {
                    //super.onAdFailedToLoad(i);
                    mAdView.setVisibility(View.GONE);
                }

            });
        }

    }

Upvotes: 0

Views: 596

Answers (1)

Adley
Adley

Reputation: 541

First you need to decide when your application will check connection again. Check the lifecycle at https://developer.android.com/reference/android/app/Activity.html

After, lets suppose you want to check everytime the application back to the acitivty that you want to show your adview.

 @Override
    protected void onRestart() {
        if(checkAppConnectionStatus(MainActivity.this)){mAdView.setVisibility(View.VISIBLE);}
        else{ mAdView.setVisibility(View.GONE);}
        super.onRestart();
    }

public static boolean checkAppConnectionStatus(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    }else{
        return false;
    }
}

Check my other answer to know more about how to use like in an utils class appConnectionStatus: Internet Connection

Upvotes: 1

Related Questions