辭職了,一直忙的也沒時間寫東西,荒廢了還久,上班期間也沒有時間作本身的小東西。終於在投簡歷的時間縫隙裏,能夠作本身的東西,寫本身的博客了。android
廢話很少說,直奔主題吧。 在作一款聯網的項目時,咱們必不可少的須要對網絡狀體進行監聽,以提示用戶在無網絡和網絡恢復。 BroadcastReceiver廣播接收器,實時接收系統發出的廣播,當斷網時和網絡鏈接上時,系統都會發出相應的廣播已通知應用。網絡
boolean success = false; //得到網絡鏈接服務 ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // State state = connManager.getActiveNetworkInfo().getState(); // 獲取WIFI網絡鏈接狀態 NetworkInfo.State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); // 判斷是否正在使用WIFI網絡 if (NetworkInfo.State.CONNECTED == state) { success = true; netWorkState = new NetWorkState(); netWorkState.setNetWorkOK(true); EventBus.getDefault().post(netWorkState); } // 獲取GPRS網絡鏈接狀態 state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState(); // 判斷是否正在使用GPRS網絡 if (NetworkInfo.State.CONNECTED == state) { success = true; netWorkState = new NetWorkState(); netWorkState.setNetWorkOK(true); EventBus.getDefault().post(netWorkState); } if (!success) { ToastUtil.showToast("網絡未鏈接,請檢查網絡鏈接狀態"); }
<receiver android:name=".util.ConnectionChangeReceiver" android:label="NetworkConnection"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/> </intent-filter> </receiver>
private void checkNetWorkState() { mNetworkStateReceiver = new ConnectionChangeReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mNetworkStateReceiver, filter); }
@Override protected void onDestroy() { unregisterReceiver(mNetworkStateReceiver); super.onDestroy(); }