gpt4 book ai didi

java - Android Volley - 检查互联网状态

转载 作者:IT老高 更新时间:2023-10-28 23:16:32 28 4
gpt4 key购买 nike

在我使用 Volley 之前,和往常一样,我使用 AsyncTask 检查我的互联网状态。

这是我在 AsyncTask 中所做的:

private class NetCheck extends AsyncTask<String, Void, Boolean> {

@Override
protected Boolean doInBackground(String... args) {
// get Internet status
return cd.isConnectingToInternet();
}

protected void onPostExecute(Boolean th) {
if (th == true) {
new LoadCategories().execute();
} else {
Toast.makeText(CategoryActivity.this, "Unable to connect to server",
Toast.LENGTH_LONG).show();
}
}
}

这是isConnectingToInternet函数:

public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected())
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) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
return false;
}

如何使用 Volley 实现这一目标?

最佳答案

请求引发了 NoConnection 错误。请在

中捕获错误
   @Override
public void onErrorResponse(VolleyError volleyError) {
String message = null;
if (volleyError instanceof NetworkError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof ServerError) {
message = "The server could not be found. Please try again after some time!!";
} else if (volleyError instanceof AuthFailureError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof ParseError) {
message = "Parsing error! Please try again after some time!!";
} else if (volleyError instanceof NoConnectionError) {
message = "Cannot connect to Internet...Please check your connection!";
} else if (volleyError instanceof TimeoutError) {
message = "Connection TimeOut! Please check your internet connection.";
}
}

关于java - Android Volley - 检查互联网状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21011279/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com