activity_main.xml中的代码
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
>
android:id="@+id/mytime"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textColor="@android:color/black"
android:textSize="36sp"/>
MainActivity.java主文件中的代码
package com.example.time;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int msgKey1 = 1;
private TextView mTime;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTime = (TextView) findViewById(R.id.mytime);
new TimeThread().start();
}
public class TimeThread extends Thread {
@Override
public void run () {
do {
try {
Thread.sleep(1000);
Message msg = new Message();
msg.what = msgKey1;
mHandler.sendMessage(msg);
}
catch (InterruptedException e) {
e.printStackTrace();
}
} while(true);
}
}
private Handler mHandler = new Handler() {
@Override
public void handleMessage (Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case msgKey1:
//获取分钟数
long sysTime = System.currentTimeMillis();
String mmtime = (String) DateFormat.format("mm", sysTime);
int i = Integer.parseInt(mmtime);
//倒计时
SimpleDateFormat sdfStopTime = new SimpleDateFormat("mm:ss", Locale.ENGLISH);
if(i < 30){
String newStoptime = sdfStopTime.format(new Date(30 * 60 * 1000 - System.currentTimeMillis() ));
mTime.setText("倒计时:"+newStoptime);
break;
}else{
String newStoptime = sdfStopTime.format(new Date(60 * 60 * 1000 - System.currentTimeMillis() ));
mTime.setText("倒计时:"+newStoptime);
break;
}
default:
break;
}
}
};
}