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

后端 未结 6 1554
生来不讨喜
生来不讨喜 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:46

    When i update my deprecated code and still want to support backward Api. i use this :

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.WANTED API VERSION){
    //code
    }else{
    //code
    }
    

    In this way each device use the appropriate code for it. Example:

    public class ConnectionDetector {
    
        private Context mContext;
    
        public ConnectionDetector(Context context) {
            this.mContext = context;
        }
        /**
         * Checking for all possible internet providers
         * **/
        public boolean isConnectingToInternet() {
            ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Network[] networks = connectivityManager.getAllNetworks();
                NetworkInfo networkInfo;
                for (Network mNetwork : networks) {
                    networkInfo = connectivityManager.getNetworkInfo(mNetwork);
                    if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                        return true;
                    }
                }
            }else {
                if (connectivityManager != null) {
                    //noinspection deprecation
                    NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
                    if (info != null) {
                        for (NetworkInfo anInfo : info) {
                            if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                                LogUtils.d("Network",
                                        "NETWORKNAME: " + anInfo.getTypeName());
                                return true;
                            }
                        }
                    }
                }
            }
            Toast.makeText(mContext,mContext.getString(R.string.please_connect_to_internet),Toast.LENGTH_SHORT).show();
            return false;
        }
    }
    

提交回复
热议问题