- public static boolean isNetworkAvailable(Context context) {
- ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
- if (connectivity == null) {
- Log.i("NetWorkState", "Unavailabel");
- return false;
- } else {
- NetworkInfo[] info = connectivity.getAllNetworkInfo();
- if (info != null) {
- for (int i = 0; i < info.length; i++) {
- if (info[i].getState() == NetworkInfo.State.CONNECTED) {
- Log.i("NetWorkState", "Availabel");
- return true;
- }
- }
- }
- }
- return false;
- }
上面這個方法就是判斷網絡是否連接的代碼,返回true表示有網絡,返回false表示無網絡。 在Android網絡應用程序開發中,經常要判斷網絡連接是否可用,因此經常有必要監聽網絡狀態的變化。android的網絡狀態監聽可以用BroadcastReceiver來接收網絡狀態改變的廣播,具體實現如下:
- @Override
- public void onReceive(Context context, Intent intent) {
- Log.e(TAG, "網絡狀態改變");
-
- boolean success = false;
-
- //獲得網絡連接服務
- ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
- // State state = connManager.getActiveNetworkInfo().getState();
- State state = connManager.getNetworkInfo(
- ConnectivityManager.TYPE_WIFI).getState(); // 獲取網絡連接狀態
- if (State.CONNECTED == state) { // 判斷是否正在使用WIFI網絡
- success = true;
- }
-
- state = connManager.getNetworkInfo(
- ConnectivityManager.TYPE_MOBILE).getState(); // 獲取網絡連接狀態
- if (State.CONNECTED != state) { // 判斷是否正在使用GPRS網絡
- success = true;
- }
-
- if (!success) {
- Toast.makeText(LocationMapActivity.this, "您的網絡連接已中斷", Toast.LENGTH_LONG).show();
- }
-
- }
在Activity的onCreate中:
- //注冊網絡監聽
- IntentFilter filter = new IntentFilter();
- filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
- registerReceiver(mNetworkStateReceiver, filter);
- //在Activity中的onDestroy中:'
-
- unregisterReceiver(mNetworkStateReceiver); //取消監聽