Java 检查是否有活动的internet连接
我正在尝试在我的应用程序中编写一个部分来区分活动Wifi连接和实际的互联网连接。使用连接管理器确定是否存在活动的Wifi连接非常简单,但是每次我尝试在Wifi连接但没有互联网连接时测试是否可以连接到网站时,我都会陷入无限循环。Java 检查是否有活动的internet连接,java,android,networking,wifi,ping,Java,Android,Networking,Wifi,Ping,我正在尝试在我的应用程序中编写一个部分来区分活动Wifi连接和实际的互联网连接。使用连接管理器确定是否存在活动的Wifi连接非常简单,但是每次我尝试在Wifi连接但没有互联网连接时测试是否可以连接到网站时,我都会陷入无限循环。 我曾尝试ping google,但结果都是一样的: Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com"); int returnVal = 5; try { ret
我曾尝试ping google,但结果都是一样的:
Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
int returnVal = 5;
try {
returnVal = p1.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean reachable = (returnVal==0);
return reachable;
我还尝试了以下代码:
if (InetAddress.getByName("www.xy.com").isReachable(timeout))
{ }
else
{ }
但是我无法让我方便地工作。我使用这个:
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.d(TAG, "Checking network connection...");
httpClient.execute(httpGet);
Log.d(TAG, "Connection OK");
return;
}
catch(ClientProtocolException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
Log.d(TAG, "Connection unavailable");
}
它来自另一个答案,但我找不到
编辑:
最后我找到了它:像这样查询一个网站: 通过向类中添加以下方法,使类实现
AsyncTaskCompleteListenere
:
@Override
public void onTaskComplete(Boolean result) {
Toast.makeText(getApplicationContext(), "URL Exist:" + result, Toast.LENGTH_LONG).show();
// continue your job
}
在类中添加一个简单的testConnection
方法,以便在检查连接时调用:
public void testConnection() {
URLExistAsyncTask task = new URLExistAsyncTask(this);
String URL = "http://www.google.com";
task.execute(new String[]{URL});
}
最后是URLExistAsyncTask
类,该类将连接测试作为异步(后台)任务执行,并在完成后调用onTaskComplete
方法:
public class URLExistAsyncTask extends AsyncTask<String, Void, Boolean> {
AsyncTaskCompleteListenere<Boolean> callback;
public URLExistAsyncTask(AsyncTaskCompleteListenere<Boolean> callback) {
this.callback = callback;
}
protected Boolean doInBackground(String... params) {
int code = 0;
try {
URL u = new URL(params[0]);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
code = huc.getResponseCode();
} catch (IOException e) {
return false;
} catch (Exception e) {
return false;
}
return code == 200;
}
protected void onPostExecute(Boolean result){
callback.onTaskComplete(result);
}
}
公共类URLExistAsyncTask扩展了异步任务{
AsyncTaskCompleteListenere回调;
公共URLExistAsyncTask(AsyncTaskCompleteListenere回调){
this.callback=回调;
}
受保护的布尔doInBackground(字符串…参数){
int代码=0;
试一试{
URL u=新URL(参数[0]);
HttpURLConnection huc=(HttpURLConnection)u.openConnection();
huc.setRequestMethod(“GET”);
huc.connect();
code=huc.getResponseCode();
}捕获(IOE异常){
返回false;
}捕获(例外e){
返回false;
}
返回码==200;
}
受保护的void onPostExecute(布尔结果){
callback.onTaskComplete(结果);
}
}
它确实对我有用:
要验证网络可用性,请执行以下操作:
private Boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
}
要验证internet访问,请执行以下操作:
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
为了检查android设备是否有活动连接,我使用下面的hasActiveInternetConnection()方法:(1)尝试检测网络是否可用,(2)然后连接到google.com以确定网络是否活动
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
if (connectGoogle()) {
return true;
} else { //one more try
return connectGoogle();
}
} else {
log("No network available! (in hasActiveInternetConnection())");
return false;
}
}
public static boolean isNetworkAvailable(Context ct) {
ConnectivityManager connectivityManager = (ConnectivityManager) ct.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public static boolean connectGoogle() {
try {
HttpURLConnection urlc = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(10000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
log("IOException in connectGoogle())");
return false;
}
}
下面是一些现代代码,它使用
AsynTask
来解决当您尝试在主线程上连接时android崩溃的问题,并为用户引入了一个带有漂洗和重复选项的警报
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) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
if (!result) { // code if not connected
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.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
doMyStuff();
}
}
}
我确实使用了这种方法。这对我有用!对于那些想要真正上网的人来说
public boolean isOnline() {
try {
HttpURLConnection httpURLConnection = (HttpURLConnection)(new URL("http://www.google.com").openConnection());
httpURLConnection.setRequestProperty("User-Agent", "Test");
httpURLConnection.setRequestProperty("Connection", "close");
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.connect();
return (httpURLConnection.getResponseCode() == 200);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
谢谢你每次都这么做!只要用一个接收器
和=>
httpURLConnection.getResponseCode() == 200
这意味着互联网已连接 您可以通过创建新的并行线程来计算时间:
final class QueryClass {
private int responseCode = -1;
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if(url == null) {
return null;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000 );
urlConnection.setConnectTimeout(5000 );
Thread thread = new Thread() {
@Override
public void run() {
super.run();
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(responseCode == -1) {
//Perform error message
Intent intent = new Intent(context,ErrorsActivity.class);
intent.putExtra("errorTextMessage",R.string.errorNoInternet);
intent.putExtra("errorImage",R.drawable.no_wifi);
context.startActivity(intent);
}
}
};
thread.start();
urlConnection.connect();
responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
使用ping方法发出警告!这在我测试过的大多数设备上都很好,但在s4mini上却不行。具体是哪个例外?这有时会冻结UI,因为它在UI线程上运行。如果我timeoutConnection=2000,int timeoutSocket=3000;检查问题以改进此答案,我会注意到不能从主线程调用
connect
,也可以setReadTimeout
。这很好,但如果没有internet访问的WiFi连接,则需要很长时间,是否有解决方法?
final class QueryClass {
private int responseCode = -1;
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if(url == null) {
return null;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000 );
urlConnection.setConnectTimeout(5000 );
Thread thread = new Thread() {
@Override
public void run() {
super.run();
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(responseCode == -1) {
//Perform error message
Intent intent = new Intent(context,ErrorsActivity.class);
intent.putExtra("errorTextMessage",R.string.errorNoInternet);
intent.putExtra("errorImage",R.drawable.no_wifi);
context.startActivity(intent);
}
}
};
thread.start();
urlConnection.connect();
responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}