Justin Petty
Justin Petty

Reputation: 265

Check for internet connection

I guess I should start off by saying that I'm completely new to eclipse and java. I'm trying to create a android app using eclipse that launches my web page. I have an example of my code that works just fine, but it's pretty much copied and pasted from examples that I've found online so please excuse my sloppy code. I would like to know how to check if an internet or wifi connection is available.. If there is no connection show an alert (No Internet Connection).. I found some similar questions but, I'm just not sure where to place the code? Can someone please show me?

    package com.mysite.news;

    import com.mysite.news.R;
    import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;

import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;




public class WebActivity extends Activity {

    private WebView wv;

    private String LASTURL = "";

    Menu myMenu = null;

    private static final String PREFS_NAME = "MyPrefs";



    private Boolean imgOn;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate( Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );
        this.getWindow().requestFeature( Window.FEATURE_PROGRESS );
        setContentView( R.layout.web_view );

        wv = ( WebView ) findViewById( R.id.web_view );

        WebSettings webSettings = wv.getSettings();
        webSettings.setSavePassword( true );
        webSettings.setSaveFormData( true );
        webSettings.setJavaScriptEnabled( true );
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportZoom(false);


        SharedPreferences settings = getSharedPreferences( PREFS_NAME, 0 );
        imgOn = settings.getBoolean( "IMGMODE", false );
        webSettings.setLoadsImagesAutomatically( imgOn );

        final Activity activity = this;


        // start ProgressDialog with "Page loading..."
        final ProgressDialog dialog = new ProgressDialog( activity );
        dialog.setMessage( "Page loading..." );
        dialog.setIndeterminate( true );
        dialog.setCancelable( true );
        dialog.show();

        wv.setWebChromeClient( new WebChromeClient() {
            public void onProgressChanged( WebView view, int progress ) {
                // set address bar and progress
//              activity.setTitle( " " + LASTURL );
//              activity.setProgress( progress * 100 );

                if( progress == 100 ) {
                    // stop ProgressDialog after loading
                    dialog.dismiss();

//                  activity.setTitle( " " + LASTURL );
                }
            }
        } );

