標籤:android 架構
1. 架構特點
(1). 通訊更快,更簡單
(2). Get、Post網路請求及網狀圖像的高效率非同步處理請求
(3). 排序
(4). 網路請求的緩衝
(5). 多層級取消請求
(6). 和Activity生命週期的聯動
缺點:不適合上傳和下載
優點:高效的Get/Post方式的資料請求互動,網狀圖片載入和緩衝,是Google官方推出的架構,效能很穩定和強勁。
2. 網路資料請求
(1). 使用Get方式請求資料
建立Application類:
<span style="white-space:pre"></span>public class MyApplication extends Application {public static RequestQueue queues;@Overridepublic void onCreate() {super.onCreate();queues = Volley.newRequestQueue(getApplicationContext());}public static RequestQueue getHttpQueues() {return queues;}}使用StringRequest測試GET請求:
<span style="white-space:pre"></span>private void volleyGetStringReuest() {String url = "http://apis.juhe.cn/mobile/get?phone=13689249616&key=d83212f9ca3a6028fa0d7d77a3ff3bf8";// 建立請求對象StringRequest request = new StringRequest(Method.GET, url,new Listener<String>() {// 請求成功時調用@Overridepublic void onResponse(String arg0) {Toast.makeText(MainActivity.this, arg0, 0).show();}}, new Response.ErrorListener() {// 請求失敗時調用@Overridepublic void onErrorResponse(VolleyError arg0) {Toast.makeText(MainActivity.this, arg0.toString(), 0).show();}});request.setTag("abcGet");MyApplication.getHttpQueues().add(request);}使用JsonObjectRequest測試GET請求:
private void volleyGetJsonObjectReuest() {String url = "http://apis.juhe.cn/mobile/get?phone=13689249616&key=d83212f9ca3a6028fa0d7d77a3ff3bf8";// 建立請求對象JsonObjectRequest request = new JsonObjectRequest(Method.GET, url,null, new Listener<JSONObject>() {// 請求成功@Overridepublic void onResponse(JSONObject arg0) {Toast.makeText(MainActivity.this, arg0.toString(), 0).show();}}, new Response.ErrorListener() {// 請求失敗@Overridepublic void onErrorResponse(VolleyError arg0) {Toast.makeText(MainActivity.this, arg0.toString(), 0).show();}});request.setTag("abcGet");MyApplication.getHttpQueues().add(request);}(2). 使用Post請求資料
使用StringRequest測試POST請求:
private void volleyStringRequestPost() {String url = "http://apis.juhe.cn/mobile/get?";StringRequest request = new StringRequest(Method.POST, url,new Listener<String>() {@Overridepublic void onResponse(String arg0) {Toast.makeText(MainActivity.this, arg0, 0).show();}}, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {Toast.makeText(MainActivity.this, arg0.toString(), 0).show();}}) {@Overrideprotected Map<String, String> getParams() throws AuthFailureError {Map<String, String> map = new HashMap<String, String>();map.put("phone", "13002909620");map.put("key", "d83212f9ca3a6028fa0d7d77a3ff3bf8");return map;}};request.setTag("abcGet");MyApplication.getHttpQueues().add(request);}
3. Volley與Activity聯動
(1). Volley與Activity的聯動
覆寫onStop方法:
@Overrideprotected void onStop() {super.onStop();MyApplication.getHttpQueues().cancelAll("abcGet");}(2). Volley的二次回調封裝
首先要建立一個抽象類別VolleyInterface:
public abstract class VolleyInterface {public Context mContext;public Listener<String> mListener;public ErrorListener mErrorListener;public abstract void onMySuccess(String result);public abstract void onMyError(VolleyError error);public VolleyInterface(Context context, Listener<String> listener,ErrorListener errorListener) {mContext = context;mListener = listener;mErrorListener = errorListener;}public Listener<String> loadingListener() {mListener = new Listener<String>() {@Overridepublic void onResponse(String arg0) {onMySuccess(arg0);}};return mListener;}public ErrorListener errorListener() {mErrorListener = new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {onErrorResponse(arg0);}};return mErrorListener;}}
然後建立一個類,自訂我們的GET和POST請求:
public class VolleyRequest {public static StringRequest stringRequest;public static Context context;/** * 自訂GET * * @param context * @param url * @param tag * @param vif */public static void requestGet(Context context, String url, String tag,VolleyInterface vif) {MyApplication.getHttpQueues().cancelAll(tag);stringRequest = new StringRequest(Method.GET, url,vif.successListener(), vif.errorListener());stringRequest.setTag(tag);MyApplication.getHttpQueues().add(stringRequest);MyApplication.getHttpQueues().start();}/** * 自訂POST * * @param context * @param url * @param tag * @param params * @param vif */public static void requestPost(Context context, String url, String tag,final Map<String, String> params, VolleyInterface vif) {MyApplication.getHttpQueues().cancelAll(tag);stringRequest = new StringRequest(Method.POST, url,vif.successListener(), vif.errorListener()) {@Overrideprotected Map<String, String> getParams() throws AuthFailureError {return params;}};stringRequest.setTag(tag);MyApplication.getHttpQueues().add(stringRequest);MyApplication.getHttpQueues().start();}}修改測試的代碼:
/** * 自訂get方式 */private void myGet() {String url = "http://apis.juhe.cn/mobile/get?phone=13689249616&key=d83212f9ca3a6028fa0d7d77a3ff3bf8";VolleyRequest.requestGet(this, url, "abcGet", new VolleyInterface(this,VolleyInterface.mListener, VolleyInterface.mErrorListener) {@Overridepublic void onMySuccess(String result) {Toast.makeText(MainActivity.this, result, 0).show();}@Overridepublic void onMyError(VolleyError error) {Toast.makeText(MainActivity.this, error.toString(), 0).show();}});}這樣做的好處是:我們可以在VolleyInterface中寫好功和失敗的兩種處理方式,這樣在每一個調用者都可以使用。
關於Post我就不做測試了。
4. 擷取網狀圖片
(1). 使用ImageRequest擷取網狀圖片
public class ImageActivity extends Activity {private ImageView imageView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_image);initView();String url = "https://www.baidu.com/img/bdlogo.png";// 寬和高指定0和0就會以原圖的方式載入ImageRequest request = new ImageRequest(url, new Listener<Bitmap>() {@Overridepublic void onResponse(Bitmap arg0) {imageView.setImageBitmap(arg0);}}, 0, 0, Config.RGB_565, new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError arg0) {imageView.setImageResource(R.drawable.ic_launcher);}});MyApplication.getHttpQueues().add(request);}private void initView() {imageView = (ImageView) findViewById(R.id.image);}}
(2). 使用ImageLoader和ImageListener緩衝網路圖片
建立BitmapCache類:
public class BitmapCache implements ImageCache {public LruCache<String, Bitmap> cache;public int max = 10 * 1024 * 1024;public BitmapCache() {cache = new LruCache<String, Bitmap>(max) {@Overrideprotected int sizeOf(String key, Bitmap value) {return value.getRowBytes() * value.getHeight();}};}@Overridepublic Bitmap getBitmap(String arg0) {return cache.get(arg0);}@Overridepublic void putBitmap(String arg0, Bitmap arg1) {cache.put(arg0, arg1);}}調用測試:
private void testImageLoader(String url) {ImageLoader loader = new ImageLoader(MyApplication.getHttpQueues(),new BitmapCache());ImageListener listener = ImageLoader.getImageListener(imageView,R.drawable.ic_launcher, R.drawable.ic_launcher);loader.get(url, listener, 0, 0);}(3). 使用ImageLoader和NetworkImageView載入圖片:
private void testNetworkImageView(String url) {ImageLoader loader = new ImageLoader(MyApplication.getHttpQueues(),new BitmapCache());netImageView.setDefaultImageResId(R.drawable.ic_launcher);netImageView.setErrorImageResId(R.drawable.ic_launcher);netImageView.setImageUrl(url, loader);}
源碼下載
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【Android進階】(2)使用開源架構Volley