由於經常會使用 Timer 來做事情,所以將每秒被重複調用的方法記錄下來,方便將來使用。
Handler Count Down 每秒調用的程式 |
- 操作系統:Windows 7 64-bit 版本
- 開發環境:Android Studio 4.0.1 版本
- 原程式:C:\Development\Development_Android\Android_Project\DIY-Android-009-18 Handler 1sTimer
- 程式:C:\Development\Development_Android\Android_Project\ DIY-Android-009-18 Handler 1sTimer
Thread 線程每秒被重複調用範例:
new Thread(new Runnable() { @Override public void run() { while (true) { // write code System.out.println(duration); duration--; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); |
Timer,TimerTask 每秒被重複調用一次範例:
Timer timer = new Timer(); TimerTask t = new TimerTask() { @Override public void run() { System.out.println(duration); duration--; } }; timer.scheduleAtFixedRate(t,1000,1000); |
Count Down Timer 每秒被重複調用一次範例:
new CountDownTimer(10000, 1000) { public void onTick(long millisUntilFinished) { // write code mtv_text.setText("Seconds remaining: " + millisUntilFinished / 1000); }
public void onFinish() { mtv_text.setText("Counter Down Finished"); } }.start(); |
Handler 每秒被重複調用一次範例:
public class MainActivity extends AppCompatActivity {
private TextView mtv_text; private Handler countDownTimer; private Runnable runnable; private int duration = 10;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mtv_text = (TextView) findViewById(R.id.tv_text);
countDownTimer = new Handler(Looper.getMainLooper()); runnable=new Runnable() { @Override public void run() { mtv_text.setText("Count Down Timer Per Second \n" + duration +" second"); duration--; countDownTimer.postDelayed(this,1000); } };
countDownTimer.post(runnable); }
} |
沒有留言:
張貼留言