在我的申请中检查互联网连接

时间:2011-11-11 02:59:08

标签: android android-internet

我正在开发基于互联网的应用,所以我需要监控互联网连接。 link

我在创建mainActivity时使用此代码来检查我的互联网连接是否正常。

public boolean isOnline() 
{  
ConnectivityManager cm = (ConnectivityManager) 
getSystemService(Context.CONNECTIVITY_SERVICE);  return 
cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

但我需要通过应用程序完成此监控。 我应该在哪里使用它?需要任何AsyncTask吗?

2 个答案:

答案 0 :(得分:6)

创建BroadcastReceiver以检测连接状态的变化。请参阅Eric的回答here

答案 1 :(得分:4)

使用BroadCast接收器,如下所示:

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
                        boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            // do application-specific task(s) based on the current network state, such 
            // as enabling queuing of HTTP requests when currentNetworkInfo is connected etc.
        }
    };

 private void registerReceivers() {    
       registerReceiver(mConnReceiver, 
           new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
   }