2016년 5월 9일 월요일

Handler 테스트

내부클래스, 외부 클래스, 멤버객체를 사용하는 방법 테스트

1. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.falcon.mythreadtest1.MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="메인스레드값"
        android:id="@+id/tvMainValue"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="24dp" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="작업스레드값"
        android:id="@+id/tvBackValue"
        android:layout_below="@+id/tvMainValue"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="73dp" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="메인스레드증가"
        android:id="@+id/btnMainIncrease"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

2. MainActivity.java
package com.example.falcon.mythreadtest1;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    SendMessageHandler mHandler;
    int mainValue = 0;
    int backValue = 0;
    TextView tvMainValue;
    TextView tvBackValue;
    Button btnMainIncrease;

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

        tvMainValue = (TextView) findViewById(R.id.tvMainValue);
        tvBackValue = (TextView) findViewById(R.id.tvBackValue);
        btnMainIncrease = (Button) findViewById(R.id.btnMainIncrease);

        mHandler = new SendMessageHandler(tvBackValue); // 2. 핸들러 객체를 사용했을때는 필요없음

        BackThread thread = new BackThread();
        thread.setDaemon(true);
        thread.start();

        btnMainIncrease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mainValue++;
                tvMainValue.setText("MainValue: " + mainValue);
            }
        });
    }

    class BackThread extends Thread {
        @Override
        public void run() {
            //super.run();
            while(true) {

                backValue++;

                Message msg = mHandler.obtainMessage();

                //mHandler.sendEmptyMessage(0);

                msg.what = 0;
                msg.arg1 = backValue;
                msg.obj = tvBackValue; // View 객체도 메시지로 전달

                mHandler.sendMessage(msg);

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
    // 1. 내부 클래스 사용했을때
    class SendMessageHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            Log.d("MYTEST", "msg.what: "+msg.what);

            if (msg.what == 0) {
                tvBackValue.setText("BackValue: " + backValue);
            }
        }
    }
    */

    /* 2. 핸들러 멤버객체를 사용했을때
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.d("MYTEST", "msg.what: "+msg.what);

            if (msg.what == 0) {
                tvBackValue.setText("BackValue: " + backValue);
            }
        }
    };*/
}

3. SendMessageHandler.java
package com.example.falcon.mythreadtest1;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
/**
 * Created by falcon on 2016-05-09.
 */
// 3. 외부 클래스 사용했을때
public class SendMessageHandler extends Handler {

    TextView tvBackValue;

    public SendMessageHandler(TextView tvBackValue) {
        // TextView 객체를 메시지로 받지 않고
        // 핸들러 객체 생성시 TextView 객체를 받고 전역변수로 대입함.
        // 메시지로 받는 경우에는 필요없음.
        this.tvBackValue = tvBackValue;
    }

    @Override
    public void handleMessage(Message msg) {

        Log.d("MYTEST", "msg.what: "+msg.what);

        if (msg.what == 0) {
            //tvBackValue.setText("BackValue: " + msg.arg1);
            TextView textView = (TextView) msg.obj; // TextView 객체를 메시지로 받음
            textView.setText("BackValue: " + msg.arg1);
        }
    }
}

* 실행결과

댓글 없음 :

댓글 쓰기