Android定时器之Handler的postDelyed方法
16lz
2021-01-26
关于定时器的实现,我们可以有三种实现方式
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); }}
}
最后来看下运行结果,这样一个随时间变化的时间文本就形成了
更多相关文章
- Android(安卓)View之基础介绍(Android开发艺术探索)
- android 预装第三方apk的方法
- unity3d android真机测试的2种方法
- Android(安卓)CTS测试修改测试结果和调试方法
- Android性能分析工具--Android(安卓)Monitor
- Android项目复盘3
- Android中View跟随手指滑动效果的实例代码
- runOnUiThread()方法
- Android欢迎界面的创建方法