Wednesday, April 27, 2011

Inent-filter to listen for internet/data connectivity status

When designing home screen widgets which tries to talk to cloud, we might be interested in knowing internet connectivity status of device. Suppoese when adding widget, data connectivity might not be available, but your would expect your widget to start collecting data, as and when device is connected to internet.

1- Check for internet connectivity / data connectivity.

private boolean checkInternetConnection() {

ConnectivityManager conMgr = (ConnectivityManager) mContext.getSystemService (mContext.CONNECTIVITY_SERVICE);


if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;


2 - To receive for Internet Connectivity dropped / up, listen for
'ConnectivityManager.CONNECTIVITY_ACTION' action.

IntentFilter filter = new IntentFilter();
mContext.registerReceiver(mNetworkStateIntentReceiver, filter);

3 - Whenever there is a change in connectivity i.e it could be either data connection is connected or disconnected, you will receive this event as broadcast, so in onreceive of the broadcast receiver, please check for internetconnect connection and decide whether internet is up or down.

BroadcastReceiver mNetworkStateIntentReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
ConnectivityManager.CONNECTIVITY_ACTION)) {

NetworkInfo info = intent.getParcelableExtra(
String typeName = info.getTypeName();
String subtypeName = info.getSubtypeName();
System.out.println("Network is up ******** "+typeName+":::"+subtypeName);

if( checkInternetConnection()== true )
"Decide your code logic here...."


1 comment: