Timer myTimer; myTimer = new Timer(); myTimer.schedule(new TimerTask() { public void run() { // Do some thing } }, 0, 1000);
myTimer.cancel();
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/txtResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="56dp" android:text="result" /> </RelativeLayout>
package com.myapp; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; import android.os.Bundle; import android.widget.TextView; import android.app.Activity; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Timer myTimer; myTimer = new Timer(); myTimer.schedule(new TimerTask() { public void run() { timerTick(); } }, 0, 1000); } private void timerTick() { this.runOnUiThread(doTask); } private Runnable doTask = new Runnable() { public void run() { // TODO Auto-generated method stub // Current Date Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formattedDate = df.format(c.getTime()); // txtResult TextView result = (TextView) findViewById(R.id.txtResult); result.setText(" Current : " + formattedDate); } }; }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท