简体   繁体   English

如何在Android中了解服务器是否可达?

[英]How to know the server in reachable or not in android?

Hi, I want to know is my website in reachable or available? 嗨,我想知道我的网站可访问或可用吗?

whit this method I know my device is online or not: 我知道我的设备是否在线:

protected boolean isOnline() {

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            Toast.makeText(this, "You are connecting to Internet!", Toast.LENGTH_LONG).show();
            return true;
        } else {
            Toast.makeText(this, "You are not connecting to Internet!", Toast.LENGTH_LONG).show();
            return false;
        }
    }

and with this method I want to know is URL available or not: 使用这种方法,我想知道URL是否可用:

public boolean isServerReachable(String serverURL) {

        ConnectivityManager connMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = connMan.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            try {
                URL urlServer = new URL(serverURL);
                HttpURLConnection urlConn = (HttpURLConnection) urlServer.openConnection();
                urlConn.setConnectTimeout(3000); //<- 3Seconds Timeout
                urlConn.connect();
                if (urlConn.getResponseCode() == 200) {
                    Toast.makeText(this, "Server is Available", Toast.LENGTH_LONG).show();
                    return true;
                } else {
                    Toast.makeText(this, "Server is not Available", Toast.LENGTH_LONG).show();
                    return false;
                }
            } catch (MalformedURLException e1) {
                return false;
            } catch (IOException e) {
                return false;
            }
        }
        return false;
    }

then I create a Button, when clicked this two method will call, like this: 然后我创建一个Button,单击时将调用这两个方法,如下所示:

if (isOnline()) {
    isServerReachable("https://www.google.com/");
 }

when I click the Button if WiFi is Off this Message will show: 如果WiFi关闭,当我单击按钮时,此消息将显示:

You are not connecting to Internet! 您没有连接到互联网!

and when WiFi is On this error will show: 当WiFi开启时,此错误将显示:

> Process: com.rastari.salar.salytest, PID: 3864
>     android.os.NetworkOnMainThreadException
>             at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
>             at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
>             at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
>             at java.net.InetAddress.getAllByName(InetAddress.java:215)
>             at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
>             at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
>             at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
>             at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
>             at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
>             at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
>             at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
>             at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
>             at com.android.okhttp.internal.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:25)
>             at com.rastari.salar.salytest.MainActivity.isServerReachable(MainActivity.java:78)
>             at com.rastari.salar.salytest.MainActivity$1.onClick(MainActivity.java:37)
>             at android.view.View.performClick(View.java:4780)
>             at android.view.View$PerformClick.run(View.java:19866)
>             at android.os.Handler.handleCallback(Handler.java:739)
>             at android.os.Handler.dispatchMessage(Handler.java:95)
>             at android.os.Looper.loop(Looper.java:135)
>             at android.app.ActivityThread.main(ActivityThread.java:5254)
>             at java.lang.reflect.Method.invoke(Native Method)
>             at java.lang.reflect.Method.invoke(Method.java:372)
>             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
>             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 06-25
> 06:14:16.845    1557-1557/? E/EGL_emulation﹕ tid 1557:
> eglCreateSyncKHR(1207): error 0x3004 (EGL_BAD_ATTRIBUTE) 06-25
> 06:14:17.614    1708-1891/? E/WifiStateMachine﹕ CMD_START_SCAN :
> connected mode and no configuration

How can I determine that the server is available or not? 如何确定服务器可用?

Thank u. 感谢你。

Call your method isServerReachable() from an Asynctask . Asynctask调用方法isServerReachable()

Since your doing a network call on main thread of your application, it crashes. 由于您是在应用程序的主线程上进行网络调用,因此崩溃。

The error is due to isServerReachable() method because you are doing the networking operations in the UI thread, which will result NetworkOnMainThreadException . 该错误是由于isServerReachable()方法引起的,因为您正在UI线程中进行联网操作,这将导致NetworkOnMainThreadException Instead to running them directly execute the method in a AsyncTask or another worker Thread . 而不是直接运行它们,而是在AsyncTask或另一个辅助Thread执行该方法。

 public class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Void... params) {
            return isServerReachable(URl);
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            //Perform operations.
        }
    }

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

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