1

I want to know how to handle network check by BroadcastReceiver for any application, I know how to check network availability when i am calling my services but suppose my network get disconnected in between transaction I can not handle this situation.

Please provide some tutorial link also where i can learn this.

Thank you.

Puneet
  • 611
  • 6
  • 22

4 Answers4

3

Use this :-

public boolean isNetworkAvailable()
    {
        ConnectivityManager cmanager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
        NetworkInfo netInformation= cmanager .getActiveNetworkInfo(); 
        if (netInformation!= null && netInformation.isAvailable() && netInformation.isConnected()) 
        { 
            return true; 
        }
        return false; 
    }

or check this:-

Checking the Networking Connectivity using BroadcastReceiver in Android

Community
  • 1
  • 1
Monty
  • 3,205
  • 8
  • 36
  • 61
3
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
    Log.w("Network Listener", "Network Type Changed");
}
};

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);        
registerReceiver(networkStateReceiver, filter);

This is a example code.

Puneet
  • 611
  • 6
  • 22
1

u can also add info.isConnectedOrConnecting() option like this..

public static boolean checkConn(Context ctx)
{
    ConnectivityManager conMgr =  (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = conMgr.getActiveNetworkInfo();
    if (info == null || !info.isConnected() || !info.isAvailable()||!info.isConnectedOrConnecting()){
        Toast.makeText(ctx, "Internet is not available", Toast.LENGTH_SHORT).show();
        return false;
    }
     return true;
}
TKumar
  • 818
  • 2
  • 10
  • 35
0

this is code I found here on Stackoverflow (don't remember who wrote it)

public static boolean isConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info == null) {
        return false;
    }
    return info.isConnected();
}

requires internet and network_state permissions

thepoosh
  • 12,497
  • 15
  • 73
  • 132
  • the first answer is also same, this code can just check network availability and as i mentioned in my question i know how to check network availability, my above posted answer works fine for me. – Puneet Dec 24 '12 at 09:07