Android getAllNetworkInfo() is Deprecated. What is the alternative?

后端 未结 6 1509
生来不讨喜
生来不讨喜 2021-01-31 09:33

I want to use the ConnectivityManager which provides the getAllNetworkInfo() method for checking the availability of network in Android. This method wa

6条回答
  •  花落未央
    2021-01-31 09:37

    I've made utils that may help you to check:

    • If network is connected.
    • If WiFi is connected.
    • If mobile data is connected.

    it uses old or new API depending on running platform :

    import android.annotation.TargetApi;
    import android.content.Context;
    import android.net.ConnectivityManager;
    import android.net.Network;
    import android.net.NetworkInfo;
    import android.os.Build;
    import android.support.annotation.NonNull;
    
    public class NetworkUtils {
    
        public static boolean isConnected(@NonNull Context context) {
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            return (networkInfo != null && networkInfo.isConnected());
        }
    
        public static boolean isWifiConnected(@NonNull Context context) {
            return isConnected(context, ConnectivityManager.TYPE_WIFI);
        }
    
        public static boolean isMobileConnected(@NonNull Context context) {
            return isConnected(context, ConnectivityManager.TYPE_MOBILE);
        }
    
        private static boolean isConnected(@NonNull Context context, int type) {
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                NetworkInfo networkInfo = connMgr.getNetworkInfo(type);
                return networkInfo != null && networkInfo.isConnected();
            } else {
                return isConnected(connMgr, type);
            }
        }
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        private static boolean isConnected(@NonNull ConnectivityManager connMgr, int type) {
            Network[] networks = connMgr.getAllNetworks();
            NetworkInfo networkInfo;
            for (Network mNetwork : networks) {
                networkInfo = connMgr.getNetworkInfo(mNetwork);
                if (networkInfo != null && networkInfo.getType() == type && networkInfo.isConnected()) {
                    return true;
                }
            }
            return false;
        }
    
    }
    

    Update:
    More information about @TargetApi and @RequiresApi: https://stackoverflow.com/a/40008157/421467 https://developer.android.com/reference/kotlin/androidx/annotation/RequiresApi

提交回复
热议问题