1

I am using webviews in my app and want to make sure when internet is not available the pop up message displays for no internet connection and also displays an html page in the background saying internet connection required. I have added some code for checking internet connection, but its not working/ showing errors for checkmark(code added based on online research). Any clue how to fix the same? Here's the code below:

 public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);

            requestWindowFeature(Window.FEATURE_NO_TITLE);
           // getWindow().requestFeature(Window.FEATURE_PROGRESS);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

            setContentView(R.layout.main);
            progress = (ProgressBar) findViewById(R.id.ProgressBar);
            progress.setVisibility(View.VISIBLE);
             webview = (WebView)findViewById(R.id.webview);


             if(CheckNetwork.isInternetAvailable(MainActivity.this))
             {
            webview.setInitialScale(1);
            WebSettings webSettings = webview.getSettings();
            webSettings.setJavaScriptEnabled(true);

            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
          //  webview.setWebViewClient(new MyCustomWebViewClient());
            if (Build.VERSION.SDK_INT >= 11){
                webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            }
            webview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
            webview.setScrollbarFadingEnabled(false);
           webview.getSettings().setRenderPriority(RenderPriority.HIGH);
            webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
           // webview.getSettings().setBlockNetworkLoads(true);
            webview.getSettings().setBuiltInZoomControls(true); 
            webview.loadUrl("http://googi.com/money/");
            webview.getSettings().setDomStorageEnabled(true);
            webview.getSettings().setDatabaseEnabled(true);
            webview.getSettings().setAppCacheEnabled(true);
            //http://www.inpixelitrust.fr/demos/restaurant_picker/
            //file:///android_asset/index.html
            webview.getSettings().setSupportZoom(false);
             }else{
                  Toast toast = Toast.makeText(MainActivity.this, "No Internet Connection", Toast.LENGTH_LONG);
                  toast.show(); 
             }
           /* webview.setWebChromeClient(new WebChromeClient()
            {
             public void onProgressChanged(WebView view, int progress)
             {
               // update the progressBar
               MainActivity.this.setProgress(progress * 100);
             }
            });*/
            if (!isTaskRoot()) {
                final Intent intent = getIntent();
                final String intentAction = intent.getAction();
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intentAction != null && intentAction.equals(Intent.ACTION_MAIN)) {
                    finish();
                    return;
                }
            }

            setFullscreen();
        }

        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if(event.getAction() == KeyEvent.ACTION_DOWN){
                switch(keyCode)
                {
                case KeyEvent.KEYCODE_BACK:
                    if(webview.canGoBack() == true){
                        webview.goBack();
                    }else{
                        finish();
                    }
                    return true;
                }

            }
            return super.onKeyDown(keyCode, event);
        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu)
        {
          super.onCreateOptionsMenu(menu);

          menu.add(0, MENU_FULLSCREEN_ON, 0, R.string.menu_fullscreen_on);
          menu.add(0, MENU_FULLSCREEN_OFF, 0, R.string.menu_fullscreen_off);


          return true;
        }
        /**
         * THIS IS FUNCTION FOR CHECKING INTERNET CONNECTION
         * @return TRUE IF INTERNET IS PRESENT ELSE RETURN FALSE
         */
        public boolean checkInternetConnection() {
            ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

            if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) {
                return true;

            } else {
                return false;
            }
        }
        @Override
        public boolean onPrepareOptionsMenu(Menu menu)
        {
          super.onPrepareOptionsMenu(menu);

          menu.findItem(MENU_FULLSCREEN_ON).setVisible(!fullscreen);
          menu.findItem(MENU_FULLSCREEN_OFF).setVisible(fullscreen);

          return true;
        }
        @Override
        public boolean onOptionsItemSelected(MenuItem item)
        {
          switch (item.getItemId()) {

          case MENU_FULLSCREEN_ON:
            fullscreen = true;
            setFullscreen();
            return true;
          case MENU_FULLSCREEN_OFF:
            fullscreen = false;
            setFullscreen();
            return true;

          }
          return false;
        }
        private void setFullscreen()
        {
          if (fullscreen) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().clearFlags(
                WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
          } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
          }

        }
    /*
        @Override
        protected void onNewIntent(Intent intent) {

              setFullscreen();


        }*/
        public class CheckNetwork {


             final String TAG = CheckNetwork.class.getSimpleName();



            public boolean isInternetAvailable(Context context)
            {
                NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

                if (info == null)
                {
                     Log.d(TAG,"no internet connection");
                     return false;
                }
                else
                {
                    if(info.isConnected())
                    {
                        Log.d(TAG," internet connection available...");
                        return true;
                    }
                    else
                    {
                        Log.d(TAG," internet connection");
                        return true;
                    }

                }
            }
                }
        private class MyCustomWebViewClient extends WebViewClient {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progress.setVisibility(View.VISIBLE);
              }
              public void onPageFinished(WebView view, String url) {
                progress.setVisibility(View.GONE);
                synchronized (SPLASH_LOCK) {
                    SPLASH_LOCK.notifyAll();
                }
              }
        }
  • Where exactly are you getting errors? Your code for checking the Internet connectivity works fine for me. – AndroidDev Feb 26 '14 at 15:21
  • I am getting errors on CheckNetwork.isInternetAvailable(MainActivity.this)) , checkmark is not defined and I am not sure what variable to define it as –  Feb 26 '14 at 16:17
  • @JusticeBauer you can check network connection availability. But not internet connection availability. You may have to ping a server and see the response. If Good then you can say the internet connection available – Raghunandan Feb 26 '14 at 16:50

