Android之監測手機網絡狀態的廣播

今天具體說下Android檢測網絡狀態的廣播,咱們在作一些手機應用的時候若是網絡發生改變可能會給用戶形成一些損失,在中國2G,3G網絡都沒有普及的狀況下,基本都是包流量的,因此在作一些視頻應用軟件的時候,若是用戶在使用WIFI的時候若是無線網絡中斷,手機網絡會自動換手機網絡,從而給用戶形成沒必要要的損失。 html

Android手機在對於一些系統廣播,如短信的接收,電話的接收,電池電量太低,網絡狀態改變都會發一個廣播,既然系統會發送一條廣播,那麼就須要一個接收器來處理這個廣播。首先定義一個類繼承NetworkChangeReceiver,重寫onReceive()就好了。而後在OnReceive()這個方法進行相應廣播的處理。 java

網絡狀態切換的廣播類: android

[java]  view plain copy
  1. package com.test;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.net.ConnectivityManager;  
  7. import android.net.NetworkInfo.State;  
  8.   
  9. public class extends BroadcastReceiver {  
  10.   
  11.     @Override  
  12.     public void onReceive(Context context, Intent intent) {  
  13.         State wifiState = null;  
  14.         State mobileState = null;  
  15.         ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
  16.         wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();  
  17.         mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();  
  18.         if (wifiState != null && mobileState != null  
  19.                 && State.CONNECTED != wifiState  
  20.                 && State.CONNECTED == mobileState) {  
  21.             // 手機網絡鏈接成功  
  22.         } else if (wifiState != null && mobileState != null  
  23.                 && State.CONNECTED != wifiState  
  24.                 && State.CONNECTED != mobileState) {  
  25.             // 手機沒有任何的網絡  
  26.         } else if (wifiState != null && State.CONNECTED == wifiState) {  
  27.             // 無線網絡鏈接成功  
  28.         }  
  29.   
  30.     }  
  31.   
  32. }  

在上面這個接收類中OnReceive()方法,你能夠在上面三個網絡狀態(只有手機網絡,只有無線網絡,沒有任何網絡)中進行相應的處理,而後在應用中註冊廣播,註冊廣播有2種方式,一種在androidmanifest.xml中註冊,一種在java代碼中註冊。 網絡

第一種: ide

[html]  view plain copy
  1. <receiver  
  2.     android:name="com.test.NetworkBroadcast"  
  3.     android:label="NetworkConnection" >  
  4.     <intent-filter>  
  5.         <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />  
  6.     </intent-filter>  
  7. </receiver>  


第二種: this

能夠在Activity的onCreate()方法中註冊廣播,在Activity的onDestory()方法中卸載廣播。 spa

[java]  view plain copy
  1. private BroadcastReceiver networkBroadcast=new BroadcastReceiver();  
[java]  view plain copy
  1.         private void registerNetworkReceiver() {  
  2.     IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);  
  3.     this.registerReceiver(networkBroadcast, filter);  
  4. }  
  5.   
  6. private void unRegisterNetworkReceiver() {  
  7.         this.unregisterReceiver(networkBroadcast);  
  8. }  

注意:在接收類中的onReceive()方法中不要處理太多複雜邏輯問題,尤爲耗時的操做。 .net

相關文章
相關標籤/搜索