티스토리 뷰

새로 생성한 스레드에서 메인 스레드로 데이터를 넘기는 건 Handler 객체의 메시지 큐와 Runnable 객체를 사용하여 실습해봤지만, 그 반대의 경우도 가능하다. 메인 스레드에서 변수를 선언하고 별도의 스레드가 그 값을 읽어가는 방법을 사용할 수 있다. 

 

하지만 별도의 스레드가 관리하는 동일한 객체를 여러 스레드가 접근할 경우 예외가 발생할 수 있기 때문에 별도의 스레드 안에 들어있는 메시지 큐를 이용해 순서대로 접근하도록 만들어야 한다. 

 

핸들러는 메시지 큐를 Looper를 사용하여 처리한다.

 

Looper는 메시지 큐에 들어오는 메시지를 지속적으로 확인하면서 하나씩 처리하게 된다. 

 

바로 한번 확인해보자.


◎MainActivity.java

package com.example.samplelooper;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.health.ProcessHealthStats;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {
    EditText editText;
    TextView textView;

    Handler handler = new Handler(Looper.getMainLooper());

    ProcessThread thread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);

        Button button = findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String input = editText.getText().toString();

                // Message 객체 참조
                Message message = Message.obtain();

                // Message Queue 에 데이터 삽입
                message.obj = input;

                thread.processHandler.handlerMessage(message);
            }
        });

        thread = new ProcessThread();
    }

    class ProcessThread extends Thread {

        ProcessHandler processHandler = new ProcessHandler();

        public void run() {
            // Thread 에서 Looper를 참조할 수 있게 init
            Looper.prepare();

            // 이 Thread 에서 Message Queue 를 Run
            Looper.loop();
        }

        class ProcessHandler extends Handler{
            public void handlerMessage(Message msg) {
                final String output = msg.obj + " from thread";

                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText(output);
                    }
                });
            }
        }
    }
}

'Mobile > Android' 카테고리의 다른 글

[Android] Thread로 애니메이션 만들기  (0) 2022.04.08
[Android] AsyncTask  (0) 2022.04.07
[Android] Runnable 2: postDelayed  (0) 2022.04.06
[Android] Runnable  (0) 2022.04.06
[Android] Thread & Handler  (0) 2022.04.05
Comments