Checking for an available WiFI connection

In the previous section we added and tested code that allows our app to display Banner Ads. If you followed the instructions correctly chances are that everything worked just fine.
Unfortunately if this is all the code additions you would make to your app, your app users would occasionally run into situation where the app would cause unwanted behaviour like displaying a black bar on the screen without any visual (ad) info or even freeze up if the app is trying to show an Interstitial ad that can't be loaded.

This behaviour could be caused because of our device not being connected to the internet. For example: maybe your device is out of range of a network or WiFi might simply be turned off.

In these section we'll add some code to our app that will help us check if our device is actually connected to the internet when it wants to make an adRequest and to skip the process of trying to download and show the ad when there is no connection.

Let's get started!

To have our app do what I've just described above I want to create a method that will return a boolean value telling me whether there is a WiFi connection. We'll add that method to the AdsController interface, implement it in the AndroidLauncher and add the code there. Add the following line of code to the file:

When you save the file you'll notice an error notification in your AndroidLauncher class. This is because the above method is not yet implemented in that class.

Add the unimplemented method (for example in Eclipse by left-clicking on the light bulb and have your IDE implement it for you) and respectively add the following lines of code to the isWifiConnected() method:

To check the network connection you typically use 2 classes:

  • ConenctivityManager: which gives information about the status of the network connectivity
  • NetworkInfo: which describes the status of a network interface, like for examply the Wifi status.

Now if there is an active network and our device is actually connected to the internet (via WiFi) this method will return true and otherwise return false.
Go back to our game's main class and wrap the showBannerAd call in an if-statement that uses the isWifiConnected() method.
Replace adsController.showBannerAd() with the following line of code:

And that's it!

We'll soon get to Interstitial ads, but before we do that I'd like to take care of one issue. You might have noticed an error popping up in the Desktop project. In the next section we'll take care of that and then continue with Interstitial Ads.