-
Notifications
You must be signed in to change notification settings - Fork 14
/
Timer.java
105 lines (82 loc) · 2.8 KB
/
Timer.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
105
package kr.pe.burt.android.lib.androidchannel;
import android.os.Message;
/**
* Created by burt on 15. 9. 23..
*/
public class Timer {
private final int START_TIMER = 0;
private final int STOP_TIMER = 1;
private AndroidChannel androidChannel;
private int interval=0;
private OnTimer onTimer;
volatile boolean loop = false;
public Timer(int interval, OnTimer onTimer) {
this.interval = (interval < 0) ? (interval*-1) : (interval);
this.onTimer = onTimer;
androidChannel = new AndroidChannel(new AndroidChannel.UiCallback() {
@Override
public boolean handleUiMessage(Message msg) {
Timer.this.onTimer.onTime(Timer.this);
return false;
}
}, new AndroidChannel.WorkerCallback() {
Thread jobThread = null;
@Override
public boolean handleWorkerMessage(Message msg) {
switch (msg.what) {
case START_TIMER:
loop = true;
break;
case STOP_TIMER:
loop = false;
jobThread = null;
break;
}
if(msg.what == START_TIMER && jobThread == null) {
jobThread = new Thread(new Runnable() {
@Override
public void run() {
while (loop) {
try {
Thread.sleep(Timer.this.interval);
Message msg = androidChannel.toUI().obtainMessage();
androidChannel.toUI().sendMessage(msg);
} catch (InterruptedException e) {
}
}
}
});
}
switch (msg.what) {
case START_TIMER:
loop = true;
jobThread.start();
break;
case STOP_TIMER:
loop = false;
jobThread = null;
break;
}
return false;
}
});
}
public void start() {
androidChannel.toWorker().sendEmptyMessage(START_TIMER);
}
public void stop() {
androidChannel.toWorker().sendEmptyMessage(STOP_TIMER);
}
public void resetInterval(int interval) {
this.interval = interval;
}
public int getInterval() {
return interval;
}
public boolean isAlive() {
return loop;
}
public interface OnTimer {
void onTime(Timer timer);
}
}