App/Android
Simple Current Time Example
selfstarter
2020. 3. 26. 14:17
Simple Current Time Example
It is simple better than using thread
package com.tmoney.taxi.sendmessagedelayed;
import androidx.appcompat.app.AppCompatActivity;
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 java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final int MESSAGE_TIMER_START = 1000;
Handler timerHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
long now = System.currentTimeMillis();
Date date = new Date(now);
SimpleDateFormat simpleDate = new SimpleDateFormat("hh:mm aa");
String currentTime = simpleDate.format(date);
clockText.setText(currentTime);
Log.d("TEST_LOG", "currentTime:"+currentTime);
sendEmptyMessageDelayed(0, MESSAGE_TIMER_START);
}
};
private TextView clockText;
private Button startBtn;
private Button endBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clockText = findViewById(R.id.text);
startBtn = findViewById(R.id.start);
endBtn = findViewById(R.id.end);
}
public void startClick(View v) {
timerHandler.sendEmptyMessage(0);
}
public void endClick(View v) {
timerHandler.removeMessages(0);
}
}