I want to use the Connectivity manager which provide the method getAllNetworkInfo() for checking the availability of network in Android. This method was deprecated in API level 23. And Developer doc is suggesting to use getAllNetworks() instead. I tried but counldn't get the exact functionalities I was getting out of my old code. Please someone could guide me how to use getAllNetworks() method. Below is the code which I'm using:
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
@SuppressWarnings("deprecation")
NetworkInfo[] info = connectivity.getAllNetworkInfo();
//use getAllNetworks() instead
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
Try this one .It is the simplest way.
I've made utils that may help you to check:
it uses old or new API depending on running platform :
Update:
More information about
@TargetApi
and@RequiresApi
: https://stackoverflow.com/a/40008157/421467 https://developer.android.com/reference/kotlin/androidx/annotation/RequiresApiFor someone needs Kotlin version, (Below is same code with Maor Hadad's)
This code is an extension method for Context.
Write down this code at any kotlin file(.kt), then you can use this method in any class which implements Context(such as Activity).
Try following code:
When i update my deprecated code and still want to support backward Api. i use this :
In this way each device use the appropriate code for it. Example:
Try this