Android(Java)
[Java] Thread 상속 클래스 타이머 예제
삽질중
2024. 1. 12. 11:05
TimerThread 클래스
- interface 통해서 Activity 로 초를 전송한다.
import android.util.Log;
interface TimerThreadDelegate {
void setTime(String time);
}
public class TimerThread extends Thread {
TimerThreadDelegate delegate;
int second = 0;
public void run() {
while (true) {
second++;
try {
// 스레드에게 수행시킬 동작들 구현
Thread.sleep(1000); // 1초간 Thread를 잠재운다
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
Log.i("경과된 시간 : ", Integer.toString(second));
delegate.setTime(Integer.toString(second));
}
Log.d("Therad End", "스레드 종료");
}
}
Activity 클래스
public class IntentActivity extends AppCompatActivity implements TimerThreadDelegate {
TimerThread timerThread;
public void onTimerStart(View v) {
timerThread = new TimerThread();
timerThread.delegate = this;
timerThread.start();
}
public void onTimerStop(View v) {
timerThread.interrupt();
}
// Interface Delegate 함수
@Override
public void setTime(String time) {
Log.d("Timer", time + "초");
// UI 갱신을 위해 UI 스레드 사용
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView) findViewById(R.id.textSecond);
textView.setText(time + "초");
}
});
}
}