0

I am trying to check internet connection of device first, if Internet is available...I need to check server is online or not. I have searched lot of in stackflow for it but there no where latest solution is available like below

1

2

but none of it is working properly as people comments and my trial. I am checking internet status of device with below code

public static boolean isInternetAvailable(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    boolean isActiveNetworkConnected = false;

    if (connectivity != null) {

        NetworkInfo info = connectivity.getActiveNetworkInfo();

        if (info != null) {
            if (info.getState() == NetworkInfo.State.CONNECTED) {

                isActiveNetworkConnected = true;
            } else {
                isActiveNetworkConnected = false;
            }
        }
    } else {
        isActiveNetworkConnected = false;
    }

    return isActiveNetworkConnected;
}

Let me know anyone have proper solution which can check server available or not with this code.

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

0

After checking the internet connectivity, you can simply make a test API hit to check server status. Send the request to server if server respond ok, start next work or in-other case handle server not responding message for user.

Here is a sample using okhttp

public boolean isServerUp(){

    private final OkHttpClient client = new OkHttpClient();

      public void run() throws Exception {
        Request request = new Request.Builder()
            .url("your server url here")
            .build();

        client.newCall(request).enqueue(new Callback() {
          @Override public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            return false;
          }

          @Override public void onResponse(Call call, Response response) throws IOException {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            return true; 
          }
        });
      }
      return false;
}
Junaid Hafeez
  • 1,618
  • 1
  • 16
  • 25
0

For checking the current status of the server after network checked, need to check if the response is not null

Ismaran Duwadi
  • 1,529
  • 12
  • 10