카테고리 없음

[안드로이드/android] 스레드(Thread) 사용하기

냠냠:) 2020. 7. 21. 23:13

Thread란?

우리는 웹 페이지를 보면서, 앱을 사용하면서 동시에 하나의 기능만을 사용하지 않는다. 동시에 여러 버튼을 눌러 응답을 받을 수 있고, 동시에 다양한 서비스를 받을 수 있다. 이렇게 동시에 다양한 일을 가능하게 해주는 것이 Thread이다. 마치 밥솥에 밥을 올려놓고 식탁에 수저를 놓는 것처럼 하나의 일이 끝날 때까지 기다리지 않는다.

 

Thread의 필요성

안드로이드 프로젝트를 하면서 우리는 우리가 구축한 서버와의 데이터 통신, 오픈 API를 이용해 데이터 통신하는 경우가 있다. 그럴 때마다 서버의 응답이 올 때까지 기다려야 한다면 앱은 사용자에게 다른 서비스를 지원못함은 물론이고 똑같은 화면을 응답이 올 때까지 보여줘야 한다. 그렇게 때문에 Thread를 이용해 서버와의 통신은 백그라운드 작업으로 돌려야 하는 것이다. 

 

 

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
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
35
36
37
38
39
40
41
42
43
44
45
46
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
 
public class MainActivity extends AppCompatActivity {
    TextView test;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        test = findViewById(R.id.test);
 
        new Thread(){
            @Override
            public void run() {
                String s = "Test Word";
                //서버와의 통신 또는 api 작업 등등
 
                Bundle Bundle = new Bundle();
                Bundle.putString("testWord", s);
 
                Message msg = handler.obtainMessage();
                msg.setData(Bundle);
                handler.sendMessage(msg);
            }
        }.start();
    }
 
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            String testWord = bundle.getString("testWord");
            test.setText(testWord);
        }
    };
}
 
cs
  • new Thread() 로 스레드를 만들어주고 run() 함수를 오버라이드해서 그 내부에 스레드 작업을 작성해주면 된다.
  • 작업 후 나온 결과 데이터들을 Bundle에 담아 Message에 setData를 통해 넣어주고
  • Handler를 통해 실제 메인 뷰에 데이터를 뿌려주면 된다.

핸들러를 사용해야하는 이유 : 안드로이드에서는 UI를 변경하려면 꼭 Main에서 변경해야 한다. 이게 무슨 소리냐면 UI에 setText 등의 기능을 사용하려면 메인 스레드가 도는 main(), 여기에서는 onCreate에서만 가능하단 소리다.
하지만 핸들러(Handler)를 사용하면 스레드에서 끝난 작업을 핸들러를 이용해 UI를 변경할 수 있기 때문에 Handler 내부에서 UI를 변경해주면 된다.

 

 

이외에도 join, Looper 등의 개념도 있다. 이 부분은 나중에 한번에 개념 정리할 때 적어봐야겠다.

반응형