2016-09-01 106 views
-2

我需要檢查用戶是否已連接CONNECTIVITY_SERVICE,因此下面的代碼給出了返回isSourceAvailable爲「true」的結果。Android檢查網絡認證

ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
     isSourceAvailable = (activeNetworkInfo != null && activeNetworkInfo.isConnected()); 

,但可能他沒有通過認證,所以我試着用下面的代碼,但它返回我「已完成」,而這是不被認證。

SupplicantState supplicantState; 
      WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); 
      WifiInfo wifiInfo = wifiManager.getConnectionInfo(); 
      supplicantState = wifiInfo.getSupplicantState(); 

enter image description here

回答

1

你必須添加此

ConnectivityManager CManager = 
    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo NInfo = CManager.getActiveNetworkInfo(); 
if (NInfo != null && NInfo.isConnectedOrConnecting()) { 
    if (InetAddress.getByName("www.xy.com").isReachable(timeout)) 
    { 
    // host reachable true 
    } 
    else 
    {  
    // host not reachable false 
    } 
} 
return; 
+0

感謝Himani,但我已經嘗試你的答案的替代,其通過的openConnection(),這是不是在我的情況下非常有用,因爲它是網絡任務。 –