Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking internet connection on android

Tags:

I have the following code for checking internet connection wifi/EDGE/GPRS/3G on my application.

the code is

public static boolean checkConn(Context ctx) {     ConnectivityManager conMgr = (ConnectivityManager) ctx             .getSystemService(Context.CONNECTIVITY_SERVICE);     if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED         || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) {         return true;     } else if (conMgr.getNetworkInfo(0).getState()==NetworkInfo.State.DISCONNECTED         || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED){         return false;     }     return false; } 

and I am calling it like below :

if (CheckInternet.checkConn(introPage.this) == true) {     Intent toMainPage = new Intent(introPage.this, mainPage.class);     System.gc();     startActivity(toMainPage); } else if (CheckInternet.checkConn(getApplicationContext()) == false) {     Toast.makeText(getApplicationContext(),         "Sorry, No internet connectivity found", Toast.LENGTH_SHORT)             .show(); } 

But I am having an issue, which is that if I am connected to wifi, and I open the application, it works fine, but if I close application and turn off wifi and re-open application, it doesn't through the error of "no connection" , I need to turn off my device and then turn it on, and same case is if wifi is off, and I open application, it throws error of "no connection", and if I turn it on, still it throws the same error of "no connection", until unless I turn off and on device.

like image 412
Adil Bhatty Avatar asked Nov 03 '10 10:11

Adil Bhatty


People also ask

How do I check my internet connection status?

Select the Start button, then type settings. Select Settings > Network & internet. The status of your network connection will appear at the top.

How do I know if my Android is connected to Wi-Fi?

You should be able to use the ConnectivityManager to get the state of the Wi-Fi adapter. From there you can check if it is connected or even available. AndroidManifest. xml for this to work.


1 Answers

Sometimes the active connection is not first in the list, or is inactive or in an error state. This is how I would do it:

  NetworkInfo i = conMgr.getActiveNetworkInfo();   if (i == null)     return false;   if (!i.isConnected())     return false;   if (!i.isAvailable())     return false;   return true; 

[EDIT 1] Don't forget to add this permission in the application manifest:

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

Does this help you?

Emmanuel

like image 156
Emmanuel Avatar answered Oct 26 '22 06:10

Emmanuel