Internet connection check in android
Every Service related app we need to check network available in phone or not before call any web service. The source code is given bellow.
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class CheckNetworkConnection {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = CheckNetworkConnection.getConnectivityStatus(context);
String status = null;
if (conn == CheckNetworkConnection.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == CheckNetworkConnection.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == CheckNetworkConnection.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
2) Give permission in manifest file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Comments
Post a Comment