안드로이드

 

 

 

class MainActivity

package org.androidtown.mythread;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final String TAG="MainActivity";

    TextView textView;
    RequestThead thead;
   // ResponseHandler responseHandler ;

    Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };



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

        textView=(TextView)findViewById(R.id.textView);
    }


    public void onButton1Clicked(View v){
        Log.d(TAG, "첫번째 버튼 클릭됨 : " );

        textView.setText("스레드 시작함");

        if(thead!=null){
            thead.interrupt();
            thead=null;
        }

        thead =new RequestThead();
        thead.setDaemon(true);
        thead.start();

        Toast.makeText(getApplicationContext(), "스레드 시작됨", Toast.LENGTH_SHORT).show();
    }


    class RequestThead extends Thread{
        public void run(){
            for(int i=0; i <=100; i++){
                println("#" + i + " : 호출됨 handler.post ");

                try{
                    Thread.sleep(500);
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        public void println(final String data){
            Log.d(TAG, data);

            //에러 발생
            //textView.setText(data);
           /* Message message=responseHandler.obtainMessage();
            //번들로 상요에 데이터 전달.
            Bundle bundle=new Bundle();
            bundle.putString("data", data);
            message.setData(bundle);

            responseHandler.sendMessage(message);*/

            // 핸들러로 자동으로 넘어간다.
            // 메소드 안에서 는 UI 접근이 가능하다.
            handler.post(new Runnable() {
                @Override
                public void run() {
                    textView.setText(data);
                }
            });
        }
    }

/*
    class ResponseHandler extends Handler{

        //UI 에 접근할 수 있는 메소드
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle=msg.getData();
            String data =bundle.getString("data");

            textView.setText(data);
        }
    }*/


    // 2. 두번째 핸들러 사용법
   /* private int secondNum;
    private boolean isThread=true;

    class NewThread extends Thread{

        @Override
        public void run() {
            while (isThread){
                secondNum++;
                Log.i(TAG, "secondNum in thread :" + secondNum);

                try {
                    Thread.sleep(500);
                }catch (Exception e){
                    e.printStackTrace();
                }

                Message msg =new Message();
                msg=Message.obtain();
                msg.what=0;
                msg.arg1=0;
                msg.arg2=0;
                msg.obj=null;
                handler.sendMessage(msg);
                handler.sendEmptyMessage(0);
            }
        }
    }

    Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==0){
                textView.setText(secondNum);
            }
        }
    };
*/


}

 

 

R.layout.activity_main

 

<?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:id="@+id/activity_main"
    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="org.androidtown.mythread.MainActivity">

    <Button
        android:text="스레드시작"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/button"
        android:onClick="onButton1Clicked"
        />

    <TextView
        android:text="결과출력"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="76dp"
        android:id="@+id/textView"
        android:textSize="30sp" />


</RelativeLayout>

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

건강하게 오래사는 것은 모든 사람의 소망이다. 인삼, 녹용, 호르몬제. 각종 자연 식품 등을 다투어 가며 구입하는 것도 모두 장수하려는 소망 때문이다. 그러나 가장 확실한 것은 역시 올바른 식생활, 규칙적 운동, 건전한 습관 등이다. - New Life 편집부

댓글 ( 4)

댓글 남기기

작성