Android Volley開源框架的使用

一、Android Volley 開源框架的使用

2013年Google I/O大會上推出了一個新的網絡通信框架——Volley。它既可以像AsyncHttpClient一樣非常簡單地進行HTTP通信,也可以像Universal-Image-Loader一樣輕鬆加載網絡上的圖片。

除了簡單易用之外,Volley在性能方面也進行了大幅度的調整,它的設計目標就是非常適合去進行數據量不大,但通信頻繁的網絡操作,而對於大數據量的網絡操作,比如說下載文件等,Volley的表現就會非常糟糕。

1、Volley ImageRequest 加載網絡圖片示例
** 此方法已經棄用,隨便了解下

(1)在AS中添加依賴庫 implementation 'com.mcxiaoke.volley:library:1.0.19'
(2)XML 佈局文件只有一個Button 、一個ImageView 較簡單此處省略
(3)MainActivity.java文件如下

public class MainActivity extends Activity {

    private Button imgRequest;
    private ImageView imageView;
    private Volley volley;
    private RequestQueue requestQueue;
    private String imgUrl = "http://pic33.nipic.com/20131007/13639685_123501617185_2.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestQueue = volley.newRequestQueue(MainActivity.this);    //初始化請求隊列

        imageView = findViewById(R.id.image);
        imgRequest = findViewById(R.id.btn1);
        imgRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                 //ImageRequest構造函數需要6個參數
                 ImageRequest imageRequest = new ImageRequest(imgUrl, new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap bitmap) {
                        imageView.setImageBitmap(bitmap);
                    }
                }, 0, 0, Bitmap.Config.ARGB_8888, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
                 requestQueue.add(imageRequest);     //將請求添加到請求隊列裏面
            }
        });
    }
}

在這裏插入圖片描述

2、Volley ImageLoader 加載網絡圖片示例
ImageLoader 加載圖片並實現緩存,界面很簡單,一個Button + ImageView。添加依賴庫同上,直接上代碼。
(1)佈局XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="imageLoader" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/image"/>

</LinearLayout>

(2)MainActivity.java代碼

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity" ;
    private Button btnImg;
    private ImageView imageView;
    private Volley volley;
    private RequestQueue requestQueue;
    private String imgUrl = "http://pic33.nipic.com/20131007/13639685_123501617185_2.jpg";
    private MyImageCache myImageCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestQueue = volley.newRequestQueue(MainActivity.this);
        myImageCache = new MyImageCache();

        imageView = findViewById(R.id.image);
        btnImg = findViewById(R.id.btn1);

        btnImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ImageLoader imageLoader = new ImageLoader(requestQueue, myImageCache);
                ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(imageView,
                        R.drawable.moren,R.drawable.cuowu);     //圖片控件、默認圖片、錯誤圖片
                imageLoader.get(imgUrl,imageListener);
            }
        });
    }
}   

 class MyImageCache implements ImageLoader.ImageCache {   //自定義緩存類

    private static final String TAG = "MyImageCache";
    private LruCache<String,Bitmap> lruCache;     //lru 最近最少使用算法

    public MyImageCache(){
        int maxSize = 10 * 1024 * 1024;  //最大爲10M
        lruCache = new LruCache<String, Bitmap>(maxSize){
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight();   //得到圖片的size
            }
        };
    }

    @Override
    public Bitmap getBitmap(String url) {
        Bitmap bitmap = lruCache.get(url);
        if (bitmap == null){
            Log.e(TAG,"getBitmap failed bitmap == null");
        }else {
            Log.e(TAG,"getBitmap success bitmap != null");
        }
        return bitmap;   //從緩存中拿到圖片
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        if (bitmap == null){
            Log.e(TAG,"putBitmap failed bitmap == null");
        }else {
            Log.e(TAG,"putBitmap success bitmap != null");
        }
         lruCache.put(url,bitmap);     //如果緩存中沒有,從網絡拿
    }
}

首次運行肯定拿不到緩存圖片,因此會打印 getBitmap failed bitmap == null , 接着從網絡拿圖片
putBitmap success bitmap != null ,後面再點擊button的時候都會從緩存拿圖片,將打印
getBitmap success bitmap != null 。

08-27 04:07:16.638 14236-14236/com.nxyuntui.mapyuntui E/MyImageCache: getBitmap failed bitmap == null
08-27 04:07:16.944 14236-14236/com.nxyuntui.mapyuntui E/MyImageCache: putBitmap success bitmap != null
08-27 04:07:42.281 14236-14236/com.nxyuntui.mapyuntui E/MyImageCache: getBitmap success bitmap != null
08-27 04:07:44.233 14236-14236/com.nxyuntui.mapyuntui E/MyImageCache: getBitmap success bitmap != null

3、Volley NetworkImageView 加載網絡圖片示例
在上面兩個步驟的基礎上,學習NetworkImageView加載網絡圖片,較簡單。
(1)MainActivity.java

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity" ;
    private Button netImg;
    private NetworkImageView imageView;    //定義NetworkImageView 組件
    private Volley volley;
    private RequestQueue requestQueue;
    private String imgUrl = "http://pic33.nipic.com/20131007/13639685_123501617185_2.jpg";
    private MyImageCache myImageCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        requestQueue = volley.newRequestQueue(MainActivity.this);
        myImageCache = new MyImageCache();     //MyImageCache 類同上

        imageView = findViewById(R.id.netImage);
        netImg = findViewById(R.id.btn1);

        netImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ImageLoader imageLoader = new ImageLoader(requestQueue, myImageCache);
                imageView.setDefaultImageResId(R.drawable.moren);
                imageView.setErrorImageResId(R.drawable.cuowu);
                imageView.setImageUrl(imgUrl,imageLoader);
            }
        });
    }
}

(2)佈局XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="netImagview" />

    <com.android.volley.toolbox.NetworkImageView      // NetworkImageView控件
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/netImage"/>

</LinearLayout>

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章