안드로이드 프로그래밍[JAVA Code]/Thread

Thread : 루퍼 를 이용한 message 보내기

훈츠 2019. 12. 5. 15:47
반응형

핸들러 기능은 새로 만든 스레드에서 메인 스레드로 메시지를 전달하는 것이었습니다. 반대로 메인 스레드에서 별도의 새로만든 스레드에 메시지를 전달하는 방법이 필요 할때가 있다. 이를 위해 메인 스레드에서 변수를 선언 하고 별도의 스레드가 그값을 읽어가는 방법을 사용할 수도 있다. 하지만 별도의 스레드가 관리하는 동일한 객체를 여러 스레드가 접근할때는 별도의 스레드 안에 들어있는 메시지 큐를 이용해 순서대로 접근 하도록 만들어야 한다. 마치 메인스레드가 처리하는 것처럼 말이다. 루퍼는 메시지 큐에 들어오는 메시지를 지속적으로 보면서 하나씩 처리하게 된다. 메인 스레드는 UI 객체들을 처리하기 위해 메시지 큐와 루퍼를 사용한다. 그러나 별도의 스레드를 새로 만들었을 때는 루퍼가 없다 따라서 메인 스레드나 다른 스레드에서 메시지 전송 방식으로 스레드에 데이터를 전달한 후 순차적으로 작업을 수행 하고 싶다면 루퍼를 만든 후 실행 해야 한다. 

1) ProcessThread thread; Thread 만들고 루퍼를 준비하고 루프한다.  

ProcessThread thread;

class ProcessThread extends Thread {
	public void run(){
            Looper.prepare();
            Looper.loop();
        }
    }
}

2) ProcessThread 안에 Inner class로 ProcessHandler 를 만들고 객체화 한다. 

    class ProcessThread extends Thread {
        ProcessHandler processHandler = new ProcessHandler();

        public void run(){
            Looper.prepare();
            Looper.loop();

        }

        class ProcessHandler extends Handler {
            String output;
            Bundle bundle;
            public void handleMessage(Message msg){
                output = msg.obj +  "from mainThread";
                bundle = msg.getData();

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

3) Main Activity 에서 ProcessThread 와 기본 Handler 를 선언 후, 객체화 한다. 

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Button button;
    ProcessThread thread;
    Handler handler = new Handler(  );
    EditText editText;

3) 그리고 S/W 누를 때, Main 에서 별도로 정의한 ProcessThread 로 데이터를 전송한다. 전송 방법 2가지 1) bundle 객체 2) Message.obj 에 보내기 obj 에 보낼때는 메시지보내고 그뒤 "" 스티링값을 포함 해야 한다. 

button.setOnClickListener( new View.OnClickListener() {
	@Override
	public void onClick(View v) {
	thread = new ProcessThread();
	thread.start();
	String input = editText.getText().toString();
    //번들에 데이터 담아보내기
	String bundletest = "bundle message";
    Bundle bundle = new Bundle(  );
    bundle.putString( "bundleT",bundletest );
    message.setData( bundle );
	//message obj 이용해서 보내기
    Message message = Message.obtain();
    message.obj = input;
    
    thread.processHandler.sendMessage( message );

	}
} );

4) ProcessThread 에서 메인 UI 로 받은 데이터 보여주기

class ProcessThread extends Thread {
ProcessHandler processHandler = new ProcessHandler();

public void run(){
Looper.prepare();
Looper.loop();

}

class ProcessHandler extends Handler {
	String output;
	Bundle bundle;
	public void handleMessage(Message msg){
	output = msg.obj +  "from mainThread";
	bundle = msg.getData();

	handler.post( new Runnable() {
@Override
public void run() {

	String bundleT  = bundle.getString( "bundleT" );
	textView.setText( output + bundleT );
	Toast.makeText( getApplicationContext(),output , Toast.LENGTH_LONG).show();
	Toast.makeText( getApplicationContext(),bundleT , Toast.LENGTH_LONG).show();
		}
	} );
}

5) 전체 코드 

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Button button;
    ProcessThread thread;
    Handler handler = new Handler(  );
    EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main );
        editText = (EditText) findViewById( R.id.editText );
        textView = (TextView) findViewById( R.id.textView );
        button = (Button) findViewById( R.id.button2 );

        button.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                thread = new ProcessThread();
                thread.start();
                String input = editText.getText().toString();
                String bundletest = "bundle message";
                Bundle bundle = new Bundle(  );
                bundle.putString( "bundleT",bundletest );
                Message message = Message.obtain();
                message.obj = input;
                message.setData( bundle );

                thread.processHandler.sendMessage( message );

            }
        } );


    }

    class ProcessThread extends Thread {
        ProcessHandler processHandler = new ProcessHandler();

        public void run(){
            Looper.prepare();
            Looper.loop();

        }

        class ProcessHandler extends Handler {
            String output;
            Bundle bundle;
            public void handleMessage(Message msg){
                output = msg.obj +  "from mainThread";
                bundle = msg.getData();

                handler.post( new Runnable() {
                    @Override
                    public void run() {

                        String bundleT  = bundle.getString( "bundleT" );
                        textView.setText( output + bundleT );
                        Toast.makeText( getApplicationContext(),output , Toast.LENGTH_LONG).show();
                        Toast.makeText( getApplicationContext(),bundleT , Toast.LENGTH_LONG).show();
                    }
                } );


            }
        }

    }
}

 

반응형

'안드로이드 프로그래밍[JAVA Code] > Thread' 카테고리의 다른 글

Thread - AsyncTask  (0) 2019.12.06
Thread : Runnable & post AlertDialog 박스  (0) 2019.12.05
Thread : information  (0) 2019.12.05
Thread : 스레드 와 핸들러  (0) 2019.12.05