简体   繁体   English

Android Internet连接超时

[英]Android Internet Connection timeout

I'm able to detect Internet connection using 我可以使用检测到Internet连接

public class InternetDetector {

    private Context _context;

    public InternetDetector(Context context) {
        this._context = context;
    }

    /**
     * Checking for all possible internet providers
     **/
    public Boolean isConnectingToInternet() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
    }
    public Boolean isOnline() {
        try {
            Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
            int returnVal = p1.waitFor();
            boolean reachable = (returnVal == 0);
            return reachable;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
}

This works perfectly if there is internet, but in some cases I am able to connect to WIFI but no internet. 如果有互联网,这将非常有效,但是在某些情况下,我可以连接到WIFI,但没有互联网。 In this case If internet is not available I nned to show a message[No INTERNET CHECK YOUR CONNECTION] to user after 10 seconds 在这种情况下,如果互联网不可用,我会在10秒钟后向用户显示一条消息[No INTERNET CHECK YOUR CONNECTION]

How can I achieve it. 我该如何实现。

You can achieve this by using handler 您可以使用处理程序来实现

new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        // This method will be executed once the timer is over
        // Your message here
    }
}, 10000); //Your time here in miliseconds

After the time is completed the message will be displayed to user. 时间结束后,该消息将显示给用户。 Simple is that. 很简单。

For 10 seconds you can add 10000 10秒内您可以增加10000

You can try out the following to check for internet connectivity and therefafter show a toast in case there is no internet : 您可以尝试以下方法检查互联网连接,然后在没有互联网的情况下显示祝酒词:

boolean isInternetAvailable = checkInternetConnection(this);

    if(!isInternetAvailable) {
        new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(this, "No INTERNET CHECK YOUR CONNECTION", Toast.LENGTH_SHORT).show();
    }
}, 10000);
    }

    public static boolean checkInternetConnection(Context context) {
        final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();

        if (activeNetworkInfo != null) { // connected to the internet
            Toast.makeText(context, activeNetworkInfo.getTypeName(), Toast.LENGTH_SHORT).show();

            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                // connected to wifi
                return isWifiInternetAvailable();
            } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                // connected to the mobile provider's data plan
                return true;
            }
        }
        return false;
    }

public boolean isWifiInternetAvailable() {
        try {
            InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
            return !ipAddr.equals("");
        } catch (Exception e) {
            return false;
        }
    }

You are right, you can check if you are connected to the wifi or Cellular Network but you cannot easily check if you are really connected to the Internet or not. 没错,您可以检查是否已连接到wifiCellular Network但无法轻松检查是否确实已连接到Internet

Right now the only way to check if you are really connected to the internet is to connecting to a remote server! 现在,检查您是否真正连接到互联网的唯一方法是连接到远程服务器! for example: 例如:

public static boolean hasInternetAccess(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) 
                (new URL("http://clients3.google.com/generate_204")
                .openConnection());
            urlc.setRequestProperty("User-Agent", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 204 &&
                        urlc.getContentLength() == 0);
        } catch (IOException e) {
            Log.e(TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(TAG, "No network available!");
    }
    return false;
}

You can change URL to any desired address but this URL generate a determined response so you don't have to worry about server problems.. Of course you can Change it to your server to check availability of server too ^^ 您可以将URL更改为任何所需的地址,但是此URL会生成确定的响应,因此您不必担心服务器问题。.当然,您也可以将其更改为服务器以检查服务器的可用性^^

For more info you can check this answer: Detect if Android device has Internet connection 有关更多信息,您可以检查以下答案: 检测Android设备是否具有Internet连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM