volley 를 한 번 써보려 한다.
gradle, com.android.volley:volley:1.0.0
가장 간단하게 사용하는 방법은 gradle 에 library 를 적어주는 것이다. 물론 이것은 공식적으로 google 에서 지원하는 방법은 아니지만, 누군가 maven repository 에 올려놨고, 이것을 이용하는 것이다. [ref. 1]build.gradle 에
compile 'com.mcxiaoke.volley:library:1.0.18'- compile 'com.android.volley:volley:1.0.0'
를 추가하면 된다.
<project>/app/src/build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "com.namh.volleytest"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.mcxiaoke.volley:library:1.0.18'
}
원래는 이 volley library jar 을 얻기위해 jar 을 만드는 과정을 거친다. 그것은 차후에 이야기 하도록 하고, 여기서는 단순히 사용을 해보자.(당장 궁금하다면, ref. 2 를 참고하자.)
간단한 example
간단한 예제는 ref. 4의 예제를 이용했다.예제는 간단하다. ref. 4 의 code 는 아래 2가지 작업을 구현했다.
- requestQueue 를 만든다.
- request 를 만든다.
- 버튼을 누를때 queue 에 request 를 insert
android.permission.INTERNET
이 작업을 할 때 한가지 주의할 점은 internet 을 사용하기 때문에 아래 permission 을 추가해 줘야 한다.
// AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
일단 이 code 를 build 해서 실행시켜 보면 간단하다. 그냥 우리가 간단한 http request 날리는 작업이랑 같다. 다만 좀 더 복잡한(?) 방법을 통해 이 작업을 하게 된다.
자세한 이야기는 Volley 분석 을 참고하자.
Sources
PodVolleyRequestQueue
package volley;
/**
* Created by namh on 2016-08-20.
*/
import android.content.Context;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
/**
* Custom implementation of Volley Request Queue
*/
public class PodVolleyRequestQueue {
private static PodVolleyRequestQueue mInstance;
private static Context mCtx;
private RequestQueue mRequestQueue;
private PodVolleyRequestQueue(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static PodVolleyRequestQueue getInstance(Context context) {
if (mInstance == null) {
synchronized (PodVolleyRequestQueue.class) {
if (mInstance == null) {
mInstance = new PodVolleyRequestQueue(context);
}
}
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
mRequestQueue = new RequestQueue(cache, network);
// Don't forget to start the volley request queue
mRequestQueue.start();
}
return mRequestQueue;
}
}
PodJsonRequest
package volley;
/**
* Created by namh on 2016-08-20.
*/
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class PodJsonRequest extends JsonObjectRequest {
public PodJsonRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
@Override
public RetryPolicy getRetryPolicy() {
// here you can write a custom retry policy
return super.getRetryPolicy();
}
}
MainActivity
package com.volleyexample;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends ActionBarActivity implements Response.Listener<JSONObject>,
Response.ErrorListener {
public static final String REQUEST_TAG = "MainActivity";
private TextView mTextView;
private Button mButton;
private RequestQueue mQueue;
...
@Override
protected void onStart() {
super.onStart();
mQueue = PodVolleyRequestQueue
.getInstance(this.getApplicationContext())
.getRequestQueue();
String url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk";
final PodJsonRequest jsonRequest = new PodJsonRequest(Request.Method
.GET, url,
new JSONObject(), this, this);
jsonRequest.setTag(REQUEST_TAG);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mQueue.add(jsonRequest);
}
});
}
...
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText(error.getMessage());
}
@Override
public void onResponse(JSONObject response) {
mTextView.setText("Response is: " + response);
try {
mTextView.setText(mTextView.getText() + "\n\n" + ((JSONObject) response).getString
("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
ImageLoader
Reference
- gradle - Android Studio + Volley - Stack Overflow
- Android working with Volley Library
- 개9 블로그 Volley 잘 쓰기,
- Android Volley Example - Truiton
- Sending a Simple Request | Android Developers
댓글 없음:
댓글 쓰기