Google开源库之Volley的初步介绍

本文介绍了Volley网络请求库的基本用法,包括如何进行JSON字符串请求和异步加载图片。Volley是Google推出的一款轻量级网络通信库,适用于数据量不大但通信频繁的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Volley是Google在2013年推出的网络请求库,在现在APP普遍与网络交互的现在,volley和http通信技术成为十分重要的技术。volley可以让网络铜芯线更快,更简单,更健壮。volley适合数据量不大但通信频繁的场景,先看volley的使用方法。
RequestQueue mRequestQueue = Volley.newRequestQueue(context);
JsonObjectRequest req = new JsonObjectRequest(URL, null,
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });
mRequestQueue.add(req);

volley提供的功能大概有以下几点:

  1. 异步获得JSON的键值对,或者图片等
  2. 网络Request的排序
  3. Request优先级处理
  4. 缓存
  5. 多级别的取消请求
  6. 与Activity生命周期联动

volley的核心有两点:

  • RequestQueue
  • Request

下面通过demo来展示volley的用法

package com.example.doqin.update;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getJSONVolley();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //获得JSON字符串
    public void getJSONVolley() {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = "";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        System.out.println("response=" + response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("error");
            }
        });
        requestQueue.add(jsonObjectRequest);
    }
}

以上就是使用Volley做JSON字符串的请求,注意Internet权限的添加。
下面介绍Volley的第二个用法,异步加载图片。

package com.example.doqin.update;

import android.graphics.Bitmap;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.LruCache;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;


public class MainActivity extends ActionBarActivity {

    private ImageView iv1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        iv1 = (ImageView) findViewById(R.id.id_progress);
        getJSONVolley();
        loadImageVolley();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //获得JSON字符串
    public void getJSONVolley() {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = "";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        System.out.println("response=" + response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("error");
            }
        });
        requestQueue.add(jsonObjectRequest);
    }

    //异步加载图片
    public void loadImageVolley() {
        String url = "";
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        //缓存操作,返回图片Bitmap
        final LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(20);
        ImageCache imageCache = new ImageCache() {
            @Override
            public Bitmap getBitmap(String key) {
                return lruCache.get(key);
            }

            @Override
            public void putBitmap(String key, Bitmap bitmap) {
                lruCache.put(key,bitmap);
            }
        };
        ImageLoader imageLoader = new ImageLoader(requestQueue,imageCache);
        ImageLoader.ImageListener listener = ImageLoader.getImageListener(iv1,R.drawable.abc_btn_default_mtrl_shape,R.drawable.abc_btn_borderless_material);
        imageLoader.get(url,listener);
    }
}

RequestQueue

RequestQueue是一个请求队列,负责分发请求,取缓存或者读网络,所以其构造函数中需要一个Cache对象和一个Network对象,还有一个ResponseDlivery对象用于派发请求结果。
新建RequestQueue后要条用它的start方法,在start中会新建一个CacheDispatcher和几个NetworkDispatcher分别处理缓存与网络请求。
通过RequestQueue的add方法添加请求。

JsonObjectRequest

讲请求结果解析成JSONObject。

JSONArrayRequest

将请求结果解析成JSONArray。

Cancel

通过给每个请求设置一个Tag,然后通过cancelAll(final Object tag)就可以取消对应Tag的请求,也可以直接使用RequestFilter。

以上就是我看到的一些基本的Volley方法,原文更详细的介绍Volley的用法

明天争取写完Volley的兄弟框架 Android-Async-Http,个人觉得后者的用法更为广泛一点。

PS/今天晚上TI5的外卡赛开始了哦,VG加油,NewBee加油!
2015-7-26-0.04

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值