0

I am developing an application in which message to be sent as soon as an internet connection is available. Connectivity Manager does provide the status of WiFi/Mobile connectivity only. I can ping any site to check internet connectivity. This means I need to continuously poll. Is there any way by which activity can be notified of the restoration of connectivity due to bad network coverage or bad Network connectivity (WiFi back-haul)?

Thanks in advance for your help.

bugfreerammohan
  • 1,471
  • 1
  • 7
  • 22
Sukesh Saxena
  • 201
  • 2
  • 18
  • check out this link this uses a broadcast receiver and not some background loop checking if internet is available. I think the play store app works the same way. https://stackoverflow.com/questions/15698790/broadcast-receiver-for-checking-internet-connection-in-android-app – Pemba Tamang Dec 06 '18 at 04:39

2 Answers2

0

I believe that this is something that you will find helpful How to check internet access on Android? InetAddress never times out. The best solution describes a couple of options.

Hopefully this helps!

AvidRP
  • 373
  • 2
  • 11
0

I once needed such a solution. So I crafted a class that does the trick with the codes from this site. Let's call this class iChessNetwork:

import android.content.*;
import android.net.*;
import android.net.wifi.*;
import android.os.*;
import android.widget.*;
import java.io.*;
import java.net.*;

public class iChessNetwork {

private Context mContext;
protected Watcher mWatcher;

public iChessNetwork(Context context, Watcher watcher) {
    mContext = context;
    mWatcher = watcher;
    init();
} 
public interface Watcher {
    public void Online();
}

private void init() {
    registerOnlineChecker();
}
public void stop() {
    unregisterOnlineChecker();
}

/*=========:INTERNET CHECK START ========*/
private BroadcastReceiver mOnlineChecker = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (isConnected()) {
            //Toast.makeText(mContext,"You are connected!",Toast.LENGTH_LONG).show();
            OnlineTester mOnlineTester = new OnlineTester();
            mOnlineTester.execute();
        }
    }
};

private void registerOnlineChecker() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    mContext.registerReceiver(mOnlineChecker, filter);
}

private void unregisterOnlineChecker() {
    mContext.unregisterReceiver(mOnlineChecker);
}

private boolean isConnected() {
    boolean isMobile = false, isWifi = false;

    ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] infoAvailableNetworks = cm.getAllNetworkInfo();

    if (infoAvailableNetworks != null) {
        for (NetworkInfo network : infoAvailableNetworks) {

            if (network.getType() == ConnectivityManager.TYPE_WIFI) {
                if (network.isConnected() && network.isAvailable())
                    isWifi = true;
            }
            if (network.getType() == ConnectivityManager.TYPE_MOBILE) {
                if (network.isConnected() && network.isAvailable())
                    isMobile = true;
            }
        }
    }

    return isMobile || isWifi;
}


/*========= INTERNET CHECK END ==========*/


private class OnlineTester extends AsyncTask<Void,Void,Boolean> {

    public OnlineTester() {

    }

    @Override
    protected Boolean doInBackground(Void[] p1) {
        boolean online = false;
        try {
            HttpURLConnection urlConnection = (HttpURLConnection)
                (new URL("http://clients3.google.com/generate_204")
                .openConnection());
            urlConnection.setRequestProperty("User-Agent", "Android");
            urlConnection.setRequestProperty("Connection", "close");
            urlConnection.setConnectTimeout(1500);
            urlConnection.connect();
            if (urlConnection.getResponseCode() == 204 &&
                urlConnection.getContentLength() == 0) {
                //Log.d("Network Checker", "Successfully connected to internet");
                online = true;
            }
        } catch (IOException e) {
            online = false;
        }
        return online;
    }

    @Override
    protected void onPostExecute(Boolean online) {
        // TODO: Implement this method
        super.onPostExecute(online);
        if(online) {
            if(mWatcher != null) {
                mWatcher.Online();
            }
        }
    }
 }
};

As you may notice, there is an interface in the class. Basically, I want to know if an "active" internet connection is available or not from one of my Activity classes. So I implemented above interface in that Activity as follows:

public class YourActivity extends Activity implements iChessNetwork.Watcher {

private iChessNetwork mNetwork;

@Override
public void Online() {
    // It's online now - do your connection

}

By now, we're ready to go. So I let it run from somewhere (usually, in onCreate(), an android app start point) in the Activity class:

mNetwork = new iChessNetwork(this, this);

And I start tracking "active" internet connection from this point and stop tracking when I don't want it (usually, in onBackPressed() and onDestroy() methods of my Activity like this:

    if(mNetwork != null) {
        mNetwork.stop();
    }

Hope this helps you and someone else.

Shahood ul Hassan
  • 745
  • 2
  • 9
  • 19
  • @starrydevelopor My apologies for responding late since get stuck in some urgent stuff. The code that you share will check internet connectivity once. Am I correct in my understanding? However what I am looking for is that it should check internet connectivity something like event listener and as soon as connectivity is restored it will send unsent message. – Sukesh Saxena Dec 12 '18 at 05:42
  • It works like an event listener like you said. Why not see it in action by building a quick demo app? – starrydeveloper Dec 12 '18 at 15:52