Search This Blog

Thursday, March 8, 2012

Checking the network Availability

You can check the network is available or not in your android device.

public boolean isNetworkAvailable() 
{
   ConnectivityManager cm=                        
                 (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo networkInfo = cm.getActiveNetworkInfo(); 
   // if no network is available networkInfo will be null, otherwise check if we are connected 

   if (networkInfo != null && networkInfo.isConnected()) 
   { 
             return true; 
    }
 return false; 
}


OR





package com.network.availibility;


import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.TextView;


public class NetworkAvailibilityActivity extends Activity {
    /** Called when the activity is first created. */
private boolean isconnected;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        
        TextView tx = (TextView)findViewById(R.id.ischeking);
        
        
        isconnected = isConnected(NetworkAvailibilityActivity.this);
        
        if(isconnected == true){
        tx.setText("You are connected to the internet");
        }
        else{
        tx.setText("Please connect your phone to internet");
        }
        
        
    }
    public static boolean isConnected(Context context) {
    
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);


    NetworkInfo wifiNetwork =
    cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    
    NetworkInfo mobileNetwork =
    cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (wifiNetwork.isAvailable()) {
    return wifiNetwork.isConnectedOrConnecting();
    }


    
    else if (mobileNetwork.isAvailable()) {
    return mobileNetwork.isConnectedOrConnecting();
    }


    
    else if(activeNetwork.isAvailable()) {
    return activeNetwork.isConnectedOrConnecting();
    }
    else{
    return false;
    }
 }
}

You just need to give the permission of the INTERNET and  ACCESS_NETWORK_STATE.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.