Android:哪种方法可以检查有效的互联网连接

时间:2017-01-11 06:24:04

标签: android internet-connection android-internet

我已经找到了一种快速有效的方法来检查互联网连接,我发现它更好地ping谷歌找到互联网连接状态。但我发现了一些ping谷歌的方法,我很困惑哪一个使用所有那些。我看到的方法。

方法1:

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) {
        e.printStackTrace();
    }
    return false;
}

方法2:

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;
}

方法3:

public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
    try {
        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500); 
        urlc.connect();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error checking internet connection", e);
    }
} else {
    Log.d(LOG_TAG, "No network available!");
}
return false;
}

方法4:

for example:

**s1->s2  (one shard with replicat (primary:s1,secondry:s2))
s3->s4  (2nd shard with replics (primary s3, secondry s4))
s5->s6  (third shard with replics (primary s5, secondry s6))
config, router is on all server i.e s1 to s6**

我应该选择哪一个?我需要一种更快捷有效的方法。

2 个答案:

答案 0 :(得分:0)

您可以尝试使用InetAddress.getByName(host).isReachable(timeOut)检查主机是否可用。它应该与检查连接是否有效相同。

查看文档以获取更多信息。InetAddress

答案 1 :(得分:-1)

我每次都使用广播检查连接。为连接信息创建一个类。

import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


public class ConnectivityStatus extends ContextWrapper{

    public ConnectivityStatus(Context base) {
        super(base);
    }

    public static boolean isConnected(Context context){

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo connection = manager.getActiveNetworkInfo();
        if (connection != null && connection.isConnectedOrConnecting()){
            return true;
        }
        return false;
    }
}

将代码应用到您的活动中:

 private BroadcastReceiver receiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
        if(!ConnectivityStatus.isConnected(getContext())){
            // no connection
        }else {
            // connected
        }
    }
 };

在您的活动的onCreate()方法中注册广播:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    ..
    ...
    ....
  }

不要忘记在活动周期中取消注册/注册:

@Override
protected void onResume() {
    super.onResume();
    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

}

@Override
protected void onPause() {
    super.onPause();
    your_activity_context.unregisterReceiver(receiver);

}