Android服务来检查互联网连接?

我想创build一个Android服务,它会在断开连接和重新连接互联网时通知主要活动。 我有以下function来检查互联网连接:

private boolean haveInternet(){ NetworkInfo info=(NetworkInfo)((ConnectivityManager)this.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; } 

但是我想知道,如何在服务中使用它。

Solutions Collecting From Web of "Android服务来检查互联网连接?"

服务是专为长背景运行任务。 你应该使用BroadcastReceiver

这是我用来监视networking状态进入我的主要活动的示例方法:

 private void installListener() { if (broadcastReceiver == null) { broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle extras = intent.getExtras(); NetworkInfo info = (NetworkInfo) extras .getParcelable("networkInfo"); State state = info.getState(); Log.d("InternalBroadcastReceiver", info.toString() + " " + state.toString()); if (state == State.CONNECTED) { onNetworkUp(); } else { onNetworkDown(); } } }; final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(broadcastReceiver, intentFilter); } } 

记得在发生onDestroy事件时调用unregisterReceiver

希望这个帮助。