2 Answers2

0
         if(info.isConnected())
                {
                    Log.d(TAG," internet connection available...");
                    return true;
                }
                else
                {
                    Log.d(TAG," internet connection");
                    return true;
                }

this condition seems to be a little weird .... try this function for internet connectvity ... works fine for me in all cases

public boolean checkNetworkState(Context context) {
    ConnectivityManager conMgr = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo infos[] = conMgr.getAllNetworkInfo();
    for (NetworkInfo info : infos) {
        if (info.getState() == State.CONNECTED)
            return true;
    }
    return false;
}
Matej Špilár
  • 2,617
  • 3
  • 15
  • 28
  • it shows me error on info as rename for the if(info.isConnected()) thing. where do i define info and how and where do i place public boolean, inside activity as a separate function? (seems like info is defined there as network info but not globally) –  Feb 26 '14 at 16:16
0

You can have below code.

public class CheckNetwork {


    private static final String TAG = CheckNetwork.class.getSimpleName();



    public static boolean isInternetAvailable(Context context)
    {
        NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
        context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        if (info == null)
        {
             Log.d(TAG,"no internet connection");
             return false;
        }
        else
        {
            if(info.isConnected())
            {
                Log.d(TAG," internet connection available...");
                return true;
            }
            else
            {
                Log.d(TAG," internet connection");
                return true;
            }

        }
    }
}

Then in Activity you can use

 if(CheckNetwork.isInternetAvailable(MainActivity.this))
 {
       // do something
 }

Note: This checks for Network Connectivity. You may be connected to wifi but you may not have internet connection available.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • As you can see I am using the same in my code. However I get error on CheckNetwork as if(CheckNetwork.isInternetAvailable(MainActivity.this)) { is not getting recognized. I am not sure what do I define checknetwork as or how. Please check my code in question. –  Feb 26 '14 at 16:53
  • @JusticeBauer yes you need to define a class with a static method `isInternetAvailable` as shown above in my code. A separate class would do – Raghunandan Feb 26 '14 at 16:54
  • that works as a separate class ,thanks! I was including it as a part of my class as seen from my code hence the error. –  Feb 26 '14 at 17:02
  • can you modify this code to include alert boxes when the internet is not connected? –  Feb 26 '14 at 17:33
  • 1
    @JusticeBauer I have aded the alert box, please check the edited code. –  Feb 26 '14 at 17:44