        wv.setWebViewClient( new WebViewClient() {
            public void onReceivedError( WebView view, int errorCode, String description, String failingUrl ) {
                Toast.makeText( getApplicationContext(), "Error: " + description + " " + failingUrl, Toast.LENGTH_LONG ).show();
            }

            @Override
            public boolean shouldOverrideUrlLoading( WebView view, String url ) {
                if( url.indexOf( "mysite" ) <= 0 ) {
                    // the link is not for a page on my site, so launch another Activity that handles URLs
                    Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( url ) );
                    startActivity( intent );
                    return true;
                }
                return false;
            }

            public void onPageStarted( WebView view, String url, Bitmap favicon ) {
                LASTURL = url;
                view.getSettings().setLoadsImagesAutomatically( true );
                view.getSettings().setBuiltInZoomControls( true );
            }

            public void onPageFinished( WebView view, String url ) {
                view.loadUrl( "javascript:(function() { " +
                                      "hide('sidebar');" +
                                      //"var parent = document.getElementsByClassName('page-navigation')[0];"+
                                      //"var panel = document.getElementsByClassName('panel-tools')[0];"+
                                      //"var div = document.createElement('div');"+
                                      //"div.innerHTML = panel.innerHTML;"+
                                      //"parent.appendChild(div);"+
                                      //"panel.innerHTML = '';"+
                                      //"div.style['margin-left'] = '31px';"+
                                      "var panel = document.getElementById('search');" +
                                      "panel.style['width'] = '55px';" +

                                      //"var imgs=document.getElementsByTagName('IMG');for(var i=0;i<imgs.length;i++){if (imgs[i].height=60) {imgs[i].src='';imgs[i].width=0;} }"+
                                      //"var urls=document.getElementsByTagName('li');for(var i=0;i<urls.length;i++){if (urls[i].style='margin: -14px 0pt 0pt;'){urls[i].style['display'] = 'none';}}"+
                                      //"hideByClass('panel-tools');"+
                                      "function hide(id){if (document.getElementById(id)){document.getElementById(id).style['display'] = 'none';}}" +
                                      //"function hideByClass(c){var e=document.getElementsByClassName(c);for(var i=0;i<e.length;i++){e[i].style['display'] = 'none';}}"+
                                      "})()" );
                if( imgOn ) {
                    view.getSettings().setLoadsImagesAutomatically( true );
                    view.getSettings().setSupportZoom(false);

                }
            }
        } );
        wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        wv.setScrollbarFadingEnabled(false);
        wv.loadUrl( "http://www.mysite.com" );
    }

    @Override
    public boolean onKeyDown( int keyCode, KeyEvent event ) {
        if( ( keyCode == KeyEvent.KEYCODE_BACK ) && wv.canGoBack() ) {
            wv.goBack();
            return true;
        }
        return super.onKeyDown( keyCode, event );
    }

    @Override
    public boolean onCreateOptionsMenu( Menu menu ) {
        super.onCreateOptionsMenu( menu );

        this.myMenu = menu;
        MenuItem item = menu.add( 0, 1, 0, "MAIN PAGE" );
        item.setIcon( R.drawable.home );
        MenuItem item2 = menu.add( 0, 2, 0, "BACK" );
        item2.setIcon( R.drawable.arrowleft );
        MenuItem item3 = menu.add( 0, 3, 0, "Reload" );
        item3.setIcon( R.drawable.s );
        MenuItem item4 = menu.add( 0, 4, 0, "CLEAR CACHE" );
        item4.setIcon( R.drawable.trash );
        MenuItem item5 = menu.add( 0, 5, 0, "Rate" );
        item5.setIcon( R.drawable.vote );
        MenuItem item6 = menu.add( 0, 6, 0, "Exit" );
        item6.setIcon( R.drawable.close );
        return true;
    }

    @Override
    public boolean onOptionsItemSelected( MenuItem item ) {
        switch( item.getItemId() ) {
            case 1:
                wv.loadUrl( "http://mysite.com" );
                break;
            case 2:
                if( wv.canGoBack() ) {
                    wv.goBack();
                }
                break;
            case 3:
                wv.loadUrl( LASTURL );
                break;
            case 4:
                wv.clearCache( true );
                break;
            case 5:
                Intent marketIntent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(
                      "https://play.google.com/store/apps/details?id=" + getPackageName()));
                    startActivity(marketIntent2);
                break;
            case 6:
                finish();
                break;

        }

        return true;
    }

    private void saveSettings( Boolean val ) {
        SharedPreferences settings = getSharedPreferences( PREFS_NAME, 0 );
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean( "IMGMODE", val );
        editor.commit();
    }
}

Upvotes: 0

Views: 2254

Answers (3)

Sudhir Mishra
Sudhir Mishra

Reputation: 597

private boolean checkNetwork() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    } else {
        Toast.makeText(getApplicationContext(),
                "Sorry, Network Unavailable! :(", Toast.LENGTH_LONG).show();
    }
    return false;
}

This snippet helped me out, hope it helps you too. Your usage might look like this.

if (!checkNetwork()) {
    //TODO Network Not Available
} else {
    //TODO Network Available    
}

You might want to put the Toast notification NOT in the function().

Upvotes: 1

Metro Smurf
Metro Smurf

Reputation: 38335

Here's a helper class I use for Network Connectivity:

public class NetworkUtils
{

    public static boolean isOnline( Service service )
    {
        ConnectivityManager cm = (ConnectivityManager) service.getSystemService( Context.CONNECTIVITY_SERVICE );

        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        if ( netInfo != null && netInfo.isConnected() )
        {
            return true;
        }

        return false;
    }

}

And don't forget to add the permissions to AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

Upvotes: 0

user1323150
user1323150

Reputation: 46

check this link How do you check the internet connection in android?

Use the same solution before you load the url. Show an error dialog if internet is not available else load the url

Upvotes: 0

Related Questions