w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
how to know when device connect to internet (Wi-fi/Mobile data) in Android

Will this also get called when user will turn on the mobile data/3G network.

No, it won't execute so to make it work when you are using mobile data/3G network, you have to add this also

<action android:name="android.net.conn.CONNECTIVITY_CHANGE"
/>

To check whether you are connected with WiFi

ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

Ah, I see in your comment

i just need to check whether device is connected or not thats all.

It is very simple which you can do like below

/**
 * This method check mobile is connected to network.
 * @param context
 * @return true if connected otherwise false.
 */
public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager conMan = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if(conMan.getActiveNetworkInfo() != null &&
conMan.getActiveNetworkInfo().isConnected())
        return true;
    else
        return false;
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.