3
我用isReachable,但它没有工作,我用ConnectivityManager和getNetworkInfo;其实这仅适用于检查,如果我连接到互联网...如何从Android活动ping一个网站并得到回应?
但问题是我要检查,所以我想用ping一个网站,以检查是否有响应,我可以访问互联网。
我用isReachable,但它没有工作,我用ConnectivityManager和getNetworkInfo;其实这仅适用于检查,如果我连接到互联网...如何从Android活动ping一个网站并得到回应?
但问题是我要检查,所以我想用ping一个网站,以检查是否有响应,我可以访问互联网。
GET方法:
private void executeReq(URL urlObject) throws IOException{
HttpURLConnection conn = null;
conn = (HttpURLConnection) urlObject.openConnection();
conn.setReadTimeout(100000); //Milliseconds
conn.setConnectTimeout(150000); //Milliseconds
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Start connect
conn.connect();
String response = convertStreamToString(conn.getInputStream());
Log.d("Response:", response);
}
您可以用
try {
String parameters = ""; //
URL url = new URL("http://alefon.com" + parameters);
executeReq(url);
}
catch(Exception e){
//Error
}
调用它来检查Internet连接,使用:
private void checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (null == ni)
Toast.makeText(this, "no internet connection", Toast.LENGTH_LONG).show();
else {
Toast.makeText(this, "Internet Connect is detected .. check access to sire", Toast.LENGTH_LONG).show();
//Use the code above...
}
}
使用这一个.. 该作品对我来说很好:)
public static void isNetworkAvailable(Context context){
HttpGet httpGet = new HttpGet("http://www.google.com");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try{
Log.e("checking", "Checking network connection...");
httpClient.execute(httpGet);
Log.e("checking", "Connection OK");
return;
}
catch(ClientProtocolException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
Log.e("checking", "Connection unavailable");
}
谢谢@Mohammed,问题是,我要检查,如果我可以访问任何网站,如果是让举杯说:“有上网” ......如果不是敬酒说“浏览问题”,即使该设备连接到WiFi – Amt87 2012-03-26 14:47:13
我更新答案..检查它的PLZ ..但它仍然需要检查访问网站..因为可能服务器停机,或没有访问等。所以检查互联网连接,然后检查呼叫站点和得到回应.... – 2012-03-26 15:09:32