Pregunta

I want to full check connection to internet and a domain or host. I used a method to check internet connection, but i can not add checking host availability. My code is here;

public class InternetCheck{
    public static boolean isInternetAvailable(Context context)
    {
        NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
        context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        if (info == null){
            Constants.connectionProblem = "Check your internet connection";
            return false;
        }
        else{
            return true;
        }
    }
}

I want to add host or domain availability check inside of isInternetAvailable() method. It must return false and set Constant.connectionProblem = "Host is not available" . Because, i will call that method on my main activity and if it returns false, i will show a Toast which shows that Constants.connectionProblem .

¿Fue útil?

Solución

try this method

private boolean isHostRechable(String hostUrl) {
        try {
            URL url = new URL(hostUrl);
            final HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setRequestProperty("User-Agent", "Android Application");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(10 * 1000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }

Otros consejos

use this method :

public static boolean isInternetConnected(Context context) {
    final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
    final Dialog dialog = new AlertDialog.Builder(context).setIcon(R.drawable.ic_launcher).setTitle("Connection Error!!")
            .setMessage("Internet Connection not found.\nCheck your settings.").setNegativeButton("ok", null).create();
    if (activeNetwork != null && activeNetwork.isConnected())
        return true;
    else
        dialog.show();
    return false;
}

If you don't want to show the toast comment it.

Don't forget to place permission in manifest file. Here is the permission :

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top