在Android中經(jīng)常用到網(wǎng)絡(luò)狀態(tài)和網(wǎng)絡(luò)類(lèi)型揪阶,不如網(wǎng)絡(luò)為WIFI是做某一操作播演,網(wǎng)絡(luò)為數(shù)據(jù)流量時(shí)做另一個(gè)操作偶翅。
以下是獲取網(wǎng)絡(luò)類(lèi)型的示例代碼:
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)
}