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.            } 

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