0

Consider the following flow:

1) User opens app when there is no internet connection on his device. (So, no banner ad displayed)

2) When using the app, user connects to Internet.

In the above situation, my banner ad does not automatically load on Internet connection establishment. I want the banner ad to be displayed after step 2.

What is the best way to do this?

To further elaborate, in order for the banner ad to be displayed in the app right now, I have to end up restarting the app, this time, with the Internet connectivity present. In other words, if the app is started without an internet connection, banner ads are just not displayed.

user3760100
  • 679
  • 1
  • 9
  • 20
  • I imagine your code need be reworked or implement another function to do the basic control checks as it iterates through your coding. The way you told us sounds a bit messy in the code. – user7568042 Feb 18 '17 at 17:08

1 Answers1

3

You can Internet connectivity state change by using this class(just add this class as it is)

 public class NetworkStateReceiver extends BroadcastReceiver {

protected List<NetworkStateReceiverListener> listeners;
protected Boolean connected;

public NetworkStateReceiver() {
    listeners = new ArrayList<NetworkStateReceiverListener>();
    connected = null;
}

public void onReceive(Context context, Intent intent) {
    if(intent == null || intent.getExtras() == null)
        return;

    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = manager.getActiveNetworkInfo();

    if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
        connected = true;
    } else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
        connected = false;
    }

    notifyStateToAll();
}

private void notifyStateToAll() {
    for(NetworkStateReceiverListener listener : listeners)
        notifyState(listener);
}

private void notifyState(NetworkStateReceiverListener listener) {
    if(connected == null || listener == null)
        return;

    if(connected == true)
        listener.networkAvailable();
    else
        listener.networkUnavailable();
}

public void addListener(NetworkStateReceiverListener l) {
    listeners.add(l);
    notifyState(l);
}

public void removeListener(NetworkStateReceiverListener l) {
    listeners.remove(l);
}

public interface NetworkStateReceiverListener {
    public void networkAvailable();
    public void networkUnavailable();
 }
}

when ever internet connection is changed call for an ad

see the complete usage over here

or you may also check out this question

Community
  • 1
  • 1
Manohar
  • 22,116
  • 9
  • 108
  • 144