Android 監聽網絡的變化

Android中網絡狀況時有變化,好比從有網到沒網,從wifi到gprs,gprs又從cmwap到cmnet...等等!
若是你的程序有些功能是須要網絡支持的,有時候就須要監聽到網絡的變化狀況進行相應的處理。
好比說下載一個文件,若是忽然斷網了,怎麼處理?網絡又恢復了,如何監聽到並重連?
 
當網絡變化的時候系統會發出義個廣播broadcast,只要在程序中註冊一個廣播接收器BroadcastReceiver,並在IntentFilter中添加相應的過濾,這樣一旦網絡有變化,程序就能監聽到
public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE" ;
2   private void registerDateTransReceiver() {
3  Log.i(TAG, "register receiver " + CONNECTIVITY_CHANGE_ACTION);
4  IntentFilter filter = new IntentFilter();
5  filter.addAction(CONNECTIVITY_CHANGE_ACTION);
6  filter.setPriority(1000);
7  registerReceiver(new MyReceiver(), filter);
8  }
1   public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
2   private void registerDateTransReceiver() {
3  Log.i(TAG, "register receiver " + CONNECTIVITY_CHANGE_ACTION);
4  IntentFilter filter = new IntentFilter();
5  filter.addAction(CONNECTIVITY_CHANGE_ACTION);
6  filter.setPriority(1000);
7  registerReceiver(new MyReceiver(), filter);
8  }

在MyReceiver中:
 
1 @Override
2 public void onReceive(Context context, Intent intent) {
3     String action = intent.getAction();
4     Log.i(TAG, "PfDataTransReceiver receive action " + action);
5     if(TextUtils.equals(action, CONNECTIVITY_CHANGE_ACTION)){//網絡變化的時候會發送通知
6         Log.i(TAG, "網絡變化了");
7         return;
8     }
9 }
1 @Override
2 public void onReceive(Context context, Intent intent) {
3     String action = intent.getAction();
4     Log.i(TAG, "PfDataTransReceiver receive action " + action);
5     if(TextUtils.equals(action, CONNECTIVITY_CHANGE_ACTION)){//網絡變化的時候會發送通知
6         Log.i(TAG, "網絡變化了");
7         return;
8     }
9 }

當網絡變化時,從有網到沒網也會發廣播,就舉的例子來講,若是下載時斷網了,接收到廣播的時候要判斷當前網絡是可用仍是不可用狀態,若是可用進行什麼操做;不可用進行什麼操做:
 
01 public static NetworkInfo getActiveNetwork(Context context){
02     if (context == null)
03         return null;
04     ConnectivityManager mConnMgr = (ConnectivityManager) context
05             .getSystemService(Context.CONNECTIVITY_SERVICE);
06     if (mConnMgr == null)
07         return null;
08     NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo(); // 獲取活動網絡鏈接信息
09     return aActiveInfo;
10 }
public static NetworkInfo getActiveNetwork(Context context){
02     if (context == null)
03         return null;
04     ConnectivityManager mConnMgr = (ConnectivityManager) context
05             .getSystemService(Context.CONNECTIVITY_SERVICE);
06     if (mConnMgr == null)
07         return null;
08     NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo(); // 獲取活動網絡鏈接信息
09     return aActiveInfo;
10 }
這個方法返回的aActiveInfo能夠判斷網絡的有無,若是返回的是null,這時候是斷網了,若是返回對象不爲空,則是連上了網。在返回的NetworkInfo對象裏,能夠有對象的方法獲取更多的當前網絡信息,好比是wifi仍是cmwap等,就很少說了。
相關文章
相關標籤/搜索