为此创建一个广播接收器,并将其注册到清单文件中。
首先创建一个新类
NetworkStateReceiver并扩展BroadcastReceiver。
public class NetworkStateReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { Log.d("app","Network connectivity change"); if(intent.getExtras()!=null) { NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO); if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) { Log.i("app","Network "+ni.getTypeName()+" connected"); } } if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) { Log.d("app","There's no network connectivity"); } }}
将此代码放在“ application”元素下的AndroidManifest.xml中:
<receiver android:name=".NetworkStateReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter></receiver>
并添加此权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
编辑
此代码仅检测连接性变化,但无法判断其连接的网络是否可以访问互联网。使用此方法检查-
public static boolean hasActiveInternetConnection(Context context) { if (isNetworkAvailable(context)) { try { HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); urlc.setRequestProperty("User-Agent", "Test"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1500); urlc.connect(); return (urlc.getResponseCode() == 200); } catch (IOException e) { Log.e(LOG_TAG, "Error checking internet connection", e); } } else { Log.d(LOG_TAG, "No network available!"); } return false;}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)