Alex Rivera | Logout

How do you check the internet connection in android?

Asked 2010-02-24T14:42:20.330
59

I want to check the internet connectivity in each activity. If it is lost a message should be displayed.

Can any one guide me how to achieve this?

Edit
Report

2 Answers

10

You can do this, for various types of network status

public void  checkNetworkStatus(){

    final ConnectivityManager connMgr = (ConnectivityManager)
     this.getSystemService(Context.CONNECTIVITY_SERVICE);

     final android.net.NetworkInfo wifi =
     connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

     final android.net.NetworkInfo mobile =
     connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

     if( wifi.isAvailable() ){

     Toast.makeText(this, "Wifi" , Toast.LENGTH_LONG).show();
     }
     else if( mobile.isAvailable() ){

     Toast.makeText(this, "Mobile 3G " , Toast.LENGTH_LONG).show();
     }
     else
     {

         Toast.makeText(this, "No Network " , Toast.LENGTH_LONG).show();
     }

}
answered 2011-10-19T07:10:18.623
1

You are not using ConnectivityManager.getNetworkInfo(0).getState() and ConnectivityManager.getNetworkInfo(1).getState() properly, instead of hardcoding the values (1) and (0) use ConnectivityManager.TYPE_WIFI and ConnectivityManager.TYPE_MOBILE

answered 2013-04-25T13:36:52.400

Your Answer