您可以使用ConnectivityManager来检查网络状态。ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);if ( conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ) { // notify user you are online}else if ( conMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.DISCONNECTED || conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.DISCONNECTED) { // notify user you are not online}请注意,常量ConnectivityManager.TYPE_MOBILE和ConnectivityManager.TYPE_WIFI表示连接类型,并且这两个值并不详尽。另外,请确保您具有监视网络状态所需的权限。您需要将此权限添加到您的AndroidManifest.xml中:<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
在任一点上只能有一个连接处于活动状态。因此,一个简单的答案是:final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();if (activeNetwork != null && activeNetwork.isConnected()) { // notify user you are online} else { // notify user you are not online} 它还适合任何新型网络,例如ConnectivityManager#TYPE_WIMAX另外,请确保您具有监视网络状态所需的权限。您需要将此权限添加到您的AndroidManifest.xml中:<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />