【Android】利用廣播BroadCast監聽網絡的變化

[java] view plain copy
  1. package com.app.test02;  
  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. import android.widget.Toast;  
  9. /** 
  10.  * Android  利用廣播BroadCast監聽網絡的變化 
  11.  * @author 402-9 
  12.  * 
  13.  */  
  14. public class BroadCastDemo extends BroadcastReceiver{  
  15.     State wifiState = null;  
  16.     State mobileState = null;  
  17.     public static final String ACTION = "android.net.conn.CONNECTIVITY_CHANGE";  
  18.     @Override  
  19.     public void onReceive(Context context, Intent intent) {  
  20.         // TODO Auto-generated method stub  
  21.         if (ACTION.equals(intent.getAction())) {  
  22.             //獲取手機的連接服務管理器,這裏是連接管理器類  
  23.             ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);    
  24.             wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();      
  25.             mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();  
  26.       
  27.             Intent intent2 = new Intent(context , BroadCastActivity2_SMS.class);  
  28.             if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED == mobileState) {  
  29.                 context.startService(intent2);  
  30.                 Toast.makeText(context, "手機網絡連接成功!", Toast.LENGTH_SHORT).show();  
  31.             } else if (wifiState != null && mobileState != null && State.CONNECTED == wifiState && State.CONNECTED != mobileState) {  
  32.                 context.startService(intent2);  
  33.                 Toast.makeText(context, "無線網絡連接成功!", Toast.LENGTH_SHORT).show();  
  34.             } else if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED != mobileState) {  
  35.                 context.startService(intent2);  
  36.                 Toast.makeText(context, "手機沒有任何網絡...", Toast.LENGTH_SHORT).show();  
  37.             }  
  38.         }  
  39.     }  
  40.   
  41. }  


增加權限

[html] view plain copy
  1. <receiver android:name=".BroadCastDemo">  
  2.     <intent-filter >  
  3.         <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>  
  4.     </intent-filter>  
  5. </receiver>  

[html] view plain copy
  1. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>  

效果圖



發佈了70 篇原創文章 · 獲贊 10 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章