【问题标题】:Checking Internet connection on Android在 Android 上检查 Internet 连接
【发布时间】:2013-03-15 08:57:48
【问题描述】:

我需要在 Android 应用上检查互联网连接。

我正在使用此代码:

 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni!=null && ni.isAvailable() && ni.isConnected()) {
            return true;
        } else {
            return false; 
        }

并且不能通过下一个错误:

未为类型 ConxsMTD 定义方法 getSystemService(String)

我尝试使用getContext().getSystemService,但也因下一个错误而失败:

方法 getContext() 对于 ConxsMTD 类型未定义

知道我做错了什么吗?

【问题讨论】:

  • 在这两种情况下,您都使用了您使用的类中不可用的方法。这是基本的java知识...

标签: java android connection


【解决方案1】:

这并不能解决您给定的示例,但我的示例确实有效并且更简单(在我看来)。

您要做的是发送一个“ping”(如果您想这样称呼它)来检查连接。如果连接完成,您就知道您仍然处于连接状态。如果您收到IOExceptionNullPointerException,那么您可能已超时并且不再连接。

try {
    URL url = new URL("http://www.google.com");
    HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
    urlConnect.setConnectTimeout(1000);
    urlConnect.getContent();
    System.out.println("Connection established.");
} catch (NullPointerException np) {
    np.printStackTrace();
} catch (IOException io) {
    io.printStackTrace();
}

【讨论】:

    【解决方案2】:

    使用这个sn-p,我在每个项目中都使用它:

    public static boolean checkNetworkState(Context context) {
        ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo infos[] = conMgr.getAllNetworkInfo();
        for (NetworkInfo info : infos) {
            if (info.getState() == State.CONNECTED)
                return true;
        }
        return false;
    }
    

    因此,您只需将getApplicationContext() 传递给此方法,例如boolean hasConnection = checkNetworkState(getApplicationContext());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 2020-11-07
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多