Android网络通信框架Volley使用技巧汇总(二)

来源:互联网 发布:历史发明家 知乎 编辑:程序博客网 时间:2024/04/30 14:51

通过上一篇文章的阅读,相信大家都对volley的使用技巧都有了不少了解,这篇文章将继续总结Volley另外一些的使用技巧,废话不多说,咱们现在开始。本篇文章主要涉及以下几个方面,

1.使用volley获取IIS状态代码,常用的有200,404,500等等

2.处理volley请求失败的结果处理,避免volley引起程序崩溃

3.将volley管理类应用到项目中,参考Android网络框架Volley(实战篇)


一.使用volley获取IIS状态码

在实际的项目开发中,我们经常需要分析服务器返回的IIS状态码来处理我们相关的业务,那么在volley中,只有状态码为200时,才会进入Response.Listener,按照正确请求处理,所以当我们需要处理其他的状态码的时候,我们要在Response.ErrorListener()中获取IIS状态码,然后进行相关处理,代码很简单只有一句话:

int status = arg0.networkResponse.statusCode;
放在整个Response.ErrorListener中就是:
new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {int status = arg0.networkResponse.statusCode;}}

二.获取volley请求错误信息,避免崩溃.

将volley应用到项目中去,有时候请求如果失败,网络无连接,或者网络异常,都会使volley抛出异常从而使我们的APP崩溃,我们通过 VolleyError类中的error对象,在进入Response.ErrorListener()的时候,取出error.getMessage()与

error.networkResponse,进行判断,从而解决在请求异常的时候不使我们的APP崩溃,Response.ErrorListener()中代码如下所示:

new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.d("error", "LogResponse-------- " + error);if(error.getMessage()!= null){Toast.makeText(getApplicationContext(), "连接异常",     Toast.LENGTH_SHORT).show();}else{if(error.networkResponse ==null ){Toast.makeText(getApplicationContext(), "网络异常",     Toast.LENGTH_SHORT).show();}else{}}}

三.将volley应用到项目中去

既然volley这么好用,简单,那么我们该如何应用到项目中去呢,我们总不能每次请求的时候都新建一个请求队列,然后将我们的请求添加进去,参考文章开头ym的管理类,我们可以继承Application类,在程序初始化的时候创建我们的RequestQueue 请求队列,然后在程序中一句话就可以添加我们的请求,要记得在AndroidManifest.xml中配置这个Application类,先奉上ApplicationController管理类:

import android.app.Application;import android.text.TextUtils;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.VolleyLog;import com.android.volley.toolbox.Volley;public class ApplicationController extends Application {/** * Log or request TAG */public static final String TAG = "VolleyPatterns";/** * Global request queue for Volley */private RequestQueue mRequestQueue;/** * A singleton instance of the application class for easy access in other * places */private static ApplicationController sInstance;@Overridepublic void onCreate() {super.onCreate();// initialize the singletonsInstance = this;}/** * @return ApplicationController singleton instance */public static synchronized ApplicationController getInstance() {return sInstance;}/** * @return The Volley Request queue, the queue will be created if it is null */public RequestQueue getRequestQueue() {// lazy initialize the request queue, the queue instance will be// created when it is accessed for the first timeif (mRequestQueue == null) {// 1// 2synchronized (ApplicationController.class) {if (mRequestQueue == null) {mRequestQueue = Volley.newRequestQueue(getApplicationContext());}}}return mRequestQueue;}/** * Adds the specified request to the global queue, if tag is specified then * it is used else Default TAG is used. *  * @param req * @param tag */public <T> void addToRequestQueue(Request<T> req, String tag) {// set the default tag if tag is emptyreq.setTag(TextUtils.isEmpty(tag) ? TAG : tag);VolleyLog.d("Adding request to queue: %s", req.getUrl());getRequestQueue().add(req);}/** * Adds the specified request to the global queue using the Default TAG. *  * @param req * @param tag */public <T> void addToRequestQueue(Request<T> req) {// set the default tag if tag is emptyreq.setTag(TAG);getRequestQueue().add(req);}/** * Cancels all pending requests by the specified TAG, it is important to * specify a TAG so that the pending/ongoing requests can be cancelled. *  * @param tag */public void cancelPendingRequests(Object tag) {if (mRequestQueue != null) {mRequestQueue.cancelAll(tag);}}}
然后在AndroidManifest.xml中配置ApplicationController类:
    <application        android:name="com.csc.util.ApplicationController" //这一行配置        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.demo.MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application>

最后在我们需要添加请求到请求队列中去的时候只需要一行代码就可以,不用再new RequestQueue了,代码如下:

ApplicationController.getInstance().getRequestQueue().add(stringRequest);


好了,到此我们就总结了常用的一些volley使用方法,我以后会更加频繁的写一些博客,当我遇到问题的时候解决之后,我尽量立马写出博客,因为这样思路最清晰。







0 0