Search code examples
androidandroid-layoutnetwork-connection

How do I show a custom dialog when there is no Internet connection?


I want to show a custom dialog in a webview app when there is no connection to the Internet. How can I check the Internet connection and after that call a dialog?


Solution

  • You can use ConnectivityManager to check if there is an internet connection, and you can show a Toast AlertDialog message to the user.

    See also: AlertDialog.Builder

    Edit: Here is an example of how to do this with a Toast message:

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null) {
        if (!info.isConnected()) {
            Toast.makeText(this, "Please check your wireless connection and try again.", Toast.LENGTH_SHORT).show();
        }
    }
    else {
        Toast.makeText(this, "Please check your wireless connection and try again.", Toast.LENGTH_SHORT).show();
    }