检查 libGDX 中的网络状态

Check network state in libGDX

我想在 libGDX 项目中检查 Wifi 状态,尝试使用以下代码:

   Gdx.net.sendHttpRequest(HttpRequest httpRequest, HttpResponseListener httpResponseListener);

    HttpResponseListener httpResponseListener = new  httpResponseListener() {
        public void handleHttpResponse (HttpResponse httpResponse) {
            HttpStatus status = httpResponse.getStatus();
            if (status.getStatusCode() >= 200 && status.getStatusCode() < 300) {
                // it was successful
            } else {
                // do something else
            }
        }
    }

我添加了权限:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

它说 HttpResponseListener cannot resolved。 我应该如何解决这个问题?

// there is a small 'h' here, which is wrong ---v
HttpResponseListener httpResponseListener = new httpResponseListener() {
    public void handleHttpResponse (HttpResponse httpResponse) {
        HttpStatus status = httpResponse.getStatus();
        if (status.getStatusCode() >= 200 && status.getStatusCode() < 300) {
            // it was successful
        } else {
            // do something else
        }
    }
}

// here, you still have the parameter types
Gdx.net.sendHttpRequest(HttpRequest httpRequest, HttpResponseListener httpResponseListener);
// this is correct
Gdx.net.sendHttpRequest(httpRequest, httpResponseListener);

除此之外,这可能行不通。如果没有互联网连接,您将不会从服务器获得响应。您必须覆盖 HttpResponseListener.failed().