I wrote this code.
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {}
But getAllNetworkInfo() is deprecated. Please help. Thank you.
as the docs say:
getAllNetworkInfo()
This method was deprecated in API level 23. This method does not support multiple connected networks of the same type. Use getAllNetworks()
and getNetworkInfo(android.net.Network)
instead.
I think you can use getActiveNetworkInfo()
:
Here is the code:
ConnectivityManager connectivity = (ConnectivityManager)
MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo nInfo=connectivity.getActiveNetworkInfo();
if (nInfo != null && nInfo.getState()== NetworkInfo.State.CONNECTED) {
//do your thing
}
}
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = connectivity.getAllNetworks();
NetworkInfo networkInfo;
for (Network mNetwork : networks) {
networkInfo = connectivity.getNetworkInfo(mNetwork);
if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
return true;
}
}
} else {
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}}
You can use this class for detecting internet connection. Hope this will help you.
See my answer at: https://stackoverflow.com/a/32771164/4279451
You can use:
getActiveNetworkInfo();
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
}
} else {
// not connected to the internet
}