Monday, January 31, 2011

To Check internet Connection status/Type in Android




Aim: To Check internet Connection status/Type in Android.
Here is some example code to check the network status .


void chkConnectionStatus()
{
  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();}
}

This snippet requires the following permissions in AndroidManifest.xml file.


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



Please let me know if any.

16 comments:

  1. thanks for sharing, really work for me...^_^

    ReplyDelete
  2. Is it working for android sdk 2.2? could you help to provide permission code for AndroidMainfest.xml. Thanks, your blog really helpful for me.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Need to provide permission for AndroidMainfest.xml
      1. android:name="android.permission.ACCESS_NETWORK_STATE"
      2. android:name="android.permission.ACCESS_WIFI_STATE"

      Delete
  3. this is great.This was really helpful in my project.
    However I wish to know if there is anyway to modify this code so that only selected applications can access the internet through 3G while other applications that are not selected will not be able to use 3G data connection.
    This is the last part of my project and I have been looking for a solution and I have not found any. only this was the closest thing to a solution.
    I hope to get your opinion on my problem.

    ReplyDelete
  4. doesnot work
    i mean nothing display
    any suggestions ! plz

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. @Ola What exactly is not working or displaying?

    ReplyDelete
  7. thanks rama mohan

    ReplyDelete
  8. thanks,
    can u send me source code.

    ReplyDelete

Android Developers Blog

Ram's shared items