2012-04-27 16 views
12

我正在做一个应用程序,它通过应用程序使用Internet连接。如果在使用应用程序时互联网连接丢失,应用程序将强行关闭。为了避免这种情况,如果互联网不可用,我想显示一条警报消息。我怎样才能做到这一点。 在登录时,我正在使用下面的代码检查连接。但是我怎么能在后台完成整个应用程序。如何在整个应用程序中定期检查Internet连接?

private boolean haveInternet(){ 
     NetworkInfo info = ((ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo(); 
     if (info==null || !info.isConnected()) { 
       return false; 
     } 
     if (info.isRoaming()) { 
       // here is the roaming option you can change it if you want to disable internet while roaming, just return false 
       return true; 
     } 
     return true; 
} 

谢谢。

+0

@parag你能告诉我一个例子吗? – wolverine 2012-04-27 12:20:52

+0

@parag,好的谢谢。 – wolverine 2012-04-27 12:33:20

+0

总是欢迎的朋友 – 2012-04-27 12:34:24

回答

39

您应该作出BroadcastReceiver当连接状态已经改变,将触发:

 public class BroadCastSampleActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
     this.registerReceiver(this.mConnReceiver, 
       new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); 
    } 
    private BroadcastReceiver mConnReceiver = new BroadcastReceiver() { 
     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); 

      if(currentNetworkInfo.isConnected()){ 
       Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show(); 
      }else{ 
       Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show(); 
      } 
     } 
    }; 
} 

,然后在AndroidManifest您可以检查您是否已经连接:

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

下载源代码 - here

+0

我添加了这段代码,但没有得到任何当网络变化时Toast消息.. – wolverine 2012-04-27 12:34:05

+0

这工作像一个魅力,这工程.. – Darpan 2013-01-04 13:07:09

+0

嘿你有没有检查另一个RegisterReceiver方法与签名(接收器,过滤器,Braodcastpermission,处理程序)?我的疑问是,如果您必须使用它来注册此接收器,您将使用什么“广播许可”? – Darpan 2013-01-25 14:08:04

相关问题