是否有比以下更好的选项来检查互联网连接。我知道 Wifi 或移动数据已连接,但我想知道我的应用是否能够连接到互联网以接收数据:
class checkInternetNetwork extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... params)
{
internetavailable = isInternetConnected();
return null;
}
protected void onPostExecute(String file_url)
{
if (internetavailable == false)
{
Log.e("Check","internetavailable");
Toast.makeText(getActivity().getApplicationContext(), "Unable to connect to server. Check your network!!", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
}
我有这样的 isInternetConnected 方法:
public boolean isInternetConnected()
{
final int CONNECTION_TIMEOUT = 1000;
try
{
HttpURLConnection mURLConnection = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
mURLConnection.setRequestProperty("User-Agent", "ConnectionTest");
mURLConnection.setRequestProperty("Connection", "close");
mURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);
mURLConnection.setReadTimeout(CONNECTION_TIMEOUT);
mURLConnection.connect();
return (mURLConnection.getResponseCode() == 200);
}
catch (IOException ioe)
{
}
return false;
}
问题是 internetAvailable 总是显示错误。
对此的解决方案将非常有用。
谢谢!
最佳答案
这绝对是一种简单的方法。更好的方法是实际检查您尝试使用的 Web 服务。因为假设 Google.com 可能出现故障而您的网络服务仍在运行,反之亦然,Google.com 可能正常运行而您的网络服务可能出现故障。
您也可以尝试:(See Documentation: 使用“ConnectivityManager 查询 Activity 网络并确定它是否具有 Internet 连接。”)
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
关于android - Android 中的互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25790899/