[英]How to properly check internet connection on android device?
我正在嘗試檢查 Android 設備上的互聯網連接,我嘗試了一些方法,但所有這些都有問題:如果我打開移動連接但我的手機沒有互聯網,Android 會檢測到互聯網連接可用。
我嘗試使用InetAddress
ping Google 但它不起作用,永遠不會超時。
我什至嘗試使用HttpUrlConnection
也可以連接到 Google 但從不超時,只有移動數據連接。 似乎永遠不會結束。
帶有HttpUrlConnection
代碼
//It is in a boolean method that return true if Internet is available
try {
HttpURLConnection urlConnection = (HttpURLConnection) (new URL("https://www.google.com").openConnection());
urlConnection.setRequestProperty("User-Agent", "Test");
urlConnection.setRequestProperty("Connection", "close");
urlConnection.setConnectTimeout(3500);
urlConnection.connect();
return urlConnection.getResponseCode() == 200;
} catch (SocketTimeoutException socketTimeoutException) {
Log.e("Internet Connection", "Internet Connection error : " + socketTimeoutException);
return false;
} catch (IOException exception) {
Log.e("Internet Connection", "Internet Connection error : " + exception);
return false;
}
我做的最后一次嘗試是使用SocketAddress
但它總是通過移動連接返回 true。
帶有SocketAddress
代碼
//Even in the same method
try {
int timeout = 3500;
Socket socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress("8.8.8.8", 53);
socket.connect(socketAddress, timeout);
socket.close();
} catch (IOException exception) {
return false;
}
return true;
我該做什么? 我也嘗試過getActiveNetworkInfo()
但我讀到它只檢查網絡是否可用,即使沒有互聯網連接。
任何幫助將不勝感激,謝謝。
您可以使用以下代碼檢查互聯網連接。
public class CheckInternetConnection {
private Context context;
public CheckInternetConnection(Context context) {
this.context = context;
}
//checking internet connection if internet is connected then it will return true
// otherwise it will return false
public boolean netCheck(){
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
boolean isConnected = nInfo != null && nInfo.isConnectedOrConnecting();
return isConnected;
}
}
在訪問 firebase 之前檢查互聯網連接是沒有意義的。 即使您的檢查通過,當您嘗試訪問 firebase 時,連接也可能在一秒鍾后丟失。 更好的是,只需嘗試訪問 firebase 並正確處理任何錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.