3

I have created appliction with webview. if i have do any action and the net is disconnected i want to display one alert. I have tried the following,

added this in oncreate method.

public class AndroidNetTestActivity extends Activity {

    public static WebView webview;
    private Handler mHandler = new Handler();       
    private boolean isConnected = true;
    final String offlineMessageHtml = "Net is disconnected";
    final String timeoutMessageHtml = "Connection timed out";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        webview=(WebView)findViewById(R.id.webview);
        webview.getSettings().setJavaScriptEnabled(true); 
        webview.loadUrl("file:///android_asset/www/index.htm");      
        webview.addJavascriptInterface(new MyJavaScriptInterface(), "Android");
        isConnected=isNetworkAvailable();
        webview.setNetworkAvailable(isConnected);
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                isConnected=isNetworkAvailable();
                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");
                }
            }
        });
        webview.setWebChromeClient(new WebChromeClient());        
    }

    final class MyJavaScriptInterface
    {
        public void ProcessJavaScript(final String scriptname, final String args)
            {             
                mHandler.post(new Runnable()
                    {
                        public void run()
                            {
                                //ToDo
                            }
                    });
            }
    }  

    public boolean isNetworkAvailable() {
           Context context = getApplicationContext();
           ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
           if (connectivity == null) {
              //boitealerte(this.getString(R.string.alert),"getSystemService rend null");
           } else {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null) {
                 for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                       return true;
                    }
                 }
              }
           }
           return false;
        }
}

if i clicking on the log in button, it should show an error message if net is not available.

but it is not working. please check my code and tell me what i did wrong

Padma Kumar
  • 19,893
  • 17
  • 73
  • 130
Ponmalar
  • 6,871
  • 10
  • 50
  • 80

2 Answers2

4

u can check internet connectivity like this

 boolean check=checkConnection();

    if(check==true){
Toast.makeText(
                    this,
                    "Internet is Connected",
                    Toast.LENGTH_LONG).show();
    }

    else{


Toast.makeText(
                    this,
                    "Failed to connect to internet.",
                    Toast.LENGTH_LONG).show();
    }




and here is  a method of checkConnection




  protected boolean checkConnection(){ 
        ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = conMan.getActiveNetworkInfo();

        final boolean connected = networkInfo != null
                && networkInfo.isAvailable()
                && networkInfo.isConnected();

        if ( !connected) {
            Toast.makeText(
                    this,
                    "Failed to connect to internet.",
                    Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }

Just Do like this it is working for me

Aamirkhan
  • 5,746
  • 10
  • 47
  • 74
  • where i have to check the connection that i'm asking not for connection check – Ponmalar Jun 29 '12 at 12:01
  • y method can't call on button click event?just call this method boolean check=checkConnection(); in button click event u will easily be able to check connection – Aamirkhan Jun 29 '12 at 12:09
  • see in webview we can load any url, if we click on the url it may navigate to any urls, at that time if the netconnection is not present then want to error msg – Ponmalar Jun 29 '12 at 12:13
  • ok have a look at this issue http://stackoverflow.com/questions/6392318/detecting-webview-error-and-show-message – Aamirkhan Jun 29 '12 at 12:40
0

ok... i updated your code. just have a look

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;


public class AndroidNetTestActivity extends Activity {

    public static WebView webview;
    private Handler mHandler = new Handler();       
    private boolean isConnected = true;
    final String offlineMessageHtml = "Net is disconnected";
    final String timeoutMessageHtml = "Connection timed out";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.full_screen_image_layout);

        webview=(WebView)findViewById(R.id.webview);
        webview.getSettings().setJavaScriptEnabled(true); 
        webview.loadUrl("http://www.google.com");      
        webview.addJavascriptInterface(new MyJavaScriptInterface(), "Android");
        isConnected=isNetworkAvailable();
        webview.setNetworkAvailable(isConnected);
        webview.setWebViewClient(new WebViewClient() {
            /* (non-Javadoc)
            * @see android.webkit.WebViewClient#onPageStarted(android.webkit.WebView, java.lang.String, android.graphics.Bitmap)
            */
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                System.out.println("page loading started");
                // TODO Auto-generated method stub
                if(!isNetworkAvailable2())
                {
                    showInfoMessageDialog("network not available");
                    System.out.println("network not available");
                    return;
                }
                else System.out.println("network available");

                super.onPageStarted(view, url, favicon);

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                isConnected=isNetworkAvailable2();
                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");
                }
            }
        });
        //webview.setWebChromeClient(new WebChromeClient());        
    }

    final class MyJavaScriptInterface
    {
        public void ProcessJavaScript(final String scriptname, final String args)
            {             
                mHandler.post(new Runnable()
                    {
                        public void run()
                            {
                                //ToDo
                            }
                    });
            }
    }  

    private void showInfoMessageDialog(String meaasge)
    {
        AlertDialog alertDialog = new AlertDialog.Builder(
                AndroidNetTestActivity.this).create();
        alertDialog.setTitle("Connectivity");
        alertDialog.setMessage(meaasge);
        alertDialog.setButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        dialog.cancel();
                    }
                });
        //alertDialog.setIcon(R.drawable.error);
        alertDialog.show();
    }

    private boolean isNetworkAvailable2()
    {
        System.out.println("isNetworkAvailable2 called");
        NetworkInfo info = (NetworkInfo) ((ConnectivityManager) getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();

        if (info == null || !info.isAvailable() || !info.isConnected())
            return false;
        else return true;
    }


    public boolean isNetworkAvailable() {
        Context context = getApplicationContext();
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            //boitealerte(this.getString(R.string.alert),"getSystemService rend null");
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                    }
                }
            }
        }
        return false;
        }
}
sunil
  • 6,444
  • 1
  • 32
  • 44
  • i can get the connection status with my code, but that method is not called while clicking on the button – Ponmalar Jun 29 '12 at 12:00
  • yes you are great that is working and displaying connection error message fine. But the page is showing "Web page is not available" when there is no netconnection. I want to be in the same page. Do you know how to do this? – Ponmalar Jul 02 '12 at 06:02
  • i found the answer that is "webview.stoploading();" added if no netconnection is availble. Thank you so much. – Ponmalar Jul 02 '12 at 06:22