Java 安卓截击-检查互联网状态
和往常一样,在使用截击之前,我使用AsyncTask检查我的internet状态 以下是我在AsyncTask中所做的工作:Java 安卓截击-检查互联网状态,java,android,android-volley,Java,Android,Android Volley,和往常一样,在使用截击之前,我使用AsyncTask检查我的internet状态 以下是我在AsyncTask中所做的工作: private class NetCheck extends AsyncTask<String, Void, Boolean> { @Override protected Boolean doInBackground(String... args) { // get Internet status return
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();
}
}
}
如何使用截击来实现此目的?使用此代码检查internet状态:
public class Internet {
private Context context;
public Internet(Context context) {
this.context = context;
}
public Boolean Check() {
ConnectivityManager cn = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf != null && nf.isConnected() == true) {
return true;
} else {
Toast.makeText(context, "No internet connection.!",
Toast.LENGTH_LONG).show();
return false;
}
}
}
请求没有引发任何连接错误。请把错误记录下来
@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.";
}
}
我使用以下代码来检测发生的错误:
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(), "Communication Error!", Toast.LENGTH_SHORT).show();
} else if (error instanceof AuthFailureError) {
Toast.makeText(getApplicationContext(), "Authentication Error!", Toast.LENGTH_SHORT).show();
} else if (error instanceof ServerError) {
Toast.makeText(getApplicationContext(), "Server Side Error!", Toast.LENGTH_SHORT).show();
} else if (error instanceof NetworkError) {
Toast.makeText(getApplicationContext(), "Network Error!", Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
Toast.makeText(getApplicationContext(), "Parse Error!", Toast.LENGTH_SHORT).show();
}
}
});
我设法在应用课上上网
public class App extends Application {
private static final String TAG = "MyApp";
private static App mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
public static synchronized App getInstance() {
return mInstance;
}
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
if(CommonUtills.isNetworkAvailable(getApplicationContext())) {
req.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
req.setTag(TAG);
getRequestQueue().add(req);
}
else
{
Toast.makeText(getApplicationContext(), "Unable to
connect to server",Toast.LENGTH_LONG).show();
}
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
所以在调用每个请求之前,如果互联网可用,它将被执行
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(), "No Connection/Communication Error!", Toast.LENGTH_SHORT).show();
} else if (volleyError instanceof AuthFailureError) {
Toast.makeText(getApplicationContext(), "Authentication/ Auth Error!", Toast.LENGTH_SHORT).show();
} else if (volleyError instanceof ServerError) {
Toast.makeText(getApplicationContext(), "Server Error!", Toast.LENGTH_SHORT).show();
} else if (volleyError instanceof NetworkError) {
Toast.makeText(getApplicationContext(), "Network Error!", Toast.LENGTH_SHORT).show();
} else if (volleyError instanceof ParseError) {
Toast.makeText(getApplicationContext(), "Parse Error!", Toast.LENGTH_SHORT).show();
}
}
});
这对作为开发人员的您有好处。但不要向最终用户显示一些此类直接消息,如身份验证和服务器端错误。要有创意,并表现出此时无法连接的样子。这就是我发出截击请求并处理响应和错误的方式,您不需要为此添加异步任务,而是在后端发出截击请求
StringRequest strReq = new StringRequest(Request.Method.POST, "your_url", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// handle your response here
// if your response is a json then create json object and use it
try {
JSONObject jsonObject = new JSONObject(response);
// now you can get values from your jsonObject
}
catch (Exception e){}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
String message = null; // error message, show it in toast or dialog, whatever you want
if (volleyError instanceof NetworkError || volleyError instanceof AuthFailureError || volleyError instanceof NoConnectionError || volleyError instanceof TimeoutError) {
message = "Cannot connect to Internet";
} else if (volleyError instanceof ServerError) {
message = "The server could not be found. Please try again later";
} else if (volleyError instanceof ParseError) {
message = "Parsing error! Please try again later";
}
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("key","value"); // put your params here
return new JSONObject(params).toString().getBytes();
}
@Override
public String getBodyContentType() {
return "application/json";
}
};
// Adding String request to request queue
Volley.newRequestQueue(getApplicationContext()).add(strReq);
StringRequest strReq=newstringrequest(Request.Method.POST,“您的url”,newresponse.Listener()){
@凌驾
公共void onResponse(字符串响应){
//在这里处理你的回答
//如果您的响应是json,那么创建json对象并使用它
试一试{
JSONObject JSONObject=新JSONObject(响应);
//现在您可以从jsonObject获取值
}
捕获(例外e){}
}
},new Response.ErrorListener(){
@凌驾
公共错误响应(截击错误截击错误){
String message=null;//错误消息,请在toast或dialog中显示,随您所需
if(网络错误的截击错误实例| | |身份验证失败错误的截击错误实例| | |无连接错误的截击错误实例| |超时错误的截击错误实例){
message=“无法连接到Internet”;
}else if(服务器错误的截击错误实例){
message=“找不到服务器,请稍后再试”;
}else if(截击错误实例解析错误){
message=“分析错误!请稍后再试”;
}
}
}) {
@凌驾
公共字节[]getBody()抛出AuthFailureError{
HashMap params=新的HashMap();
put(“key”,“value”);//将参数放在这里
返回新的JSONObject(params.toString().getBytes();
}
@凌驾
公共字符串getBodyContentType(){
返回“application/json”;
}
};
//向请求队列添加字符串请求
newRequestQueue(getApplicationContext()).add(streq);
在android manifest.xml中添加权限:是的,您可以在启动AsynTask之前使用此代码检查internet连接,但我不想使用AsyncTask。可以用截击代替吗?是的,可以。如果要将图像从服务器加载到列表视图,可以使用smartImageView:hi请查看。希望它能解释你想做什么,我确实认为你可以按照我的回答中给出的方法来做。我觉得它真的很好,很合适。这是不一样的。NoConnectionError不仅在没有网络连接时抛出,而且在无法与主机建立连接时抛出(例如,如果无法解析主机)。由于NoConnectionError
扩展了NetworkError
,因此您永远不会点击if(NoConnectionError的截击错误实例){
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(), "No Connection/Communication Error!", Toast.LENGTH_SHORT).show();
} else if (volleyError instanceof AuthFailureError) {
Toast.makeText(getApplicationContext(), "Authentication/ Auth Error!", Toast.LENGTH_SHORT).show();
} else if (volleyError instanceof ServerError) {
Toast.makeText(getApplicationContext(), "Server Error!", Toast.LENGTH_SHORT).show();
} else if (volleyError instanceof NetworkError) {
Toast.makeText(getApplicationContext(), "Network Error!", Toast.LENGTH_SHORT).show();
} else if (volleyError instanceof ParseError) {
Toast.makeText(getApplicationContext(), "Parse Error!", Toast.LENGTH_SHORT).show();
}
}
});
StringRequest strReq = new StringRequest(Request.Method.POST, "your_url", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// handle your response here
// if your response is a json then create json object and use it
try {
JSONObject jsonObject = new JSONObject(response);
// now you can get values from your jsonObject
}
catch (Exception e){}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
String message = null; // error message, show it in toast or dialog, whatever you want
if (volleyError instanceof NetworkError || volleyError instanceof AuthFailureError || volleyError instanceof NoConnectionError || volleyError instanceof TimeoutError) {
message = "Cannot connect to Internet";
} else if (volleyError instanceof ServerError) {
message = "The server could not be found. Please try again later";
} else if (volleyError instanceof ParseError) {
message = "Parsing error! Please try again later";
}
}
}) {
@Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("key","value"); // put your params here
return new JSONObject(params).toString().getBytes();
}
@Override
public String getBodyContentType() {
return "application/json";
}
};
// Adding String request to request queue
Volley.newRequestQueue(getApplicationContext()).add(strReq);