4

Hi I am working with android webview application.I uses my the url succesfully in my app and it works only if internet connection available .But I want to show some messages when there is no internet connection.how can i do this ???please help me since I am new to android development and thanks :)

5 Answers5

16

Call this method before opening the webView if this method returns true that means the internet connection is avialable and you can process to the webview otherwise show some Toast or you can show Dialog if this method returns false.

Edit

Use this code like in your Main Activity as like this

if(isNetworkStatusAvialable (getApplicationContext())) {
    Toast.makeText(getApplicationContext(), "internet avialable", Toast.LENGTH_SHORT).show();
} else {
    Toast.makeText(getApplicationContext(), "internet is not avialable", Toast.LENGTH_SHORT).show();

}

Method

public static boolean isNetworkStatusAvialable (Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) 
    {
        NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
        if(netInfos != null)
        if(netInfos.isConnected()) 
            return true;
    }
    return false;
}
  • 2
    have you given the permission ??? ` ` –  Jan 08 '14 at 08:39
  • Ok I have edited the answer have you checked it now?? And what was the logcat output ?? –  Jan 08 '14 at 09:06
  • 1
    also can u please suggest how to make its UI more beutiful..nw its jst the webview with a splash screen. –  Jan 08 '14 at 10:15
  • What `UI` you want? What are your requirements?? –  Jan 08 '14 at 10:24
  • I just want to make webview more attractive..that means i am looking to make some designs to top and bottom of page while loading the web content. –  Jan 08 '14 at 12:26
  • For that you have to design your view in xml... [Search this](https://www.google.co.in/search?q=android+layout+design+tutorials&oq=android+layout+design+tut&aqs=chrome.1.69i57j0l2.23459j0j7&sourceid=chrome&espv=210&es_sm=93&ie=UTF-8) –  Jan 09 '14 at 04:10
2

Use Below code:

boolean internetCheck;
/*
     * 
     * Method to check Internet connection is available
     */

    public static boolean isInternetAvailable(Context context) {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;
        boolean connectionavailable = false;
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        NetworkInfo informationabtnet = cm.getActiveNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            try {

                if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                    if (ni.isConnected())
                        haveConnectedWifi = true;
                if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                    if (ni.isConnected())
                        haveConnectedMobile = true;
                if (informationabtnet.isAvailable()
                        && informationabtnet.isConnected())
                    connectionavailable = true;

            } catch (Exception e) {
                // TODO: handle exception
                System.out.println("Inside utils catch clause , exception is"
                        + e.toString());
                e.printStackTrace();
                /*
                 * haveConnectedWifi = false; haveConnectedMobile = false;
                 * connectionavailable = false;
                 */
            }
        }
        return haveConnectedWifi || haveConnectedMobile;
    }

It return true if network is available otherwise false In the mantifest add below permissions

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
jyomin
  • 1,957
  • 2
  • 11
  • 27
2

as Brain said on this post
To determine when the device has a network connection, request the permission <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> and then you can check with the following code. First define these variables as class variables.

private Context c;
private boolean isConnected = true;

In your onCreate() method initialize c = this;

Then check for connectivity.

ConnectivityManager connectivityManager = (ConnectivityManager)
    c.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
    NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
    if (ni.getState() != NetworkInfo.State.CONNECTED) {
        // record the fact that there is not connection
        isConnected = false;
    }
}

Then to intercept the WebView requets, you could do something like the following. If you use this, you will probably want to customize the error messages to include some of the information that is available in the onReceivedError method.

final String offlineMessageHtml = "DEFINE THIS";
final String timeoutMessageHtml = "DEFINE THIS";

WebView browser = (WebView) findViewById(R.id.webview);
browser.setNetworkAvailable(isConnected);
browser.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (isConnected) {
            // return false to let the WebView handle the URL
            return false;
        } else {
            // show the proper "not connected" message
            view.loadData(offlineMessageHtml, "text/html", "utf-8");
            // return true if the host application wants to leave the current 
            // WebView and handle the url itself
            return true;
        }
    }
    @Override
    public void onReceivedError (WebView view, int errorCode, 
        String description, String failingUrl) {
        if (errorCode == ERROR_TIMEOUT) {
            view.stopLoading();  // may not be needed
            view.loadData(timeoutMessageHtml, "text/html", "utf-8");
        }
    }
});
Community
  • 1
  • 1
FxRi4
  • 1,096
  • 10
  • 15
0

I did it this way:

Create two java files as below:

NetworkConnectivity.java

package com.connectivity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;

public class NetworkConnectivity {

    private static NetworkConnectivity sharedNetworkConnectivity = null;

    private Activity activity = null;

    private final Handler handler = new Handler();
    private Runnable runnable = null;

