ConnectivityManager getNetworkInfo(int) deprecated
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
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to mobile data
}
} else {
// not connected to the internet
}
Or in a switch case
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
switch (activeNetwork.getType()) {
case ConnectivityManager.TYPE_WIFI:
// connected to wifi
break;
case ConnectivityManager.TYPE_MOBILE:
// connected to mobile data
break;
default:
break;
}
} else {
// not connected to the internet
}
activeNetworkInfo.type is deprecated in API level 28
UPDATE
The connectivityManager.activeNetworkInfo
is also deprecated in API level 29
Now we need to use ConnectivityManager.NetworkCallback API
or ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties
SAMPLE CODE USING
ConnectivityManager#getNetworkCapabilities
private fun isInternetAvailable(context: Context): Boolean {
var result = false
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connectivityManager.activeNetwork ?: return false
val actNw =
connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
result = when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
connectivityManager.run {
connectivityManager.activeNetworkInfo?.run {
result = when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
ConnectivityManager.TYPE_ETHERNET -> true
else -> false
}
}
}
}
return result
}
OLD ANSWER
Yes getType()
is deprecated in API level 28
Now we need to use Callers should switch to checking NetworkCapabilities.hasTransport(int)
Also getAllNetworkInfo()
is deprecated in API level 29
Now we need to use getAllNetworks()
instead of getNetworkInfo(android.net.Network)
.
getNetworkInfo()
- Returns connection status information about a particular Network.
getAllNetworks()
- Returns an array of all Network currently tracked by the framework.
SAMPLE CODE
fun isWiFiConnected(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
val network = connectivityManager.activeNetwork
val capabilities = connectivityManager.getNetworkCapabilities(network)
capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
connectivityManager.activeNetworkInfo.type == ConnectivityManager.TYPE_WIFI
}
}
COMPLETE CODE
@Suppress("DEPRECATION")
fun isInternetAvailable(context: Context): Boolean {
var result = false
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cm?.run {
cm.getNetworkCapabilities(cm.activeNetwork)?.run {
result = when {
hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
}
}
} else {
cm?.run {
cm.activeNetworkInfo?.run {
if (type == ConnectivityManager.TYPE_WIFI) {
result = true
} else if (type == ConnectivityManager.TYPE_MOBILE) {
result = true
}
}
}
}
return result
}
ConnectivityManager.getActiveNetworkInfo() / NetworkInfo is deprecated in API 29. What's an alternative?
The solution is this:
val capability = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
return capability?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?: false
NetworkInfo has been deprecated by API 29
It's deprecated base on Google Document
- getActiveNetworkInfo is deprecated on API 29.
- getAllNetworkInfo is deprecated on API 23.
So, If you want to find the Network Connection status, you can use this code.
kotlin :
private fun isNetworkAvailable(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val nw = connectivityManager.activeNetwork ?: return false
val actNw = connectivityManager.getNetworkCapabilities(nw) ?: return false
return when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
//for other device how are able to connect with Ethernet
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
//for check internet over Bluetooth
actNw.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) -> true
else -> false
}
} else {
return connectivityManager.activeNetworkInfo?.isConnected ?: false
}
}
Java :
private Boolean isNetworkAvailable(Application application) {
ConnectivityManager connectivityManager = (ConnectivityManager) application.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network nw = connectivityManager.getActiveNetwork();
if (nw == null) return false;
NetworkCapabilities actNw = connectivityManager.getNetworkCapabilities(nw);
return actNw != null && (actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) || actNw.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH));
} else {
NetworkInfo nwInfo = connectivityManager.getActiveNetworkInfo();
return nwInfo != null && nwInfo.isConnected();
}
}
you can see all NetworkCapability here.
getActiveNetworkInfo() is deprecated in API 29
I have finally found a code that works on all APIs in case anybody want it
NetworkCapabilities is not deprecated in API 29 but it requires API 21 so I have called it on API 29 only.
However getActiveNetworkInfo() is deprecated only in API 29 and works on all APIs , so we can use it in all apis bellow 29
here's the code
public static boolean isNetworkAvailable(Context context) {
if(context == null) return false;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
return true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)){
return true;
}
}
}
else {
try {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
Log.i("update_statut", "Network is available : true");
return true;
}
} catch (Exception e) {
Log.i("update_statut", "" + e.getMessage());
}
}
}
Log.i("update_statut","Network is available : FALSE ");
return false;
}
NetworkInfo and WifiConfiguration has been deprecated in SDK 22
Deprecated classes were repaced with ConnectivityManager
system service and NetworkCallbacks
: https://developer.android.com/training/monitoring-device-state/connectivity-status-type
Even though the official code example shows how to get NetworkInfo
from ConnectivityManager
there is a highlighted note:
Here is a sample code of how you could get the current network state and also receive updates as time goes by. This is a partially stripped-down solution that I would use in production. If you connect it with RxJava or RxKotlin you could create an observable that will hold network state and that will be updated when overridden method of NetworkCallback get called.
Note regarding Java: public class-level variables are made public just for brevity. I'd instead create a few getters for these to access the value behind these variables.
Feel free to ask questions.
Java
class NetworkReachabilityService {
public NetworkType networkType;
public NetworkState networkState = NetworkState.Unavailable;
private ConnectivityManager connectivityManager;
private ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
updateAvailability(connectivityManager.getNetworkCapabilities(network));
}
@Override
public void onLosing(@NonNull Network network, int maxMsToLive) {
super.onLosing(network, maxMsToLive);
networkState = NetworkState.Losing;
}
@Override
public void onLost(@NonNull Network network) {
super.onLost(network);
networkState = NetworkState.Lost;
}
@Override
public void onUnavailable() {
super.onUnavailable();
networkState = NetworkState.Unavailable;
}
@Override
public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities);
updateAvailability(networkCapabilities);
}
};
public NetworkReachabilityService(Context context) {
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
private void updateAvailability(NetworkCapabilities networkCapabilities) {
if (networkCapabilities == null) {
networkState = NetworkState.Unavailable;
return;
}
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
networkType = NetworkType.CELL;
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
networkType = NetworkType.WiFi;
}
networkState = NetworkState.Available;
}
public void resumeListeningNetworkChanges() {
pauseListeningNetworkChanges();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
connectivityManager.registerNetworkCallback(
new NetworkRequest.Builder().build(),
networkCallback
);
}
}
public void pauseListeningNetworkChanges() {
try {
connectivityManager.unregisterNetworkCallback(networkCallback);
} catch (IllegalArgumentException exception) {
// Usually happens only once if: "NetworkCallback was not registered"
}
}
private enum NetworkState {
Available, Unavailable, Connecting, Losing, Lost
}
private enum NetworkType {
WiFi, CELL, OTHER
}
}
Kotlin
sealed class NetworkState {
data class Available(val type: NetworkType) : NetworkState()
object Unavailable : NetworkState()
object Connecting : NetworkState()
object Losing : NetworkState()
object Lost : NetworkState()
}
sealed class NetworkType {
object WiFi : NetworkType()
object CELL : NetworkType()
object OTHER : NetworkType()
}
class NetworkReachabilityService private constructor(context: Context) {
private val connectivityManager: ConnectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
// There are more functions to override!
override fun onLost(network: Network) {
super.onLost(network)
networkState = NetworkState.Lost
}
override fun onUnavailable() {
super.onUnavailable()
networkState = NetworkState.Unavailable
}
override fun onLosing(network: Network, maxMsToLive: Int) {
super.onLosing(network, maxMsToLive)
networkState = NetworkState.Losing
}
override fun onAvailable(network: Network) {
super.onAvailable(network)
updateAvailability(connectivityManager.getNetworkCapabilities(network))
}
override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
super.onCapabilitiesChanged(network, networkCapabilities)
updateAvailability(networkCapabilities)
}
}
var networkState: NetworkState = NetworkState.Unavailable
private set
private fun updateAvailability(networkCapabilities: NetworkCapabilities?) {
if (networkCapabilities == null) {
networkState = NetworkState.Unavailable
return
}
var networkType: NetworkType = NetworkType.OTHER
if (networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
networkType = NetworkType.CELL
}
if (networkCapabilities.hasTransport(TRANSPORT_WIFI)) {
networkType = NetworkType.WiFi
}
networkState = NetworkState.Available(networkType)
}
fun pauseListeningNetworkChanges() {
try {
connectivityManager.unregisterNetworkCallback(networkCallback)
} catch (e: IllegalArgumentException) {
// Usually happens only once if: "NetworkCallback was not registered"
}
}
fun resumeListeningNetworkChanges() {
pauseListeningNetworkChanges()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(networkCallback)
} else {
connectivityManager.registerNetworkCallback(
NetworkRequest.Builder().build(),
networkCallback
)
}
}
}
To start receiving network state updates call resumeListeningNetworkChanges
and to stop pauseListeningNetworkChanges
respectively.
Update: how to switch between deprecated and new API
Note that even when you use this solution you will anyway have a message that the certain code you use is deprecated! It is completely fine and is not considered as an error as long as you provide an implementation that can switch between new API and old, deprecated API.
Here is an approximate solution. Since the new classes were added in API level 29 we must use Build.VERSION_CODES.Q
because it is an integer with the value 29
.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Use new API here
} else {
// Use old API here
}
Related Topics
Why Does the Google Play Store Say My Android App Is Incompatible with My Own Device
About "_Id" Field in Android SQLite
Android Push Notification (Gcm), Is There Any Daily Limit
Get Current Location of User in Android Without Using Gps or Internet
Manifest Merger Fails for Appcomponentfactory
Android SQLite Db When to Close
How to Prevent a Service from Being Killed by Os
How to Create Edittext with Rounded Corners
Android Webview Not Loading an Https Url
Using the Recyclerview with a Database
Embedding Ads Within Recyclerview
Get Android API Level of Phone Currently Running My Application
Android Studio Emulator Does Not Come with Play Store for API 23
How to Change Progressbar's Progress Indicator Color in Android
Android Getdefaultsharedpreferences