Android Studioにvolleyとvolleyを追加する簡単な使い方

17132 ワード

  • Volleyライブラリ
  • を追加
  • Volleyの簡単な使い方
  • StringRequestとJsonObjectRequest
  • Activityの終了と同時にVolleyネットワーク要求
  • を停止する.
  • ImageRequestの使用
  • ImageLoaderの使用


  • Volleyライブラリの追加
    まず、Volleyのjarパッケージをダウンロードするか、自分でVolleyソースコードをコンパイルする必要があります.Volleyソースコードのダウンロードアドレス:
    https://android.googlesource.com/platform/frameworks/volley/+archive/master.tar.gz
    Android StudioにVolleyソースを追加する例として、Volleyソースをダウンロードした後、それを解凍し、ディレクトリvolley-masterを得る.
    Andorid StudioのメニューFile - New - Import Module...オプションでは、解凍されたディレクトリをmoduleとしてプロジェクトにインポートし、volleyモジュールの名前としてvolley-masterを使用します.
    注意すべき点は、volley-master/build.gradleファイルにvolleyソースコードのコンパイル情報が含まれていることです.以下に示します.
    android {
        compileSdkVersion 22
        buildToolsVersion = '22.0.1'
    }

    ソースコードをコンパイルするために必要なAndroid SDK Build-toolsのバージョンは22.01であり、システムにbuild-toolsがインストールされていることを保証する必要があります.より高いバージョンのbuild-toolsではクラスがいくつか廃棄されているため、高いバージョンのbuild-toolsを使用してコンパイルできません.
    ライブラリとしてインポートするvolley-masterモジュールを選択し、メニューからBuild - Rebuild Projectコンパイルモジュールを選択します.
    コンパイルが完了したら、メニューからFile - Project Structure...を選択するか、ショートカットCtrl+Alt+Shift+Sを押してProject Structureパネルを開き、左側でvolleyフレームワークを使用するmoduleを選択し、右側でDependenciesタブを選択し、右側の緑の をクリックし、3 Module dependencyを選択し、ポップアップウィンドウでvolley-masterモジュールのインポートを選択してからvolleyを使用します.
    Volleyの簡単な使い方
    volleyを使用する前に、まずvolleyのグローバルリクエストキューを作成して、リクエストを管理します.
    アプリケーションクラスにグローバルリクエストキューを作成し、onCreate()メソッドでリクエストキューをインスタンス化し、リクエストキューにgetメソッドを設定します.
    public class MyApplication extends Application {
        //Volley       
        public static RequestQueue sRequestQueue;
    
        /**
         * @return Volley      
         */
        public static RequestQueue getRequestQueue() {
            return sRequestQueue;
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            //   Volley      
            sRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
    }

    次にAndroidManifestにApplicationを登録し、ネットワーク権限を追加します.
    name="android.permission.INTERNET"/>
    <application android:name=".MyApplication"/>

    StringRequestとJsonObjectRequest
    volleyソースコードでは、StringRequestとJsonObjectRequestを例に、volleyにどのようなリクエストがあるかを確認できます.
    JsonObjectRequestは、JSON形式のデータを返す要求を処理し、データ形式がJSON形式でない場合や、要求されたデータの返却形式が不確定な場合にStringRequestを使用する.
    以下にサンプルコードの一部のみを書きます.完全なコードは以下を参照してください.
    https://github.com/VDerGoW/AndroidMain/tree/master/volley-demo/src/main/java/tips/volleytest
    StringRequestの使用例:
  • StringRequestインスタンスを作成し、要求タイプ(GET/POST)要求のURLを入力し、成功したListenerを要求し、失敗したListenerの4つのパラメータを要求する.2つのリスナーは、リクエストが成功したイベントとリクエストが失敗したイベントをそれぞれ処理するインタフェースメソッドを実装する必要があります.
  • StringRequestインスタンスのtagを設定し、そのtagを使用してグローバルキューにアクセスできます.
  • は、StringRequestインスタンスをグローバルキューに追加します.

  • GET方式:
    /**
     * Volley StringRequest    
     * HTTP method : GET
     */
    public void volleyStringRequestDemo_GET() {
    
        //Volley request,  :    ,   URL,       ,       
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url_GET, new Response.Listener() {
            /**
             *        
             * @param response        
             */
            @Override
            public void onResponse(String response) {
                // TODO:       
                Log.i("### onResponse", "GET_StringRequest:" + response);
            }
        }, new Response.ErrorListener() {
            /**
             *        
             * @param error VolleyError
             */
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO:     
                Log.e("### onErrorResponse", "GET_StringRequest:" + error.toString());
            }
        });
    
        // request  tag,   tag        request
        stringRequest.setTag(VOLLEY_TAG);//StringRequestTest_GET
    
        // request      
        MyApplication.getRequestQueue().add(stringRequest);
    }

    POST方式の使用例:
    POST方式ではStringRequestクラスのgetParams()メソッドを実装し,パラメータマッピングを実装する必要がある.
    /**
     * Volley StringRequest    
     * HTTP method : POST
     *        volleyStringRequestDemo_GET()  
     */
    public void volleyStringRequestDome_POST() {
    
        String url = JUHE_API_URL;
    
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener() {
            @Override
            public void onResponse(String response) {
                // TODO:       
                Log.i("### onResponse", "POST_StringRequest:" + response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO:     
                Log.e("### onErrorResponse", "POST_StringRequest:" + error.toString());
            }
        }) {
            /**
             *     POST PUT      Map
             */
            @Override
            protected Map getParams() throws AuthFailureError {
    
                Map paramMap = new HashMap<>();
                // TODO:   POST  
                paramMap.put("postcode", postcode);
                paramMap.put("key", JUHE_APPKEY);
    
                return paramMap;
            }
        };
    
        stringRequest.setTag(VOLLEY_TAG);//StringRequest_POST
    
        MyApplication.getRequestQueue().add(stringRequest);
    }

    JsonObjectRequestの使用例:
    GET方式:
    /**
     * Volley JsonObjectRequest    
     * HTTP method : GET
     *        volleyStringRequestDemo_GET()  
     */
    public void volleyJsonObjectRequestDemo_GET() {
    
        /*
        *      :request   (POST),  null           
        *    GET    ,       URL 
        * */
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url_GET, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                // TODO:       
                Log.i("### onResponse", "GET_JsonObjectRequest:" + response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO:     
                Log.e("### onErrorResponse", "GET_JsonObjectRequest:" + error.toString());
            }
        });
    
        jsonObjectRequest.setTag(VOLLEY_TAG);//JsonObjectRequestTest_GET
    
        MyApplication.getRequestQueue().add(jsonObjectRequest);
    }

    Activityの終了と同時にVolleyネットワークリクエストを停止
    ActivityのoStop()メソッドを上書きし、グローバルキューのcancelAll()メソッドを呼び出し、対応するtagに転送し、ネットワークリクエストをキャンセルします.
    @Override
    protected void onStop() {
        super.onStop();
        // Activity     ,  Activity       
        MyApplication.getRequestQueue().cancelAll(VOLLEY_TAG);
        Log.i("### onStop", "cancel all:tag=" + VOLLEY_TAG);
    }

    ImageRequestの使用
    ImageRequestの使用例:
    public class VolleyImageRequestDemo {
    
        public static final String IMAGE_URL = "https://www.baidu.com/img/bd_logo1.png";
        public static final String VOLLEY_TAG = "tag_volley_image_request";
    
        public void volleyImageRequestDemo(final Callback callback) {
    
            // @param maxWidth : Maximum width to decode this bitmap to, or zero for none
            // @param maxHeight : Maximum height to decode this bitmap to, or zero for none
            // If both width and height are zero, the image will be decoded to its natural size
            ImageRequest imageRequest = new ImageRequest(IMAGE_URL, new Response.Listener() {
                @Override
                public void onResponse(Bitmap response) {
                    //     
    
                    callback.onSuccess(response);
                }
            }, 0, 0, ImageView.ScaleType.FIT_XY, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //     
    
                    Log.i("### onErrorResponse", "ImageRequest:" + error.toString());
                    callback.onError(error);
                }
            });
    
            imageRequest.setTag(VOLLEY_TAG);
    
            MyApplication.getRequestQueue().add(imageRequest);
        }
    
        //            ,            Activity ImageView 
        //         ,   ImageRequest    Activity ,       
        public interface Callback {
            void onSuccess(Bitmap response);
    
            void onError(VolleyError error);
        }
    }

    ImageLoaderの使用
    ImageLoaderを使用するには、まずImageCacheが必要ですので、クラスを定義してImageLoaderを実装します.ImageCacheインタフェース.次にgetBitmap()メソッドとputBitmap()メソッドを実装し、画像を格納するためのLruCacheオブジェクトを構築メソッドでインスタンス化する.
    ImageCacheの例:
    /**
     * Simple cache adapter interface. If provided to the ImageLoader, it
     * will be used as an L1 cache before dispatch to Volley. Implementations
     * must not block. Implementation with an LruCache is recommended.
     */
    public class VolleyBitmapCacheDemo implements ImageLoader.ImageCache {
    
        private LruCache mCache;
    
        public VolleyBitmapCacheDemo() {
            int maxMemorySize = 1024 * 1024 * 10;
            mCache = new LruCache(maxMemorySize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getRowBytes() * bitmap.getHeight();
                }
            };
        }
    
        @Override
        public Bitmap getBitmap(String key) {
            return mCache.get(key);
        }
    
        @Override
        public void putBitmap(String key, Bitmap bitmap) {
            mCache.put(key, bitmap);
        }
    }

    次にActivityでImageLoaderを使用します.
    ImageLoader imageLoader = new ImageLoader(MyApplication.getRequestQueue(), new VolleyBitmapCacheDemo());
    ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(mLoaderImage, R.mipmap.ic_launcher,R.mipmap.ic_launcher);
    imageLoader.get(IMAGE_URL, imageListener);

    完全なサンプルコードは以下を参照してください.
    https://github.com/VDerGoW/AndroidMain/tree/master/volley-demo/src/main/java/tips/volleytest