    private boolean stopRequested = false;
    private boolean monitorStarted = false;

    private static final int NETWORK_CONNECTION_YES = 1;
    private static final int NETWORK_CONNECTION_NO = -1;
    private static final int NETWORK_CONNECTION_UKNOWN = 0;

    private int connected = NETWORK_CONNECTION_UKNOWN;

    public static final int MONITOR_RATE_WHEN_CONNECTED_MS = 5000;
    public static final int MONITOR_RATE_WHEN_DISCONNECTED_MS = 1000;

    private final List<NetworkMonitorListener> networkMonitorListeners = new ArrayList<NetworkMonitorListener>();

    private NetworkConnectivity() {
    }

    public synchronized static NetworkConnectivity sharedNetworkConnectivity() {
        if (sharedNetworkConnectivity == null) {
            sharedNetworkConnectivity = new NetworkConnectivity();
        }

        return sharedNetworkConnectivity;
    }

    public void configure(Activity activity) {
        this.activity = activity;
    }

    public synchronized boolean startNetworkMonitor() {
        if (this.activity == null) {
            return false;
        }

        if (monitorStarted) {
            return true;
        }

        stopRequested = false;
        monitorStarted = true;

        (new Thread(new Runnable() {
            @Override
            public void run() {
                doCheckConnection();
            }
        })).start();

        return true;
    }

    public synchronized void stopNetworkMonitor() {
        stopRequested = true;
        monitorStarted = false;
    }

    public void addNetworkMonitorListener(NetworkMonitorListener l) {
        this.networkMonitorListeners.add(l);
        this.notifyNetworkMonitorListener(l);
    }

    public boolean removeNetworkMonitorListener(NetworkMonitorListener l) {
        return this.networkMonitorListeners.remove(l);
    }

    private void doCheckConnection() {

        if (stopRequested) {
            runnable = null;
            return;
        }

        final boolean connectedBool = this.isConnected();
        final int _connected = (connectedBool ? NETWORK_CONNECTION_YES
                : NETWORK_CONNECTION_NO);

        if (this.connected != _connected) {

            this.connected = _connected;

            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    notifyNetworkMonitorListeners();
                }
            });
        }

        runnable = new Runnable() {
            @Override
            public void run() {
                doCheckConnection();
            }
        };

        handler.postDelayed(runnable,
                (connectedBool ? MONITOR_RATE_WHEN_CONNECTED_MS
                        : MONITOR_RATE_WHEN_DISCONNECTED_MS));
    }

    public boolean isConnected() {
        try {
            ConnectivityManager cm = (ConnectivityManager) activity
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();

            if (netInfo != null && netInfo.isConnected()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    private void notifyNetworkMonitorListener(NetworkMonitorListener l) {
        try {
            if (this.connected == NETWORK_CONNECTION_YES) {
                l.connectionEstablished();
            } else if (this.connected == NETWORK_CONNECTION_NO) {
                l.connectionLost();
            } else {
                l.connectionCheckInProgress();
            }
        } catch (Exception e) {
        }
    }

    private void notifyNetworkMonitorListeners() {
        for (NetworkMonitorListener l : this.networkMonitorListeners) {
            this.notifyNetworkMonitorListener(l);
        }
    }

}

NetworkMonitorListener.java

package com.connectivity;

public interface NetworkMonitorListener {

    public void connectionEstablished();
    public void connectionLost();
    public void connectionCheckInProgress();
}

And finally, the usage:

NetworkConnectivity.sharedNetworkConnectivity().configure(this);
        NetworkConnectivity.sharedNetworkConnectivity().startNetworkMonitor();
        NetworkConnectivity.sharedNetworkConnectivity()
                .addNetworkMonitorListener(new NetworkMonitorListener() {
                    @Override
                    public void connectionCheckInProgress() {
                        // Okay to make UI updates (check-in-progress is rare)
                    }

                    @Override
                    public void connectionEstablished() {
                        // Okay to make UI updates -- do something now that
                        // connection is avaialble

                        Toast.makeText(getBaseContext(), "Connection established", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void connectionLost() {
                        // Okay to make UI updates -- bummer, no connection

                        Toast.makeText(getBaseContext(), "Connection lost.", Toast.LENGTH_LONG).show();
                    }
                });

With the above usage, you will be able to check for internet connection in runtime. As soon as the internet connection is lost, Toast will appear (as per the above code).

Chintan Soni
  • 24,761
  • 25
  • 106
  • 174
0

If you are use internet connection check internet can be unavalable even if mobile or wi-fi network connected but your internet connection checker returns true https://stackoverflow.com/a/39883250/2212515 use something like that

Community
  • 1
  • 1
user2212515
  • 1,220
  • 1
  • 12
  • 10