Android设备判断网络连接状态

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

所需权限(AndroidManifest.xml文件中添加):

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  

Java代码(MainActivity.java文件)
    package com.example.androidtest;  
      
    import android.net.ConnectivityManager;  
    import android.net.NetworkInfo;  
    import android.net.NetworkInfo.State;  
    import android.os.Bundle;  
    import android.app.Activity;  
    import android.content.Context;  
    import android.util.Log;  
    import android.view.Menu;  
      
    public class MainActivity extends Activity {  
      
        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main);  
      
            boolean bFlag = isNetworkAvailable(this.getApplicationContext());  
            if (bFlag) {  
                Log.i("Network state - ", "connected");  
            } else {  
                Log.i("Network state - ", "disconnected");  
            }  
      
        }  
      
        /** 
         * 判断网络连接状况 
         *  
         * @param ctx 
         * @return 
         */  
        public boolean isNetworkAvailable(Context ctx) {  
            boolean bFlag = false;  
            if (ctx != null) {  
                ConnectivityManager conMan = (ConnectivityManager) ctx  
                        .getSystemService(Context.CONNECTIVITY_SERVICE);  
                if (conMan != null) {  
                    // wifi Network  
                    NetworkInfo nInfoW = conMan  
                            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);  
                    if (nInfoW != null) {  
                        State wifi = nInfoW.getState();  
                        if (State.CONNECTED == wifi) {  
                            bFlag = true;  
                        }  
                    }  
                    if (!bFlag) {  
                        // mobile Network  
                        NetworkInfo nInfoM = conMan  
                                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);  
                        if (nInfoM != null) {  
                            State mobile = nInfoM.getState();  
                            if (State.CONNECTED == mobile) {  
                                bFlag = true;  
                            }  
                        }  
                    }  
                }  
            }  
            return bFlag;  
        }  
      
        @Override  
        public boolean onCreateOptionsMenu(Menu menu) {  
            // Inflate the menu; this adds items to the action bar if it is present.  
            getMenuInflater().inflate(R.menu.activity_main, menu);  
            return true;  
        }  
      
    }  

isNetworkAvailable方法里先做wifi连接状态判断,如果wifi未连接,再做2g/3g/4g...手机网连接状态判断。