0

I use Android Studio for converting my website in android application. I try to show dialog box when no internet connection at the opening. It works fine.

But the problem is when the application is still running and suddenly there is no internet connection. Then if i click on a url, the webview display "Web page not available".

Web page not available

MainActivity.java

package com.example.myapp;

import android.graphics.Bitmap;
import android.provider.SyncStateContract;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private WebView mywebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (!DetectConnection.checkInternetConnection(this)) {
            try {
                AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();

                alertDialog.setTitle("Info");
                alertDialog.setMessage("Internet non disponible, Verifiez votre connexion internet et réessayez");
                alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Réessayer", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        startActivity(getIntent());
                    }
                });

                alertDialog.show();
            } catch (Exception e) {

            }
        } else {
            mywebView = (WebView) findViewById(R.id.webview);
            WebSettings webSettings = mywebView.getSettings();
            mywebView.loadUrl("https://myapp.com/");
            mywebView.setWebViewClient(new WebViewClient());
            mywebView.clearCache(true);
            mywebView.clearHistory();
            webSettings.setJavaScriptEnabled(true);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        }
    }

    public class myWebClient extends WebViewClient{
        @Override
        public void onPageStarted (WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
           view.loadUrl(url);
           return true;
        }
    }

    @Override
    public void onBackPressed (){
        if(mywebView.canGoBack()){
            mywebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

DetectConnection.java

package com.example.mycollege;

import android.content.Context;
import android.net.ConnectivityManager;


public class DetectConnection {
    public static boolean checkInternetConnection(MainActivity context) {

        ConnectivityManager con_manager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);

        return (con_manager.getActiveNetworkInfo() != null
                && con_manager.getActiveNetworkInfo().isAvailable()
                && con_manager.getActiveNetworkInfo().isConnected());
    }
}

I want to know how to prevent the click on the when no connection detected replacing the default page "Web page not available" by a dialog box "No internet, check your connexion!". Any ideas?

3 Answers3

0

Your myWebClient class will be like:

// Function to load all URLs in same webview
private class myWebClient extends WebViewClient {
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (!DetectConnection.checkInternetConnection(this)) {
      Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
    } else {
      view.loadUrl(url);
    }     
    return true;
  }
}

Check internet connection inside shouldOverrideUrlLoading.

Thank you.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
  • I change it sir @Pratik Butani , but it display this message **"error: incompatible types: MainActivity.myWebClient cannot be converted to MainActivity "**. The error refer to the **"this"** in **!DetectConnection.checkInternetConnection(this)**. Any ideas? – Mohamed Fall Sep 28 '19 at 13:27
  • Change `this` to `MainActivity.this` – Pratik Butani Sep 28 '19 at 13:29
  • I think you should learn basic concepts which will you help to solve this types of basic problems. – Pratik Butani Sep 28 '19 at 13:29
  • I change **this** to **MainActivity.this** and there no error. But that's not solve the problem. – Mohamed Fall Sep 28 '19 at 13:40
0

First:

In your onClick method of button first check if internet is available or not

add this method in your activity:

  public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager objConnectivityManager;
    try {
        objConnectivityManager = (ConnectivityManager) context.getSystemService(Activity.CONNECTIVITY_SERVICE);
        final boolean IsWifiAvailable = objConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected();

        boolean IsInternetAvailable = false;
        if (objConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null)
            IsInternetAvailable = objConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected();
        if (IsWifiAvailable == true || IsInternetAvailable == true)
            return true;
        else
            return false;
    } catch (Exception e) {
        return false;
    }
}

then call this method in your onClick

boolean isNetworkAvailable = CommonMethods.isNetworkAvailable(this);
        if (isNetworkAvailable){
            // Call the webpage
        }else {
            Toast.makeText(this, "No internet connection", Toast.LENGTH_SHORT).show();
        }

Second: If you are asking about-

  1. you are using app

  2. internet connection is on

  3. BUT there is no response from server[No internet]

then use time out on your webview refer this answer

Makarand
  • 983
  • 9
  • 27
  • So sir @Makarand, what do you call **CommonMethods** ? – Mohamed Fall Oct 03 '19 at 13:32
  • @MohamedFall CommonMethod is a separate class. Created for common methods which project needs. Just copy and paste isNetworkAvailable method in it, then you can call it from anywhere. – Makarand Oct 04 '19 at 04:48
0

Check these two methods while clicking time, If the network is available then proceed the actions

1 - for check connection :

private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }

2 - for check internet :

public boolean internetIsConnected() {
        try {
            String command = "ping -c 1 google.com";
            return (Runtime.getRuntime().exec(command).waitFor() == 0);
        } catch (Exception e) {
            return false;
        }
    }

Add permissions to manifest :

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Stephan John
  • 331
  • 1
  • 2
  • 11