我使用一个功能通过发送ping成功检测Android 4.1到6.0应用中的互联网连接。 (因为,请记住,连接到WiFi或移动网络本身并不能保证,该设备实际上可以访问互联网。) 我的问题是我发现由于某种原因,我的代码在Android 4.3中无效。 你知道怎么解决这个问题吗?或者,您是否知道在Android 4.1 - 6.0版本的所有设备上检测互联网连接的更好方法?
//this function works perfectly!! except in Android 4.3 Jellybean
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
if(exitValue==0)
app.logy("PING @K - ONLINE!!");
return (exitValue == 0);
} catch (IOException e){
e.printStackTrace();
app.logy("PING ERROR - OFFLINE");
return false;
}
catch (InterruptedException e){
e.printStackTrace();
app.logy("PING ERROR - OFFLINE");
return false;
}
}
答案 0 :(得分:0)
http://clients3.google.com/generate_204用于检查连接,ping在不同设备中的工作方式不同。
Why does ping works on some devices and not others?
private int inter = 0;
class checkconne extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... args) {
int kk=0;
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();
kk= urlc.getResponseCode();
} catch (IOException e) {
Log.e("qweqwe", "Error checking internet connection", e);
}
inter=kk;
return null;
}
@Override
protected void onPostExecute(String file_url) {
if (inter == 204){
Toast.makeText(MainActivity3.this, "is connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity3.this, "No connection", Toast.LENGTH_LONG).show();
}
}
}