timetask = new TimerTask() { public void run() { handler.post(new Runnable() { public void run() { } }); }}; timer.schedule(timetask, 0, 1000); // Every 1 second
<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" > <Button android:id="@+id/btnStart" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Start" /> <Button android:id="@+id/btnStop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/btnStart" android:text="Stop" /> <TextView android:id="@+id/txtResult" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/btnStop" android:layout_centerHorizontal="true" android:layout_marginTop="98dp" 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.os.Handler; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.app.Activity; public class MainActivity extends Activity { Handler handler = new Handler(); Timer timer = new Timer(); TimerTask timetask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // btnStart final Button btnStart = (Button) findViewById(R.id.btnStart); // Perform action on click btnStart.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub doTask(); } }); // btnStop final Button btnStop = (Button) findViewById(R.id.btnStop); // Perform action on click btnStop.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub stopTask(); } }); } public void doTask(){ timetask = new TimerTask() { public void run() { handler.post(new Runnable() { public void run() { 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("TimeTask runing... Current : " + formattedDate); } }); }}; timer.schedule(timetask, 0, 1000); // Every 1 second } public void stopTask(){ if(timetask != null) { timetask.cancel(); TextView result = (TextView) findViewById(R.id.txtResult); result.setText("TimeTask stop."); } } }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท