rupesh
rupesh

Reputation: 2891

how to know when device connect to internet (Wi-fi/Mobile data) in Android

i want to communicate to the server as soon as device connects to the wi-fi or mobile data. Currently i am using broadcast receiver to notify when devices connects to wifi code is below:

<receiver android:name="com.example.rup35h.WifiReceiver" >
        <intent-filter android:priority="100" >
            <action android:name="android.net.wifi.STATE_CHANGE" />
        </intent-filter>
    </receiver>

My concern is will it work when device will connect to mobile data. will this also get called when user will turn on the mobile data/3G network.

Please let me know if any one will have something related to this. Thanks in advance.

Upvotes: 0

Views: 312

Answers (1)

Ajay S
Ajay S

Reputation: 48602

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;
}

Upvotes: 1

Related Questions