如何从Java Android Studio ping网站

时间:2019-05-31 10:47:42

标签: android server ping

我目前正在使用Android Studio开发需要互联网连接才能运行的应用程序。我想通过ping我的网站在应用程序开始时检查互联网访问。我已经尝试过方法ConnectivityManager,但是它只是检查用户是否已连接到wifi或移动数据。我如何对任何网站执行ping操作,以检查手机是否可以访问互联网?

2 个答案:

答案 0 :(得分:0)

/**
 * Verifies if the device is connected to the internet.
 * @return
 */
public static boolean itsOnline(Context context) {
    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();

        StrictMode.setThreadPolicy(policy);

        int timeoutMs = 2000;
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

        sock.connect(sockaddr, timeoutMs);
        sock.close();
        Log.i("CONNECTION STATUS:", "connected");

        return true;
    } catch (IOException ioException) {
        Log.i("CONNECTION STATUS:", "disconnected");
        return false;
    }
    return false;
}

答案 1 :(得分:0)

You can check different connection-types by using the TelephonyManager like so:

public boolean hasNetworkAccess() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getNetworkInfo(cm.getActiveNetwork());

        return info.isConnected();
    }

    public String connectionStrength() {
        if (!hasNetworkAccess()) {
            return "NOT_CONNECTED";
        }

        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

        // switch for different network types (e.g. 4G, EDGE, ...)
        switch (tm.getNetworkType()) {
            case TelephonyManager.NETWORK_TYPE_EDGE:
                // return a value that you want to identify the strength with
                return "EDGE";
            // ...
            default:
                return null;
        }
    }

Dont forget to add the <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> in the manifest above the application tag