728x90

안드로이드 발리는 사용하기 매우 편리한 http라이브러리이다.

이를 무조건 추천하지 않는게 deprecated됬으므로 언젠가는 사라지게될 라이브러리라는 것이다.

하지만 아직은 가볍게 하기에 좋은 라이브러리 생각되어서 여러분에게 설명하려고한다.


발리의 특징은 비동기식이다. 기본이 비동기식이므로 이벤트큐에 넣는 방식으로 사용한다.

그리고 사용하기 쉽다. 이게 발리의 특징이다.

이제 발리로 get을 받아오는 예제를 해보도록 하자.



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.theceres.volleytest">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

<uses-permission android:name="android.permission.INTERNET" />
</manifest>

먼저 manifests를 수정하도록 하자. 아래에 user-permission으로 INTERNET퍼미션을 열어준다.


또한 build.gradle에들어가서 volley를 의존성(dependencies)에 추가시켜 준다.

라이브러리는 maven repository에서 찾자.


volley를 검색하자.


그러면 위와같이 선택할 수있다.

이제 gradle에 위와 같이 추가해준다.


apply plugin: 'com.android.application'

android {
compileSdkVersion 27
defaultConfig {
applicationId "net.theceres.volleytest"
minSdkVersion 23
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

// https://mvnrepository.com/artifact/com.android.volley/volley
compile group: 'com.android.volley', name: 'volley', version: '1.0.0'
}

dependecies에 마지막 한줄로 추가하면된다.


그레이들이 변경되면 위에 싱크할지 물어보는데 싱크를 해준다.

이제 테스트 화면을 보여줄 액티비티를 가볍게 구성하자.


위와같이 간단히 만들자. get을 받아서 화면에 뿌려줄 것이다.


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

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is text."
android:id="@+id/tvMain"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>

xml은 위와 같이 만들었다.

그럼 동작하는 코드를 보자.


package net.theceres.volleytest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
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 com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MAIN";
private TextView tv;
private RequestQueue queue;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tvMain);
queue = Volley.newRequestQueue(this);
String url = "http://www.google.com";

StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
tv.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
});

stringRequest.setTag(TAG);
queue.add(stringRequest);
}

@Override
protected void onStop() {
super.onStop();
if (queue != null) {
queue.cancelAll(TAG);
}
}
}

코드는 처음 보면 복잡할 수 있지만 사실 복잡한 코드는 아니다. 

몇가지를 보도록하자.


private RequestQueue queue;
queue = Volley.newRequestQueue(this);

queue.add(stringRequest);

발리는 작업을 큐에 넣어서 동작한다.

위의 과정은 우리가 내내 사용할 request queue를 만들고 그 안에 우리가 할 작업을 넣는것이다.

작업을 넣기만 하면 알아서 큐가 동작시킨다.

그래서 쉽다는 것이다.

그럼 우리가할 동작을 보도록하자.


StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
tv.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
});

stringRequest.setTag(TAG);

이제 요청객체를 만들자. 일단 요청을 문자열로 받도록 해보자. 그러려면 StringRequest로 만들어야한다.

그리고 첫번째 인자로 request타입을, 두번째 인자로 url을 , 세번째 인자로 성공했을 시의 작업을, 네번째 인자로 실패했을시의 작업을 넣는다.

우리는 성공했을때 텍스트뷰에 get요청을 뿌려줄 것이다.




실행해보면 구글에서 받아온 화면의 html을 뿌려주는것을 볼 수 있다.


+ Recent posts