Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check network connection android

In my application, which I test on emulator, I use the following code to check the network connection (WIFI):

    public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

This method returns always true, even if I disable the wireless connection of my computer... Is this caused by the emulator or is it something else?

If this is not the right way to check network connection, how can I do that?

like image 437
amp Avatar asked Apr 04 '12 11:04

amp


Video Answer


2 Answers

It's better to (1) pass in the context so that the every activity can invoke this functions, and (2) Make this function static:

 public boolean isNetworkOnline() {
    boolean status=false;
    try{
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getNetworkInfo(0);
        if (netInfo != null && netInfo.getState()==NetworkInfo.State.CONNECTED) {
            status= true;
        }else {
            netInfo = cm.getNetworkInfo(1);
            if(netInfo!=null && netInfo.getState()==NetworkInfo.State.CONNECTED)
                status= true;
        }
    }catch(Exception e){
        e.printStackTrace();  
        return false;
    }
    return status;

    }  
like image 168
Nishant Avatar answered Sep 18 '22 12:09

Nishant


To get getActiveNetworkInfo() to work you need to add the following to the manifest.

1. uses-permission android:name="android.permission.INTERNET"
 2. uses-permission
    android:name="android.permission.ACCESS_NETWORK_STATE"

better to use netInfo.isConnected() rather than netInfo.isConnectedOrConnecting

and also try this

Context.getSystemService(Context.CONNECTIVITY_SERVICE).getNetworkInfo(ConnectivityManager.TYPE_MOBILE)

or

Context.getSystemService(Context.CONNECTIVITY_SERVICE).requestRouteToHost(TYPE_WIFI, int hostAddress)
like image 23
SuN Avatar answered Sep 20 '22 12:09

SuN