0

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.

rupesh
  • 2,865
  • 4
  • 24
  • 50

1 Answers1

1

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;
}
Ajay S
  • 48,003
  • 27
  • 91
  • 111
  • http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html – Piovezan May 24 '14 at 14:28
  • @TGMCians but i heard that this will also notify me when device will be loosing the connection too. http://stackoverflow.com/questions/15698790/broadcast-receiver-for-checking-internet-connection-in-android-app?rq=1 – rupesh May 24 '14 at 14:29
  • @rup35h Yes you are right, there you have to check the condition whether you are connected with internet and through what medium – Ajay S May 24 '14 at 14:31
  • @TGMCians no i just need to check whether device is connected or not thats all. thanks for your great support. – rupesh May 24 '14 at 14:33
  • @rup35h Yes I know, Anyway I'm glad to help you :-) – Ajay S May 24 '14 at 14:49