关于定时器的实现,我们可以有三种实现方式
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();@Overrideprotected 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);    }}

}

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

更多相关文章

  1. Android(安卓)View之基础介绍(Android开发艺术探索)
  2. android 预装第三方apk的方法
  3. unity3d android真机测试的2种方法
  4. Android(安卓)CTS测试修改测试结果和调试方法
  5. Android性能分析工具--Android(安卓)Monitor
  6. Android项目复盘3
  7. Android中View跟随手指滑动效果的实例代码
  8. runOnUiThread()方法
  9. Android欢迎界面的创建方法

随机推荐

  1. Android
  2. Android(安卓)获取本机号码
  3. 谈谈Android(安卓)Activity的生命周期管
  4. android 取消Title 头部标题栏
  5. Android(安卓)Studio设置apk文件名
  6. This Android(安卓)SDK requires Android
  7. oauth点击授权之后,不Callback到指定url
  8. Android开发便签2:Activity的生命周期
  9. [GeoWay]android用于打开各种文件的inten
  10. Android引导页面去除白屏