본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/Thread

Android Studio Thread 2

by 차누감 2019. 9. 19.

0.5초마다 시간을 Toast로 띄우는 예제

먼저 화면을 디자인 하자

activity_main.xml 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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:padding="16dp"
    tools:context=".MainActivity">
 
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="현재시간 출력"
        android:onClick="clickBtn"/>
 
 
</RelativeLayout>
 
 

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
 
 
 
 
public class MainActivity extends AppCompatActivity {
 
    MyThread thread;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    //화면이 보이면 발동하는 메소드
    @Override
    protected void onStart() {
        super.onStart();
    }
 
    @Override
    protected void onResume() {
        super.onResume();
    }
 
    //이 액티비티가 화면에서 안보이기 시작할때 자동 실행
    @Override
    protected void onPause() {
        super.onPause();
    }
 
    //이 액티비티가 아예 화면에서 안보이면
    @Override
    protected void onStop() {
        if(thread!=null) thread.stopThread(); // 만약 뒤로가기에만 스레드 정지가 있으면 홈버튼 누르면 Toast메세지는 계속 뜬다. 그걸 대비
        super.onStop();
    }
 
    //이 액티비티가 메모리에 없어지면
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
 
    //뒤로가기 버튼을 눌렀을 때 발동하는 메소드
    @Override
    public void onBackPressed() {
        //Thread 멈추기!! - run method를 끝내면 스레드가 종료됨
        //이 예제에서는 run메소드 안에 while문에 의해 무한 반복중이라서..
        //while을 break해야 run메소드가 종료됨.
        if(thread!=null) thread.stopThread(); //if 조건문을 한 것은 만약 사용자가 버튼을 안누르고 바로 뒤로가기를 눌렀을 경우 대비
        //버튼을 눌러야 thread를 생성하므로
 
        super.onBackPressed();
    }
 
    public void clickBtn(View view) {
        //5초에 한번씩 현재시간을 Toast로 출력
        thread= new MyThread();
        thread.start();
 
    }//clickBtn() ..
 
    //이너 클래스
    class MyThread extends Thread{
 
        boolean isRun=true;
        @Override
        public void run() {
            while (isRun){
                //현재시간
                Date now= new Date();
                final String s=now.toString();
 
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
                    }
                });
 
                //5초 간격 지연
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {e.printStackTrace();}
 
            }//while
        }// run() ..
 
        void stopThread(){
            isRun=false;
        }
 
 
    }//MyThread class ..
}//MainActivity class ..
 
 
 

<실행화면>

댓글