在layout文件中添加一个文本框
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/timerView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textSize="60sp" /> </LinearLayout>
在对应的java文件中添加如下代码
package com.example.lastgps; import android.os.Handler; import android.os.Message; import java.util.Timer; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.text.DecimalFormat; import java.util.TimerTask; public class time extends AppCompatActivity { private TextView timerView; private TextView runspeed; private long baseTimer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_time); time.this.baseTimer = SystemClock.elapsedRealtime(); timerView = (TextView) this.findViewById(R.id.timerView); final Handler startTimehandler = new Handler() { public void handleMessage(android.os.Message msg) { if (null != timerView) { timerView.setText((String) msg.obj); } } }; new Timer("开机计时器").scheduleAtFixedRate(new TimerTask() { @Override public void run() { int time = (int) ((SystemClock.elapsedRealtime() - time.this.baseTimer) / 1000); String hh = new DecimalFormat("00").format(time / 3600); String mm = new DecimalFormat("00").format(time % 3600 / 60); String ss = new DecimalFormat("00").format(time % 60); String timeFormat = new String(hh + ":" + mm + ":" + ss); Message msg = new Message(); msg.obj = timeFormat; startTimehandler.sendMessage(msg); } }, 0, 1000L); } }
运行结果如下