-3

I am working on an android application that have a web-view. The problem comes when I want to check whether Internet is available before displaying default message. I have studied these links Link1and link2. I am confused how to do this. Here is my code

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Web= findViewById(R.id.webview);
    Web.getSettings().setJavaScriptEnabled(true);
    Web.loadUrl("http://yourconsenthomebuilders.com/app/clients");
}
Usman Ali
  • 425
  • 1
  • 9
  • 31

2 Answers2

4

Use this method to check internet connection

public class ConnectionDetector {

    public ConnectionDetector() {
    }

    public Boolean check_internet(Context context) {
        if (context != null) {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork != null) { // connected to the internet
                if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                    return true;
                }
            }
        }
        return false;
    }
}

After this you can create object and check internet connection like this

Fragment

ConnectionDetector connectionDetector = new ConnectionDetector();
connectionDetector.check_internet(getContext())

Activity

ConnectionDetector connectionDetector = new ConnectionDetector();
connectionDetector.check_internet(this)
Siddharth Patel
  • 205
  • 1
  • 13
1

After setContentView() add this logic

ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();

    if (info != null && info.isAvailable() && info.isConnected())
    {
        //network connected
        //show web view logic here
    }else{
        //network not connected
        //show alerts to users
    }
Venky G
  • 180
  • 7