앱 만들기/안드로이드

안드로이드의 기술 # Handler 타이머 구현하기- 전체 소스

나도 처음이야 2020. 11. 10.

 

티스토리에 댓글로 전체 소스를 요청하신 분이 계서서 공유드립니다.

핸들러 타이머의 테스트 예제 임을 감안하시고 보시면 좋겠습니다. 당연히 버그나 이상 동작이 있을 수 있습니다.

오늘도 티스토리를 찾아주셔서 감사드립니다. :)

 

핸들러 타이머 구현 소스

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
105
106
107
108
109
110
111
112
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
 
public class MainActivity extends AppCompatActivity {
 
    int timerTime = 30// 30 초를 디폴트로.
    // Timer 를 처리해주는 핸들러
    TimerHandler timer;
    // 시작, 중지 버튼
    Button button, button2;
    // 시간을 표시
    TextView textView;
    boolean isRunning = true;
 
    int status = 0 ; // 0:정지, 1:시작, 2:일시정지
 
    public void onStartPauseButton(View view){
        // 타이머 시작!
        if(status == 0// 정지 상태 라면, 재 시작.
        {
            status = 1;
            timer.sendEmptyMessage(0);
            button.setText("일시정지");
 
        }else if(status == 1){ // 타이머 동작 중이라면, 일시 정지 시키기
 
            status = 0;
            // 1번 메시지를 던진다.
            timer.sendEmptyMessage(1);
            button.setText("시작");
        }
    }
 
    public void onStop(View view){
            status = 0;
            timer.sendEmptyMessage(2);
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
 
        button = (Button)findViewById(R.id.button);
        button2 = (Button)findViewById(R.id.button2);
        textView = (TextView)findViewById(R.id.textView);
 
        timer = new TimerHandler();
 
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer != null)
            timer.removeMessages(0);
        isRunning = false;
    }
 
    // 타이머 핸들러 클래스.
    class TimerHandler extends Handler{
 
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
 
            switch (msg.what){
                case 0// 시작 하기
                        if (timerTime == 0) {
                            textView.setText("Timer : " + timerTime);
                            removeMessages(0);
                            break;
                        }
                        // Main Thread 가 쉴때 Main Thread 가 실행하기에
                        // 오래걸리는 작업은 하면 안된다. (무한 루프 문 etc.. 은 쓰레드로)
                        textView.setText("Timer : " + timerTime--);
                        sendEmptyMessageDelayed(01000);
                        Log.d("test""msg.what:0 time = " + timerTime);
 
                    break;
 
                case 1//일시 정지
                    removeMessages(0); // 타이머 메시지 삭제
                    textView.setText("Timer : " + timerTime); // 현재 시간을 표시.
                    Log.d("test" , "msg.what:1 time = " + timerTime);
 
                    break;
 
                case 2// 정지 후 타이머 초기화
                    removeMessages(0); // 타이머 메시지 삭제
                    timerTime = 30// 타이머 초기화
                    textView.setText("Timer : " + timerTime);
                    button.setText("시작");
                    Log.d("test" , "msg.what:2 time = " + timerTime);
                    break;
 
 
            }
 
        }
    }
 
}
cs

 

화면 구성 XML

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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#72E1DEDE"
        android:gravity="center"
        android:text="Timer :"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textSize="50sp"
        android:textStyle="bold" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="30dp"
        android:layout_weight="1"
        android:onClick="onStartPauseButton"
        android:text="시작"
        android:textAppearance="@style/TextAppearance.AppCompat.Large" />
 
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:onClick="onStop"
        android:text="정지"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textSize="22sp" />
</LinearLayout>
cs

 

반응형

댓글