我尝试使用其他方法,如HttpURLConnection和URLConnection,但它们即使在连接时也会返回false。
有什么想法或解决方案可以在所有设备上运行。提前感谢您的回答。我将按顺序发布我已经尝试过的内容。
方法1:
public static Boolean isOnline() {
try {
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 8.8.8.8");
int returnVal = p1.waitFor();
return (returnVal == 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
我已经尝试过本地和谷歌服务器,并且产生了完美的结果。问题是它不能在所有设备上运行。
方法2:
public boolean isConnected() {
boolean connectivity;
try {
URL url = new URL("www.google.com");
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);
conn.connect();
connectivity = true;
} catch (Exception e) {
connectivity = false;
}
return connectivity;
}
无论我的连接是否活动,这个方法总是返回false。 方法三:
public static boolean isInternetReachable() {
try {
//make a URL to a known source
URL url = new URL("http://www.google.co.ke");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection) url.openConnection();
Object objData = urlConnect.getContent();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
与这个相同。假值.
上一个是这个类,但它也在做相同的事情:
class TestInternet extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
connected = true;
return connected;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
connected = false;
return connected;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
connected = false;
return connected;
}
return connected;
}
@Override
protected void onPostExecute(Boolean result) {
if (!result) { // code if not connected
AlertDialog.Builder builder = new AlertDialog.Builder(CtgActivity.this);
builder.setMessage("An internet connection is required.");
builder.setCancelable(false);
builder.setPositiveButton(
"TRY AGAIN",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
new TestInternet().execute();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
} else { // code if connected
Toast.makeText(CtgActivity.this,"Yes",Toast.LENGTH_LONG).show();
}
}
@Override
protected void onPreExecute() {
Toast.makeText(getBaseContext(),"Checking for internet",Toast.LENGTH_LONG).show();
super.onPreExecute();
}
}
我在浏览Stack Overflow寻找任何有关的内容,但所有的都与这些问题有关。请告诉我是否我做错了什么或建议更好的解决方法。这是我项目的最后一步。