0

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();
    }
}
Justin Petty
  • 283
  • 4
  • 21
  • So where's the 2nd half ( the code you want to place). Do you just want to test it on activity start up. Perhaps just have it in another activity and if you have internet connection start this activity or otherwise show something else. Thats a nice separation of concerns. – Blundell Apr 22 '12 at 19:18
  • You have to check if there is Internet connection before you execute wv.loadurl(); and if there is Internet connection -> continue, if not -> show message – Hesham Saeed Apr 22 '12 at 19:23

3 Answers3

1
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().

Sudhir Mishra
  • 578
  • 2
  • 16
0

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

Community
  • 1
  • 1
0

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>
Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
  • I guess I just want to test it on activity start up.. I found something here [link](http://stackoverflow.com/questions/4238921/android-detect-whether-there-is-an-internet-connection-available#_=_) That might work but, like I said I really don't know where to place it... @Blundell – Justin Petty Apr 22 '12 at 19:29
  • I was thinking something like this... `private boolean checkInternetConnection() { ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE); // ARE WE CONNECTED TO THE NET if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) { return true; } else { Log.v(TAG, "Internet Connection Not Present"); return false; } }` Can I put this in the code above? if so where? – Justin Petty Apr 22 '12 at 20:31
  • Use the helper class I posted. And then whenever you need to check if there is a connection, simply call `if (!NetworkUtils.isOnline( service ) ) { return; }` as needed. i.e., check if the network is available before calling `wv.loadurl()` Obviously, the parameter `service` needs to come from the calling class. – Metro Smurf Apr 22 '12 at 20:44
  • I created a new class call NetworkUtils and added the `if (!NetworkUtils.isOnline( service ) ) { return; }` before `wv.loadurl()` and I got errors on both files. Any Suggestions – Justin Petty Apr 23 '12 at 22:50
  • Not sure without the error. But I'm willing to bet it's because you just copied the code, including the sample parameter for `service`. You need to use the `Service` from the implementing class as the parameter. – Metro Smurf Apr 23 '12 at 23:21