메뉴 건너뛰기

조회 수 348 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

http 나 https 등 웹형식의 네트워크 교신을 할때 쓰레드와 Handler 등으로 다소 복잡한 코딩을 해야 한다.

이때 메인쓰레드에서는 UI를 직접 변경이 불가능하기 때문에 handler 를 통하여 정보를 보내고 이를 다시 받아 처리하는 등의 또다른 작업도 해야한다.

 

Volley 라는 놈은 이러한 쓰레드 작업을 알아서 해주고 자체 메소드 오버라이딩 만으로 웹의 응답처리를 간단히 할 수 있다.

 

 

 

위의 실행화면은 요청하기 버튼을 클릭하면 https://www.google.co.kr 의 웹주소에 Get 방식으로 정보를 요청하고 응답결과를 아래 화면에 텍스트로 출력하는 간단한 예제내용이다.

 

[ AndroidManifest.xml ]

1
2
3
4
<uses-permission android:name="android.permission.INTERNET" />
<application 
...
android:usesCleartextTraffic="true">
cs

 

[ build.gradle ] (app) 

1
2
3
dependencies {
    implementation 'com.android.volley:volley:1.1.0'
}
cs

volley 를 삽입하고, Sync Now 를 눌러 라이브러리를 추가한다.

 

 

[ activity_main.xml ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?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"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <Button
        android:id="@+id/button1"
        android:text="요청하기"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
 
    <ScrollView
        android:id="@+id/scrollView1"
        android:background="#DDD2AF"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                android:id="@+id/textView1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>
        </LinearLayout>
    </ScrollView>
</LinearLayout>
cs

ScrollView 를 넣어서 그안에서 TextView에 응답 내용을 출력하도록 하였다. 

 

 

[ MainActivity.java ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
import com.android.volley.AuthFailureError;
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;
 
import java.util.HashMap;
import java.util.Map;
 
public class MainActivity extends AppCompatActivity {
    Button button1;
    TextView textView1;
 
    static RequestQueue requestQueue;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView1 = findViewById(R.id.textView1);
        button1 = findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestProcess();
            }
        });
 
        // RequestQueue 객체생성
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }
    }
 
    public void requestProcess() {
        String url = "https://www.google.co.kr";
 
        StringRequest request = new StringRequest(
                Request.Method.GET,
                url,
                new Response.Listener<String>() {
                    // 요청을 보내고 응답받았을때
                    @Override
                    public void onResponse(String response) {
                        println("응답 -> " + response);
                    }
                },
                new Response.ErrorListener() {
                    // 요청보내고 에러 발생시에 호출되는 리스너
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        println("에러 -> " + error.getMessage());
                    }
                }
        ) {
            // POST 방식으로 요청할 경우에 전달하는 파라미터값들 지정
            @Override
            protected Map<StringString> getParams() throws AuthFailureError {
                //return super.getParams();
                Map<String,String> params = new HashMap<String,String>();
                return params;
            }
        };
 
        // 캐쉬기능을 끊다. 바로바로 내용처리되도록
        request.setShouldCache(false);
        requestQueue.add(request);
 
    }
 
    public void println(String data) {
        textView1.setText(data + "\n");
    }
}
cs

 

 [ 소스 추가 부연 ]

[ MainActivity.java ] - 소스 보완

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MyRequestQueue";
    static RequestQueue requestQueue;
 
    protected void onCreate(Bundle savedInstanceState) {
        ......
 
        // RequestQueue 객체생성
        if (requestQueue == null) {
            requestQueue = Volley.newRequestQueue(getApplicationContext());
        }
    }
 
    public void requestProcess() {
        ......
 
        // StringRequest 객체의 태그값을 지정
        request.setTag(TAG);
 
        // 캐쉬기능을 끊다. 바로바로 내용처리되도록
        request.setShouldCache(false);
        requestQueue.add(request);
    }
 
    @Override
    protected void onStop() {
        super.onStop();
 
        if (requestQueue != null) {
            // RequestQueue 의 TAG 값으로 지정된 Queue 안의 모든 request들을 취소한다.
            requestQueue.cancelAll(TAG);
        }
    }
}
cs

 


List of Articles
번호 제목 날짜 조회 수
257 Effects - Animate() 메서드 (여러가지 효과 동시 처리) file 2014.10.16 30624
256 안드로이드와 mysql 연동시키기. php 와 json 사용 file 2015.07.16 24488
255 [DB] 서버/클라이언트 소켓 통신하기 2015.07.13 20567
254 월별 캘린더에 일정 입력 및 조회 기능 리스트로 추가하기 file 2015.07.16 18552
253 스토리보드 짜는 방법 file 2015.07.16 15419
252 카카오톡 대화내용 가져오기(sqlite3, chat_logs) file 2016.05.26 15117
251 간단한 mp3 플레이어 만들기 , 음악넣기 , 노래재생 file 2016.06.07 14623
250 TextureView를 이용한 카메라 Preview 좌우 반전 2015.06.10 14212
249 Android Login and Registration with PHP, MySQL and SQLite file 2015.07.16 14178
248 블루투스(Bluetooth) 통신에 대해 알아보자 file 2015.07.26 14047
247 사진찍기 및 앨범 에서 사진 가져오기!!! 2014.08.28 13889
246 EditText의 글자 수 제한 걸기 2015.07.16 13881
245 [DB]Android - DB 연동 기술 정리 2015.07.13 13798
244 노티피케이션(Notification) 사용법 / Notification.Builder , NotificationManager file 2016.06.10 13470
243 안드로이드] 페이스북 같은 슬라이드 메뉴 만들기 file 2015.12.15 12536
242 안드로이드용 채팅프로그램 클라이언트(java), 서버(c#) 소스 file 2016.05.19 11722
241 안드로이드에서 JSP 를 사용하여 mysql 연동하기 2015.07.16 11685
240 WIFI 신호세기 강도 측정하기 2014.08.28 11243
239 블루투스 및 비콘 관련 정리 2015.07.26 10828
238 Android 간단한 회원 가입 폼 만들기 for Mac (PHPMyAdmin 이용) file 2015.07.10 10508
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved