android - Android 中的互联网连接

标签 android http ping

是否有比以下更好的选项来检查互联网连接。我知道 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/

相关文章:

javascript - 无法使用 PhantomJS 加载页面资源

javascript - 如何从 Angularjs 模块调用 JSON 文件

batch-file - 多次 ping 尝试后批处理崩溃

android - 异步运行一个方法

android - 如何在回收站 View 中隐藏特定行的 View ?

android - 如何在 jetpack compose 中使用惰性列和惰性垂直网格?

android - 加载大量图片时,Recyclerview 加载时间过长

Android - 在继续之前等待动画完成?

java - HTTP GET 检索压缩文件

python - 如何使用 Python websockets 库在 "pong"调用上获取 "ping"响应?