tags:

views:

290

answers:

3

How would i know whether my device is connected the web or not? How can i detect connectivity? Any sample code?

+5  A: 

First, you need permission to know whether the device is connected to the web or not. This needs to be in your manifest, in the <manifest> element:

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

Next, you need to get a copy of the ConnectivityManager:

ConnectivityManager cm = (ConnectivityManager) Context.getSystemService(Context.CONNECTIVITY_SERVICE);

From there you need to obtain a NetworkInfo object. For most, this will mean using ConnectivityManager. getActiveNetworkInfo():

NetworkInfo ni = cm.getActiveNetworkInfo();

From there, you just need to use one of NetworkInfo's methods to determine if the device is connected to the internet:

boolean isConnected = ni.isConnected();
Daniel Lew
I get a null pointer exception at this statement:boolean isConnected = ni.isConnected();Why?
Maxood
+1  A: 

ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

if (connec != null && (connec.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) ||(connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED)){ 
    //You are connected, do something online.
}else if (connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED ||  connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED ) {             
    //Not connected.        
    Toast.makeText(getApplicationContext(), "You must be connected to the internet", Toast.LENGTH_LONG).show();
} 

the 1 and 0 in the getNetworkInfo() represent Wifi, and 3g/edge I forget which is which but I know this code checks correctly.

Tim