Android中檢查網絡連接狀態的變化,無網絡時跳轉到設置界面

轉自:http://blog.csdn.net/jdsjlzx/article/details/7560010

AndroidManifest.xml中加一個聲明

[html] view plaincopy

1.     <receiver android:name="NetCheckReceiver">  

2.         <intent-filter>  

3.                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />  

4.         </intent-filter>  

5.     </receiver>  

NetCheckReceive.java文件如下

[java] view plaincopy

1.     import android.content.BroadcastReceiver;  

2.     import android.content.Context;  

3.     import android.content.Intent;  

4.     import android.net.ConnectivityManager;  

5.       

6.     public class NetCheckReceiver extends BroadcastReceiver{  

7.       

8.         //android 中網絡變化時所發的Intent的名字  

9.         private static final String netACTION="android.net.conn.CONNECTIVITY_CHANGE";  

10.      @Override  

11.      public void onReceive(Context context, Intent intent) {  

12.    

13.          if(intent.getAction().equals(netACTION)){  

14.      //IntentConnectivityManager.EXTRA_NO_CONNECTIVITY這個關鍵字表示着當前是否連接上了網絡  

15.      //true 代表網絡斷開   false 代表網絡沒有斷開  

16.              if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)){  

17.                  aActivity.stopFlag = true;  

18.              }else{  

19.                  aActivity.stopFlag = false;  

20.              }  

21.          }  

22.      }  

23.  }  

aActivity.stopFlag 是一個static布爾值 可以出現在程序需要判斷網絡情況的地方。

順便加一個不需要broadcastReceiver就可以查看網絡的例子。

這個方法可以放在需要檢查網絡通訊情況的地方。返回值爲true代表網絡暢通。

[java] view plaincopy

1.     private boolean checkNetwork() {  

2.             ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);  

3.             NetworkInfo net = conn.getActiveNetworkInfo();  

4.             if (net != null && net.isConnected()) {  

5.                 return true;  

6.             }  

7.             return false;  

8.         }  

 

以下的這個判斷可以使用戶在失去網絡鏈接的情況下,自動跳轉到設置無線網界面。

 

[java] view plaincopy

1.     if (!checkNetwork()) {  

2.                Toast.makeText(this, R.string.lose_network, Toast.LENGTH_LONG).show();  

3.                Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");  

4.                startActivity(intent);  

5.                return;  

6.            } 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章