Android網路連接判斷與處理

來源:互聯網
上載者:User

擷取網路資訊需要在AndroidManifest.xml檔案中加入相應的許可權。

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 

1)判斷是否有網路連接

 


 1 public boolean isNetworkConnected(Context context) { 
 2     if (context != null) { 
 3         ConnectivityManager mConnectivityManager = (ConnectivityManager) context 
 4                 .getSystemService(Context.CONNECTIVITY_SERVICE); 
 5         NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 
 6         if (mNetworkInfo != null) { 
 7             return mNetworkInfo.isAvailable(); 
 8         } 
 9     } 
10     return false; 
11 } 

2)判斷WIFI網路是否可用

 


 1 public boolean isWifiConnected(Context context) { 
 2     if (context != null) { 
 3         ConnectivityManager mConnectivityManager = (ConnectivityManager) context 
 4                 .getSystemService(Context.CONNECTIVITY_SERVICE); 
 5         NetworkInfo mWiFiNetworkInfo = mConnectivityManager 
 6                 .getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
 7         if (mWiFiNetworkInfo != null) { 
 8             return mWiFiNetworkInfo.isAvailable(); 
 9         } 
10     } 
11     return false; 
12 } 

 

3)判斷MOBILE網路是否可用

 


 1 public boolean isMobileConnected(Context context) { 
 2     if (context != null) { 
 3         ConnectivityManager mConnectivityManager = (ConnectivityManager) context 
 4                 .getSystemService(Context.CONNECTIVITY_SERVICE); 
 5         NetworkInfo mMobileNetworkInfo = mConnectivityManager 
 6                 .getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 
 7         if (mMobileNetworkInfo != null) { 
 8             return mMobileNetworkInfo.isAvailable(); 
 9         } 
10     } 
11     return false; 
12 } 

 4)擷取當前網路連接的類型資訊

 


 1 public static int getConnectedType(Context context) { 
 2     if (context != null) { 
 3         ConnectivityManager mConnectivityManager = (ConnectivityManager) context 
 4                 .getSystemService(Context.CONNECTIVITY_SERVICE); 
 5         NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); 
 6         if (mNetworkInfo != null && mNetworkInfo.isAvailable()) { 
 7             return mNetworkInfo.getType(); 
 8         } 
 9     } 
10     return -1; 
11 } 

 

在開發android應用時,涉及到要進行網路訪問,時常需要進行網路狀態的檢查,以提供給使用者必要的提醒。一般可以通過ConnectivityManager來完成該工作。

ConnectivityManager有四個主要任務:

1、監聽行動電話通訊狀態(包括GPRS,WIFI, UMTS等)

2、手機狀態發生改變時,發送廣播

3、當一個網路連接失敗時進行故障切換

4、為應用程式提供可以擷取可用網路的高精度和粗糙的狀態

當我們要在程式中監聽網路狀態時,只要一下幾個步驟即可:

1、定義一個Receiver重載其中的onReceive函數,在其中完成所需要的功能,如根據WIFI和GPRS是否斷開來改變空間的外觀

 

 


connectionReceiver = new BroadcastReceiver() {
  
   @Override
   public void onReceive(Context context, Intent intent) {
    ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
     Log.i(TAG, "unconnect");
     // unconnect network
     }else {

    // connect network
     }
   }
  };

 

 

2、在適當的地方註冊Receiver,可以在程式中註冊,在onCreate中調用如下函數即可:

 

IntentFilter intentFilter = new IntentFilter();
  intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
  registerReceiver(connectionReceiver, intentFilter);
 

 

3、在適當時取消註冊Receiver,可以在程式中取消,在onDestroye中調用如下函數即可:

 

if (connectionReceiver != null) {
   unregisterReceiver(connectionReceiver);
  }
 

 

Ps:網上還有很多關於使用TelephonyManager 的方法的,方法如下(但是我試了好幾次都有問題,如每次第一次進入一個Activity時會自動收到網路斷開的訊號,每次網路狀態改變時收到多次回調且狀態不正確。不知道有什麼要注意的地方,求指點!)


final TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 

mTelephonyMgr.listen(new PhoneStateListener(){

@Override

public void onDataConnectionStateChanged(int state) {

switch(state){

case TelephonyManager.DATA_DISCONNECTED://網路斷開

break;

case TelephonyManager.DATA_CONNECTING://網路正在串連

break;

case TelephonyManager.DATA_CONNECTED://網路連接上

break;

}

}

}, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);

 

至於第二種方法,本人並沒有去嘗試過。第一種方式還是比較好用,如果要程式隱藏在背景話,建議開個service,將BroadcastReceiver註冊在service,但不要忘了取消註冊。

在測試中遇到過這樣的狀況,將一個當前串連wifi的路由裝置關閉,但是程式並沒有捕捉到unconnect network,可能是因為手機裝置立刻串連另一個路由裝置了。

 

Android 監控網路狀態
 

 1 public static boolean isNetworkAvailable(Context context) {  
 2         ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);  
 3         if (connectivity == null) {  
 4             Log.i("NetWorkState", "Unavailabel");  
 5             return false;  
 6         } else {  
 7             NetworkInfo[] info = connectivity.getAllNetworkInfo();  
 8             if (info != null) {  
 9                 for (int i = 0; i < info.length; i++) {  
10                     if (info[i].getState() == NetworkInfo.State.CONNECTED) {  
11                         Log.i("NetWorkState", "Availabel");  
12                         return true;  
13                     }  
14                 }  
15             }  
16         }  
17         return false;  
18     } 


上面這個方法就是判斷網路是否串連的代碼,返回true表示有網路,返回false表示無網路。 在Android網路應用程式開發中,經常要判斷網路連接是否可用,因此經常有必要監聽網路狀態的變化。android的網路狀態監聽可以用BroadcastReceiver來接收網路狀態改變的廣 播,具體實現如下:


 1 @Override  
 2 public void onReceive(Context context, Intent intent) {  
 3 Log.e(TAG, "網路狀態改變");  
 4  
 5 boolean success = false;  
 6  
 7 //獲得網路連接服務  
 8 ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);  
 9 // State state = connManager.getActiveNetworkInfo().getState();  
10 State state = connManager.getNetworkInfo(  
11 ConnectivityManager.TYPE_WIFI).getState(); // 擷取網路連接狀態  
12 if (State.CONNECTED == state) { // 判斷是否正在使用WIFI網路  
13 success = true;  
14 }  
15  
16 state = connManager.getNetworkInfo(  
17 ConnectivityManager.TYPE_MOBILE).getState(); // 擷取網路連接狀態  
18 if (State.CONNECTED != state) { // 判斷是否正在使用GPRS網路  
19 success = true;  
20 }  
21  
22 if (!success) {  
23 Toast.makeText(LocationMapActivity.this, "您的網路連接已中止", Toast.LENGTH_LONG).show();  
24 }   
25  
26 } 


在Activity的onCreate中:


//註冊網路監聽  
IntentFilter filter = new IntentFilter();   
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);  
registerReceiver(mNetworkStateReceiver, filter);  
//在Activity中的onDestroy中:'  
 
unregisterReceiver(mNetworkStateReceiver); //取消監聽

很多朋友在android開發中,都會遇到行動電話通訊類型判斷,因為就目前的android平台手機來說:可能會存在4中狀態

      1.無網路(這種狀態可能是因為手機停機,網路沒有開啟,訊號不好等原因)

      2.使用WIFI上網

      3.CMWAP(中國移動代理)

      4.CMNET上網

 這四種狀態,如果沒有網路,肯定是無法請求Internet了,如果是wap就需要為手機添加中國移動代理,關於為手機添加中國移動的代理,請到

http://www.bkjia.com/kf/201111/112100.html 這裡寫有關於添加中國移動代理的例子!

下面是網路判斷的方法:


 1 /**
 2
 3      * @author sky
 4
 5      * Email vipa1888@163.com
 6
 7      * QQ:840950105
 8
 9      * 擷取當前的網路狀態  -1:沒有網路  1:WIFI網路2:wap網路3:net網路
10
11      * @param context
12
13      * @return
14
15      */
16
17     public static int getAPNType(Context context){
18
19         int netType = -1; 
20
21         ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
22
23         NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
24
25         
26
27         if(networkInfo==null){
28
29             return netType;
30
31         }
32
33         int nType = networkInfo.getType();
34
35         if(nType==ConnectivityManager.TYPE_MOBILE){
36
37             Log.e("networkInfo.getExtraInfo()", "networkInfo.getExtraInfo() is "+networkInfo.getExtraInfo());
38
39             if(networkInfo.getExtraInfo().toLowerCase().equals("cmnet")){
40
41                 netType = CMNET;
42
43             }
44
45             else{
46
47                 netType = CMWAP;
48
49             }
50
51         }
52
53         else if(nType==ConnectivityManager.TYPE_WIFI){
54
55             netType = WIFI;
56
57         }
58
59         return netType;
60
61     }

因為擷取的是服務物件,所以這個網路狀態都是時時重新整理的,所以我們只需要得到網路狀態就可以了!

學習在於積累,希望和大家一起分享

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.