Android定时器之Handler的postDelyed方法

关于定时器的实现,我们可以有三种实现方式
handler+thread,Timer+TimerTask,也可以用handler的postDelyed方法,当然也有上一篇我们说过的倒计时定时器CountDownTimer.
这一篇主要说一下handler的postDelyed方法,看代码

首先是布局文件,只有一个TextView用于显示系统时间

<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"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="当前系统时间" />

</RelativeLayout>

接下来是MainActivity类

“`
public class MainActivity extends Activity {

private TextView mTime;

//定义Handler对象
private Handler mHandler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mTime = (TextView) findViewById(R.id.time);

    //1s后执行Runnable对象的run方法
    mHandler.postDelayed(new MyRunnable(),1000);

}

/**
 * 自定义Runnable对象
 * @author maoxf
 *
 */
class MyRunnable implements Runnable{

    @Override
    public void run() {
        //定义时间格式,获取系统时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String time = format.format(date);
        mTime.setText(time);
        //每隔1s执行一次Run方法
        mHandler.postDelayed(this, 1000);
    }
}

}

最后来看下运行结果,这样一个随时间变化的时间文本就形成了
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值