在Android中经常用到网络状态和网络类型,不如网络为WIFI是做某一操作,网络为数据流量时做另一个操作。
以下是获取网络类型的示例代码:
private void checkNetworkConnection() {
String TAG = "Basic Network Demo";
// Whether there is a Wi-Fi connection.
boolean wifiConnected = false;
// Whether there is a mobile connection.
boolean mobileConnected = false;
// BEGIN_INCLUDE(connect)
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
if (wifiConnected) {
Log.i(TAG, "The active connection is wifi.");
} else if (mobileConnected) {
Log.i(TAG, "The active connection is mobile.");
}
} else {
Log.i(TAG, "No wireless or mobile connection.");
}
// END_INCLUDE(connect)
}