android的Handle计时器实现代码
解决方法:
1、activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/root"
tools:context="com.example.ff.MainActivity" >
<TextView
android:id="@+id/txtTimer"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:text="当前时间: 00:00:00" />
<Button
android:id="@+id/btnBegin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/txtTimer"
android:layout_below="@+id/txtTimer"
android:layout_marginLeft="49dp"
android:layout_marginTop="26dp"
android:text="开始" />
<Button
android:id="@+id/btnEnd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/btnBegin"
android:layout_alignBottom="@+id/btnBegin"
android:layout_marginLeft="37dp"
android:layout_toRightOf="@+id/btnBegin"
android:text="停止" />
</RelativeLayout>
2、MainActivity.java
package com.example.ff;
import java.sql.Time;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button btnBegin;
Button btnEnd;
TextView txtTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnBegin = (Button) findViewById(R.id.btnBegin);
btnEnd = (Button) findViewById(R.id.btnEnd);
txtTimer = (TextView) findViewById(R.id.txtTimer);
btnBegin.setOnClickListener(listenerBegin);
btnEnd.setOnClickListener(listenerEnd);
}
//实例化Handle对象
Handler handler = new Handler();
//操作的线程
Runnable updateThread = new Runnable(){
@Override
public void run() {
Log.i("Handle", new Time(System.currentTimeMillis()).toString());
//更新界面上的时间
txtTimer.setText("当前时间是:" + new Time(System.currentTimeMillis()));
//1秒钟后,再加一个线程到队列中
handler.postDelayed(updateThread, 1000);
}
};
//开始按钮
View.OnClickListener listenerBegin = new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Handle",new Time(System.currentTimeMillis()).toString());
//往队列中放入第一个线程
handler.post(updateThread);
}
};
//结束按钮
View.OnClickListener listenerEnd = new View.OnClickListener() {
@Override
public void onClick(View v) {
//结束整个队列的运行
handler.removeCallbacks(updateThread);
}
};
}