專案實戰:三、判斷有網沒網 識別WIFI線上
1.判斷是不是wifi:
/**
* Check whether the device is connected, and if so, whether the connection
* is wifi or mobile (it could be something else).
*/
private void checkNetworkConnection() {
// 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, getString(R.string.wifi_connection));
} else if (mobileConnected){
Log.i(TAG, getString(R.string.mobile_connection));
}
} else {
Log.i(TAG, getString(R.string.no_wifi_or_mobile));
}
// END_INCLUDE(connect)
}
---------------------
2.NetworkInfo判斷有網沒網:
public static Boolean getResault(FragmentActivity activity) {
//定義一個布林型別變數,用來返回到底有沒有網路的結果
Boolean resault = false;
//獲取網路連線管理物件
ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(activity.CONNECTIVITY_SERVICE);
//根據連線管理物件呼叫getActiveNetworkInfo方法
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
//判斷當前activity是否連線網路
if(activeNetworkInfo!=null){
//有網,判斷網路是否可用,可用賦值true
resault=activeNetworkInfo.isAvailable();
}
return resault;
}
---------------------
3.