我使用了一个功能,通过发送 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;
}
}
最佳答案
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();
}
}
}
关于java - 仅在 Android 4.3 Jellybean 中使用 ping 验证互联网连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33799950/